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 |
---|---|---|---|---|---|---|---|---|
542 | Hello guys welcome song video mein ceo sudhir wa problem hai koi 80 tricks let's get started se given in the remix marathi to the distance of the nearest to for its a distance between two stations as one selected in this particular example pe thadi example all the self Baitha Values Us Have A Distance Zero Baitha Values Us Have A Distance Zero Baitha Values Us Have A Distance Zero Vikas Dead Cells Us Where To Find A Distance From 0001 Bajirao Have A Distance Of 0 Report Subscribe Now To Minimum Distance From 0 To 100 Years And Will Give A Distance Of One From The President Of India Example In The World Pacific Description Colorful Distance of World Records St. Pimple Continues But Will Return to Distance of Wave the Last Bottom Slip Series Top Level Which Gives Evidence of One From the Nearest to the White Mask and Neither Bottom Corner One Should Say Never 08 Will Also Have Minimum Distance 140 Quite Difficult One Which Aims And This Particular Question Destroys Everything In Just One And It's Gautam Ne But Unfortunately Due To Exist So It's Proper Ideal Of Neighbors And Good Tightening Effect Pawan Some Cases Will Have To See The Next To Subscribe The Distance From the nearest to beautiful distance from this particular word ok no problem solve this particular problem to it's time to understand you win the great destruction caused this will help you not think so much to find nearest distance from subscribe mode on this is the chatting To find the nearest distance of all notes from this particular Video subscribe Video plz subscribe Channel and subscribe the [ subscribe Channel and subscribe the [ subscribe Channel and subscribe the Subscribe Now He is Visited Are Key Form Hai Jhala Distance Adventures Water Notification First Weekend Mark All The Avengers Minus One Which Were Not Visited To 151 Updates Amazon Final Distance Sanam Status Report Handed Over The Mode Of One Right Initially Latest Quality Decoration Relics Of Jesus Level Number 1098 Snacks Near His Neighbors Side In The Morning To Find A Distance Of Sixteen Years Never Stop All The Not Actually Supervision Years Never Stop And Entry Impatient What Will Push 2.3 Voices in South Push 2.3 Voices in South Push 2.3 Voices in South Willpower Namak Suryavanshi Unconfirmed 243 Leather Facility Withdrawal Can Make Its Existence S 100 1000 Just Be The Next Level of The Who Is The Setting Job Starting Over 200 Till 2.30 Just Neighbors of Women Rights to Till 2.30 Just Neighbors of Women Rights to Till 2.30 Just Neighbors of Women Rights to Act Will Be Given At Some Will Put Water Levels One In A Video 128 Bit With You And What Will U Will Travel Alone To Achieve Snakes In The Clubhouse to-let Sunil Check Snakes In The Clubhouse to-let Sunil Check Snakes In The Clubhouse to-let Sunil Check The Number Of 2025 Will Put The Interactive Withdrawal 512 22.58 2100000 But For His Withdrawal 512 22.58 2100000 But For His Withdrawal 512 22.58 2100000 But For His Neighbors And Three You Acid On Second Ok Body Visit Birth And Investigative Agencies And Five And Three Already Hasm Value Which Is Not - Banoga Already Hasm Value Which Is Not - Banoga Already Hasm Value Which Is Not - Banoga Show Will Help You Avoid Subha Not Post Any Person In This Powerful Similarly For Three Winters Pocket OLX Never Supported For Pune Pred Election The Dreams and Tiered Second Series Setting Versus 2.30 Level and You Can See Hidden From Which Second Series Setting Versus 2.30 Level and You Can See Hidden From Which Second Series Setting Versus 2.30 Level and You Can See Hidden From Which is the Water Level Indicator Minimum Distance from the Thing Which Was 10000000000 Example Suppose I Want to Find the Distance from Near This After Subset with Just One Particular Drought Joe Hair Oil To Concept Is Time But Interview Multiple After 10 Minutes This To Find The Nearest S0 For Every Sale Ok Person Just Find The Best 05 Gondvi The Same But Instead Of One Lord Uses Social Aspect Member Answer Matrix Setting On To Do Galaxy User Name Contact Lens Depend Sarpanch And User Input Device To Vacation Image - 100th Comments Dividend - Vacation Image - 100th Comments Dividend - Vacation Image - 100th Comments Dividend - - Way All Notes 100 David - 121 - Way All Notes 100 David - 121 - Way All Notes 100 David - 121 Ki And All The Notes Settle Zero Two Have A Distance From 0001 Number Valve This Same Which Process User Possible Pushya Crops Sweater This code these pictures strong oil book points in the youtube like you data structure and good pushya ka majabar indicating this particular selected in the food alphabet next month to push business month voice mail setting mode my friend I am starting notes and pushing me dim pod this Vitamin Coordinator of Zero Command Questions Asked Next Is Particular Being Discerning Coordinator of Way Today I Will Request Inductive Most Lord Is Traveling Merchants Who Will Do I Will Stop This Element Drafting Element I Will OK Ask Its Neighbors To What Is The Number Forward 40 Marketing Politicizing This Particular Has Bigg Boss Not Been Visited 140 Have Been For Me But Its Top Neighbors Not Even Be Reduced It's True Love Never Avoid - Jaswant Gharu On Thursday I Will Avoid - Jaswant Gharu On Thursday I Will Avoid - Jaswant Gharu On Thursday I Will Mark The Distance 1000 Answered Questions Withdrawal 0.000 From The Year Award Will Be Cheese Neighbors Unknown Visitors Vacancy Date Planet To Neighbors But This Particular And This Particular Dependent Thought Actually Not Visited Record This Value - One In The Answer Visited Record This Value - One In The Answer Visited Record This Value - One In The Answer Matric Shiva Will Replace Value - 151 D0 Matric Shiva Will Replace Value - 151 D0 Matric Shiva Will Replace Value - 151 D0 Q0 S0 U0 Cotton Incomplete This Particular Topic Video VIDEO - 110 CHANNEL MARKET VALUE AND 1000 PLUS MINUS SIGN MARKET VALUE IS UNABLE TO SHARE WORD ACCORDING NET PROFIT SHOW DAD LEVEL-2 WORK TO OK GOOD NIGHT LOVE YOU WHAT IS THIS LEVEL-2 WORK TO OK GOOD NIGHT LOVE YOU WHAT IS THIS LEVEL-2 WORK TO OK GOOD NIGHT LOVE YOU WHAT IS THIS ELEMENT WHICH ONE WILL NEVER [MUSIC] NEVER EXIST FROM Failures Solid This Video Channel Minus One Side Change 2012 Wood Gwalior Print Vikas Turn Fancy Dress Per Kilo And This Plant Talking About The Natives Having A Distance Of Two From The Nearest Zero Friends Were Made Value Toothpaste And Will Confirm In The Giver What Is Water Awards Code to Communities Where Put You and Friends Will Take 021 More 08 2013 Dates in This World Who Liberates Ne 2009 23.22 Command2ne 23.22 Command2ne 23.22 Command2ne Aur Tu Kahan 2000s Particulars 12112 Tips Number Plate Minutes Clarification of the Green Color Ad 348 So No One Can See the Greatest 200 And Minus One So President Should Stop Ne Year Old Positive And What Is A Flu Minus One Mid Valley OnePlus One But Will Need A Two And Subscribe Do n't Forget To Subscribe Our YouTube Channel Avoid - 1 Avoid - 1 Avoid - 1 Dam Of Your Seniors So It's Members Have Also Been Hidden Things - Bante Have Also Been Hidden Things - Bante Have Also Been Hidden Things - Bante Software Computer Depression And During Samiksya To Internet Consist Of Then Minimum Distance Of Any Salute From The Nearest Must Try Doob Co Twist Solution Nagpur Soft Coding System For Singh20 Different Youtube And Quite Sure I Will Give The Answer To all its perimeter number subscribe meter call on this number - 1 meter call on this number - 1 meter call on this number - 1 phone no of the spot where lord wavel hydrate open what is my water harvesting mode to my starting muscle previous 051 in answer 80 dock limited distance from 4070 orient i20 size plus point J2 Pro Chirva 's Saudagar Singh Do You Certificate Is 's Saudagar Singh Do You Certificate Is 's Saudagar Singh Do You Certificate Is Minutes Of IPTA Is Equal To Receive New Updates York Post In Goals And Objectives On Asking A Professional Well-Marked Specific - The Amazing OK Well-Marked Specific - The Amazing OK Well-Marked Specific - The Amazing OK Admission Example And Tried To Learn The Mera Tab Day Obliged To Water Where And When The Giver Institute Arvind Setting Year In Certificates Will Be I N G Super School Will Take You To Front End Milk Powder Sugar Lee The Forest Leg This Android Jelly nawya.in Sugar To All Its Neighbors Were Not Visited Dad Tips Validity Subscribe 120 Days That Feature 6 Kids Of It's Nothing Features Painter Inch Width Size Of The American Kids Who Didn't Withdraw Champ Validity Kinda Loose Stake In Name In 10m For Morning And Jewelry You Will 2000 I Will Not give any need not waste your time limit for be id am id not withdraw all the best way give the nearest 0 already nearest distance from rest do Shubhesh Owinoy tied in this time to what came into being in the check video channel it is simply that A This Check Is It Is Equal To Minus One Need Not Withdraw Resignation Is Remedy - After What Need Not Withdraw Resignation Is Remedy - After What Need Not Withdraw Resignation Is Remedy - After What Doing For The Same Do Itself And Declared While Being Id As Current Silver Jubilee Hall Suitable Check For Its Neighbors Festival Day Take Off And Value Saver Mode Off Playlist One Chapter - 110G Plus Mode Off Playlist One Chapter - 110G Plus Mode Off Playlist One Chapter - 110G Plus One Time Job - Let Me To Regulate Milk One Time Job - Let Me To Regulate Milk One Time Job - Let Me To Regulate Milk Duggal Minute Copy Paste Twist Hotspot Times End Within Ther Is Superhit Time But B2C Mail Check Width Plus One Ok End Next Time Will Check Point - Next Time Mirchi One Valve Point - Next Time Mirchi One Valve Point - Next Time Mirchi One Valve Job Laxman Next Time You Will Check To DJ - Sid Love On DJ - Sid Love On DJ - Sid Love On A Doctor But Man Left Right All The Four Ne Mobile Top Down For Right And Never Show This To Have No Words Decided To Connect With To Do The Why Sleep Subscribe My Channel And Also Water With The Answer Will Be Plus B Plus Top Subscribe To A Technical Colleges Depending Life This Is One Knack Tweet A Chief Guest Lectures Last Volume Fast And The Subject Must - Element Subscribe I Safe Episodes With Answer In This Year And Its Leaders Pregnancy Alarm Set Fine Learning System Internships Accepted Accept Thank you for being the sentences in our eyes | 01 Matrix | 01-matrix | Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_.
The distance between two adjacent cells is `1`.
**Example 1:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Example 2:**
**Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\]
**Output:** \[\[0,0,0\],\[0,1,0\],\[1,2,1\]\]
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 104`
* `1 <= m * n <= 104`
* `mat[i][j]` is either `0` or `1`.
* There is at least one `0` in `mat`. | null | Array,Dynamic Programming,Breadth-First Search,Matrix | Medium | 550,2259 |
665 | hello guide line weak hot mean that they will discuss in nod in this question Thursday do subscribe my channel must subscribe button video do subscribe button more your and not supposed to give vent there video person chain more seen in liquid you are not being Increasingly Difficult Subscribe Suv Thursday Bihar Day Special Weather And Find Out The Only One Position Which Means To Change In The Middle Of Increasing Subscribe The - 12345 Topics Must Subscribe 409 Former Victims Officers Were Appointed Second 289 In This Special Position - 151 - Second 289 In This Special Position - 151 - Second 289 In This Special Position - 151 - Web Notifications subscribe The Amazing Value in between subscribe and subscribe the that perhaps this is the youth proof of subscribe the Video then subscribe to subscribe that and over flow of the intellect to his opposition length - to the Video then subscribe to the Page if you liked The Video then subscribe to subscribe this Video not धुंध वालू फ्रूम - मिदिंग Video not धुंध वालू फ्रूम - मिदिंग Video not धुंध वालू फ्रूम - मिदिंग मिद्गिंग पूशिणन नहीं मिद्गिंग पूशिणन नहीं मिद्गिंग पूशिणन नहीं रुद्रपुर नाशन टॉडे इंडेवी विद्रॉन इस पूशिणन रुद्रपुर नाशन टॉडे इंडेवी विद्रॉन इस पूशिणन रुद्रपुर नाशन टॉडे इंडेवी विद्रॉन इस पूशिणन नहीं - 151 अधेरे टो विद्रोन मूड आन नहीं - 151 अधेरे टो विद्रोन मूड आन नहीं - 151 अधेरे टो विद्रोन मूड आन इस बीच twitter The Amazing position it इस बीच twitter The Amazing position it इस बीच twitter The Amazing position it Surely the post on the Valv Veeravar on the subscribe coat election lad tride to run code | Non-decreasing Array | non-decreasing-array | Given an array `nums` with `n` integers, your task is to check if it could become non-decreasing by modifying **at most one element**.
We define an array is non-decreasing if `nums[i] <= nums[i + 1]` holds for every `i` (**0-based**) such that (`0 <= i <= n - 2`).
**Example 1:**
**Input:** nums = \[4,2,3\]
**Output:** true
**Explanation:** You could modify the first 4 to 1 to get a non-decreasing array.
**Example 2:**
**Input:** nums = \[4,2,1\]
**Output:** false
**Explanation:** You cannot get a non-decreasing array by modifying at most one element.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 104`
* `-105 <= nums[i] <= 105` | null | Array | Medium | 2205 |
456 | hi everyone today we are going to start with a little called question one three two pattern so you are given an array of n integers nums uh one three two pattern is a subsequence of three integers times I numbers J and the numbers K such that I is less than J is less than K and the announce I is less than numbers K less than numbers J written through if there is a 132 pattern in nums otherwise return false so let's see the example so you are given like a one two three four output is false because in this question K is a biggest index in I got three in indices and uh but the numbers J is a biggest number in three numbers so in this case uh input array is sorted so there is no way we can find the uh like a 132 pattern in input array that's why we should return false so let's see the example two so we are like a given one three one four two so if index I is pointing 1 and uh index J is pointing 4 and the index K is pointing um two in this case k is a biggest index and uh 4 is the biggest number so it's a 132 pattern so that's why output is true in this case okay so let me explain with this example so this is a true case if index I is pointing 1 and the J is pointing 4 and the K is pointing to in this case we should return true but so this is an easy case because three numbers are like an autojacent so but uh what if one is index zero and the three is index one in this case we also written true because if index I is pointing index 0 so yeah we meet uh one three two pattern so that's why we should return true but problem is how can we keep the current Max in the current minimum at the same time so to solve this question we use stack so every time we find the number um We compare current marks with current number and the current number is greater than current Max in that case I popped the current marks from stack and then continue compare again so yeah let's begin so first I find one uh in and but there is no numbers in stock so in this case I put one into stock one and also we calculate the minimum number so far so in this case one and then move next we find three and in this case three is greater than current Max in our case we pop one from stack and then our three to stack and also uh we need to calculate the current minimum so far and uh the numbers we found so far is one over three and the one is a smallest number so far so in this case I keep one as a minimum number and then move next and we find four and then compare the mark current marks three and the 4 is greater than three in that case we pop three from uh stack and the other four to um stuck and then calculates the current minimum so far so C1 is the smallest minimum number so we keep the one as a minimum number and then move next and we find two and uh compare the current marks so 2 is less than 4. so here is an interesting point so important point and so current number should be uh like a index k because uh this is a like a this number is located at the biggest index number in three numbers right because uh we already found like a four or one so this is a this should be a number with index k and so now K number is less than 4. and in this case Force should be a like a Place uh in at the index J right because we find the 4 after we find the index we find one right so that means this Max number should be a number at index J and then so that means minimum number should be a number at index I so if current number is less than Max number and a greater than minimum number actually we can we find like a 132 pattern so in this case we compare two with four and two is less than 4 and compare with a minimum number so 2 is a greater than one in this case we find the 132 pattern so that's why we should return true in this case yeah that is a basic idea to solve this question without being said let's get into the code okay so let's write the code once you understand the concept of this question it's not difficult so first of all initialize stack with empty array and uh internet is also current minimum with number at index 0. and start looping or n in nums and then start from index one because I initialize current minimum with a number in Excel here so after that wide stuck is has data and the current number is greater than or equal stock and the latest Max number in stock so -1 and the latest Max number in stock so -1 and the latest Max number in stock so -1 and uh zero because that we have a like a Max number and a minimum number in stock so zero is a Max number in that case uh we pop the number from stack after that if stuck has data and n is greater than stuck minus one so latest number in stock and uh compared with minimum number in the case um visually done two so because uh we continue pop if we meet this condition I mean stack has data and the current number is greater than or equal the current marks and uh once we finish the this wire and if stack has data which means uh stag has the larger number than current number so that's why if current number is greater than current minimum that means we find like a 132 pattern so that's why we should return true so after that stuck up end and the current number and the current minimum and I calculate current minimum equal mean current minimum versus current number after that we should return false yeah that's it so let me submit it yeah looks good and the time complexity of this solution should be order of n because I iterates through all numbers in input array and the space complexity is also order of n because potentially I have to put all numbers into stack so let me summarize step-by-step so let me summarize step-by-step so let me summarize step-by-step algorithm this is a step-by-step algorithm of 132 this is a step-by-step algorithm of 132 this is a step-by-step algorithm of 132 pattern step one interest stack and the minimum number with number at index zero step two start iterating and number one if stock has data compare a current number with a maximum number in stock if the current number is greater than greater or equal to the maximum number then pop it from stack continue until you don't meet the condition Step 2 if stack has data and the current number is greater than a minimum number in stock then return true three append the current number and the current minimum number to stack update the current minimum if current number is less than current minimum step 3 data false if you don't find the 160 pattern yeah that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question | 132 Pattern | 132-pattern | Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`.
Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Explanation:** There is no 132 pattern in the sequence.
**Example 2:**
**Input:** nums = \[3,1,4,2\]
**Output:** true
**Explanation:** There is a 132 pattern in the sequence: \[1, 4, 2\].
**Example 3:**
**Input:** nums = \[-1,3,2,0\]
**Output:** true
**Explanation:** There are three 132 patterns in the sequence: \[-1, 3, 2\], \[-1, 3, 0\] and \[-1, 2, 0\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 2 * 105`
* `-109 <= nums[i] <= 109` | null | Array,Binary Search,Stack,Monotonic Stack,Ordered Set | Medium | null |
1,046 | cool okay 10:46 last dumb way we have a 10:46 last dumb way we have a 10:46 last dumb way we have a collections of wild siege vodkas a positive integer way each time we choose to heaviest walks as fashion together suppose the stomach separate weights X Y with X is the Neko lesson why do we solve the smashes if X is you go to Y both times that Tori destroy FX is not equal to Y the stone of way excess Tori destroyed under stone of way why isn't has new weight y minus X the end there is at most one stone left we turn the weight of this stone but so if there's no stoner ok this seems pretty well W straight for it there's a so the number of songs is dirty so we can actually do to uh do this pretty quickly with some just proof for isn't you can do something like and cube type things or and square you I mean either way works if they're the number of stones is a lot more actually then you could I mean there's you can actually do it a man again but it just seems unnecessary for yeezy column of these constraints so I'm we're just arrived and cool yeah no just turn square solution maybe let me look up see shopping party cues for a second yeah not sure why do isn't one so yeah maybe like just five on there it's gonna use party cue just prism it's actually slightly easier to write for me but uh yeah well actually push something like that just print it out just making sure that I have ever correct okay that looks roughly right so this is a men's min-heap sound good point yeah or just min-heap sound good point yeah or just min-heap sound good point yeah or just kinda gated to get the maxi or heap we try again you should have an aggravated for it hmm so now we take them to heaviest items I guess there's more item to let's just use X by just using the language of the poem a she buys the bigger one so no typos destroyed okay so then you just push mmm the next one is even away and that's it okay what's okay I'm gonna actually just print this out because they actually okay but just step by step so we're getting better tougher check yep so it just matches two examples so that looks good and then the only other test I would write is just when you have two things that are the same I guess so that should return zero yep cool um yeah I'm yeah so just wait till you straight for a poem I mean there's a easy - I think I solved in a way that easy - I think I solved in a way that easy - I think I solved in a way that just died uh it's a little bit hammer e for and egos dirty bite everybody when you yeah when you look at you see a palm and see that you want to be peel and they get the min or max of something usually heap so or putting them in a / usually heap so or putting them in a / usually heap so or putting them in a / he provided you I probably the way to go end up thinking about it that way yeah I mean I think this is a very straightforward palm and depending on like as an interviewee you know it's okay is that nothing tricky I think it's okay as an interviewer I think the different variations on this some people might I'm I could see this being an interview form people might actually ask you to implement the heat maybe for example I haven't for me January I don't you know a lot of people to use whatever you know whatever a language comes what they want if they know about it then they should more than happy to use it and yeah I try simulated we were as much as possible and yeah I mean but generally I also let people go you know use Google to career search for language stuff because you know yeah that's how that's what real-life people that's how that's what real-life people that's how that's what real-life people do anyway so not a shame if it's not gonna ask you for random trivia | Last Stone Weight | max-consecutive-ones-iii | You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000` | One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on. | Array,Binary Search,Sliding Window,Prefix Sum | Medium | 340,424,485,487,2134 |
1,055 | hey everybody this is Larry this is me going to do the week two of the weekly premium challenge yep hit the like button hit the Subscribe button join me in the Discord let me know what you think about this poem I haven't done it before yay newcomer 10 55 shortest way to form string a subsequence of a strain is a new string that is formed from the original string by deleting some of the characters without disrupting the relative positions of the remaining characters Ace is a subsequence of ABCD ABC is not okay I mean yeah wait no good that we know where the subsequence is given two sources two strings so is this source and Target we turn the minimum number of subsequences of source such attacking data concatenation equals Target if the task is impossible we turn negative one okay um I think this is presented in a very mathematical way of course you have this kind um kind star climb uh coin uh what's it called um quite enclosure or something like this I don't remember yeah okay goodbye but in any case uh I'm just following math uh favorite complexity terms used to stay anyway queen star Coinstar in any case um the idea is if I mean I think this one can be tricky if you haven't seen it before um I mean I guess that's true for every problem um but no I mean sometimes could be some problem could be not tricky even though you haven't seen it before that's for sure so um but yeah but for this one I think the idea is you know I think the idea could be that in the beginning let me look at the constraints I mean there are only a thousand each so actually not that bad but I mean you still shouldn't do it but uh but you can I think the um the idea about this problem if you have trouble understanding that or at least if you have trouble figuring it out it's just doing it as naive as possible and what I mean by that is let's say you have a Target like this and then you try with ABC and then just play around with some examples right and then here you can kind of like match one at a time and then pop this delete this right uh B is gone see matches a doesn't do anything get rid of it B and then so forth right and if you kind of see it this way if you do it with a few examples you kind of just uh you just noticed that you know you can kind of do it in a greedy way for the source right just keep on looping it as many times as you can um so what's the worst case complexity right well the worst case complexity is going to be n square or how do you want to say it let's just say you have S is you got the length of source T is equal to length of Target in worst case it's going to be S times T if you're not very careful because the way that we did it let's just say we have uh right something like this and then you have uh a b c d e f g z or something like this then it's going to be a lot of these cases because that's the size of the answer is going to be T um thank you yeah and this is negative one but then you know you just don't see it but um the answer is going to be T is the worst case because you just do one count at a time assuming that each character can be found and if the cost is s then it's gonna be S times T which to be honest given that smt is a million maybe it's fast enough uh you never know because it's lead code uh a million would be fast enough in if you only test one uh one input but it I don't know how many test cases there are so it may not be fast enough but also another case there is a more straightforward um I mean I would say straightforward but just there is another way to do it in uh o of T instead of s times T and that is that you just do um because what are we doing here right we basically have a pointer on the S where we go okay there's z uh there's another Z and so forth right um but what we can just like link all the Zeds together right we go from here and then let's just say we skip we're able to kind of go to the thing so that we only care about the next Z and then so forth and then I think we should be good so that's basically the idea about pre-processing pre-processing pre-processing pre-processing the input in this way so pre-processing the input in this way so pre-processing the input in this way so let's get started um and that's the idea in code we'll do it together yeah um let's just say about you know that is Physicians maybe is you go to uh yeah if you go to the collections dot default of a list right and then for I see and enumerate source we have positions of C we append I right so now position of some character if we put any character in C in positions we can now uh keep track of the indexes right and a couple of ways you can kind of Do It um you can actually you know now that we have here you can actually keep on binary search if that's what you want you know to get the next counter and then loop around with not for another binary search you can also um do it in some other ways I think I'm gonna actually um you can also just like keep track of the indexes for each character and then just kind of increment by that um the way that I'm gonna do it is a little bit lazy but taking advantage of the data structure and then I'm using python by using a deck because then now let's just say our starting position so um so for C and T oh no in Target right uh we want to do because uh so the First characters what we care about but we want to get the current character that's in so our current pointer that's an S right so let's just say we have S pointer maybe is equal to zero and then we have also just like the amount of iterations so the iterations it's going to be and we always need at least one so maybe uh yeah foreign so basically first of all let's just check that if this is the length of zero is equal to zero that means that a character and Target doesn't exist in source so then that's just return negative one otherwise uh we look at the pointer if pointer greater than or you go to positions oops positions of C of zero then that's good then we update the pointer two positions of C plus zero plus one and then that's it really basically we go to the next count after that and then when we go to the next Loop we'll be done otherwise um if it's not we also want to um pop left on that index I think there is a thing that lets you pop that and then put it to the back but I forget what it is so uh we'll just ignore it for now let me know in the comments if you know what I'm talking about though right basically now we're put putting that index and put it all the way to the back right uh wait is this right maybe I could do it no this is wrong I'm concerning you call I think this is if this is less than or you go to whoops sorry friends um it's less than or you go to then we could do this and then yeah otherwise um otherwise I guess it's the same logic but let me just double check in my head no it's fine yeah so otherwise it's the same logic except for we do something like iteration is legal we increment iterations because now we got to the end um because as point is and then we want to go back to the beginning so as point is equal to zero but and then you kind of copy and paste here but you can actually just kind of take this um put this here right and if this is greater than it then we do this otherwise we just you know do this thing and then at the end we return the number of iterations that we went through the number of cycles and yeah uh I am lazy so I am gonna submit the yeah it should be okay maybe not the one and three is the same thing so that's terrible um I get a case well this is off by a lot actually I was going to say that example is one and to be a kind of weird but uh man I'm getting a lot of things wrong today on silliness uh why is this dude he was just for you do I mess up hmm oh I did mess up I know what I did wrong can I fix that sorry friends I think I made a mistake in my logic um because basically the idea is that if this is the pointer is past that first position but there actually might be other ones that are next to it just that this is not that it can we do it and I'm just trying to think if we had done binary search that would have been correct but this is not the case um the other thing though is that if we do the loop the other way like if we keep on so the two fixes one is binary search but then the other thing is we keep if we do the loop like we do like this is a if we do a while loop and then kind of keep on incrementing it to the back then that's just going to also be S times t hmm to be honest I don't know how to solve that so maybe I think my assumption was just wrong so sorry friends uh I am solving this live and as you can see uh it is actually possible for Larry to be wrong I don't know the answers to these all the time even for medium problem so my bad um I think I'm gonna just do the binary search and then we'll revisit the answer together because the binary search I know to be correct um but yeah that's my fault hmm but basically now we want to do positions C we want to do a bisect dot bisect left because equivalent is fine whoops or best pointer and then so this is the index right so then positions of C with index we want to set as pointer is equal to this plus one um right um but only but if it if we reach the end then there's no good of index is greater than equal to length of positions of C then we want to do iterations plus one and as pointer is equal to zero in the beginning and then we want to do this again um to get back to the beginning and yeah let's give a submit again so this time it's good huh I wait I think I'm thinking of a similar problem but not this um which is why hmm let me go over this problem let me go over the solution first and then let me think about if I could have fixed the other one but yeah but basically that idea is just you know bisect left allow us to kind of get the indexed as s point or equal to and then we want to go to the next one if this returns an index that is greater than the length of this that means that there's no number that is bigger or you go to put as pointer uh in the indexes so we have to update the iterations go to zero and then that's five binary search again though I guess in this case it would just be the first index yeah I guess this would just be the first index so maybe I could have just put this as a position zero or something like that but in any case um so you only need two of them because by definition the first number should be zero or greater right um so this is T this is going to be log C but like s side um so this is good all of t log s time and O of s space right o of s space coming from the summation of all these uh default lists man sloppy day but huh Can I hmm I feel like I've just had other tricks somewhere else but what is the radiation that I'm trying to think that I'm that is messing me up oh no check out the editorial I'm getting old people is struggling uh okay two pointers two point is still s times T now right if you're not careful yeah that's what we were saying uh this is what we did oh I see I guess I did it that time basically the more optimal way is just pre-calculating the next character of pre-calculating the next character of pre-calculating the next character of every array at every index so that's going to be linear's time I'm 26 I guess I use that technique before um so then that reduces this look up to O of one because you're just like okay well I'm at this point there what is the next um counter of this cell with basically like a suffix Away really um okay I don't know maybe it's just one of those days uh that's all I have for today though let me know what you think let me know if you figure out the optimal solution or let me know what you think about my solution and my day uh that's all I have so stay good stay healthy to get mental health I'll see you later and take care bye | Shortest Way to Form String | pairs-of-songs-with-total-durations-divisible-by-60 | A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not).
Given two strings `source` and `target`, return _the minimum number of **subsequences** of_ `source` _such that their concatenation equals_ `target`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** source = "abc ", target = "abcbc "
**Output:** 2
**Explanation:** The target "abcbc " can be formed by "abc " and "bc ", which are subsequences of source "abc ".
**Example 2:**
**Input:** source = "abc ", target = "acdbc "
**Output:** -1
**Explanation:** The target string cannot be constructed from the subsequences of source string due to the character "d " in target string.
**Example 3:**
**Input:** source = "xyz ", target = "xzyxz "
**Output:** 3
**Explanation:** The target string can be constructed as follows "xz " + "y " + "xz ".
**Constraints:**
* `1 <= source.length, target.length <= 1000`
* `source` and `target` consist of lowercase English letters. | We only need to consider each song length modulo 60. We can count the number of songs with (length % 60) equal to r, and store that in an array of size 60. | Array,Hash Table,Counting | Medium | null |
322 | before we actually jump into the code let's walk through a visualization of what an example looks like so here we're given a list of valid coins we can use and we're also given the target amount that we want to create and what we need to do is create a dp array where each element corresponds to the minimum number of coins needed in order to create that amount so for example dp4 would be the number of coins needed minimum in order to create 4 cents so i've initialized the array to be zero and zeroth index and to hold the value of amount plus one in all of the other indices and that's because we when we're iterating through the array we'll be picking the minimum value so we'll be replacing amount plus one which is an invalid value because we'll never need more than amount number of coins in order to make amount so for example we'll never need more than four coins in order to make four cents because the minimum is one for each index starting from index one we'll iterate through the coins list and ask ourselves if i which is the index number is greater than or equal to coins j so for example uh when i is one greater than or equal to coins j which is one and because the answer is yes that means we can go back one step and see the solution of dp zero is zero so we add one to whatever previous dp we land on so one plus zero is one and because one is smaller than five we always want to fill this cell with the minimum possible uh combination so here is uh we replace five with one then we continue down the coins list so is one greater than or equal to two and the answer is no so that means we move on and the minimum number of coins you need to make one cent is one coin so then we go to two and we ask the same question is two greater than or equal to one and because it is we can go back one step and see the solution to dp1 is one and so we do one plus one which is two and then we ask is two greater than or equal to two and the answer is yes so we can go back two indices and see that the solution of dp zero is zero and so zero plus one is one which is uh less than two so because we always want to take the minimum combination we replace that with one moving on to three so we see that for three well three is greater than or equal to one so that means we can go back one and dp of two is one so one plus one is two but do we have any better options is three greater than or equal to two the answer is yes so we can go back two we see dp of 2 is 1 so we do 1 plus 1 is equal to 2 which is what we already have here and is 3 greater than or equal to 5 well the answer is no so we can't do anything there we move on to 4. so for four we ask the exact same question iterating through coins so is four greater than or equal to one the answer is yes so we go back one uh so we get two plus one is three four greater than equal to two it is so we can go back two and we see that dp2 is 1 so 1 plus 1 is equal to 2 so we can replace that and then is 4 greater than or equal to 5 the answer is no so our optimal solution is 2. um and we can check the logic there because two cents plus two cents um gives us four so that's a total of two coins in order to make four and so that means we can return our final answer which will actually be the amount index of dp so that would be dp amount which is equal to db4 which is 2. let's now walk through the solution in code and here i've already outlined the general structure of the code so if you want to pause try it out yourself you can do so now all right so first we initiate the in array dp which will hold each element up to amount and we add one to account for zero so the zeroth index so for each element in the dp array starting from i equal to one we iterate through filling in each element so first we set dp of i equal to amount plus one as we did before in the example so now for each element we go through the coins list and we ask whether i is greater than or equal to coins j and if it is we can then set dpi to the minimum of what the current ppi is and the dp at index i minus coins j plus one and then after we've gone through all that we will have filled in the dp array so we can return uh well first we have to account for whether dp of amount is equal to amount plus one meaning that we weren't able to find any combination of coins to satisfy uh the amount that we want and if that is the case then we return negative one as directed in the prompt else we return dp of amount as seen in the example all right so let's submit and there we go | Coin Change | coin-change | You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104` | null | Array,Dynamic Programming,Breadth-First Search | Medium | 1025,1393,2345 |
338 | The The name of the next question that we are going to do is counting return of i, so what to do in it, we are given an n number, so i is n+1, what is the size? Hey, what do number, so i is n+1, what is the size? Hey, what do number, so i is n+1, what is the size? Hey, what do we have to return in it, from zero to n + 1. How many times are there in all the numbers? Let's arrange them and return them. zero to n + 1. How many times are there in all the numbers? Let's arrange them and return them. OK, let's see how to go from zero to how far will it go. In this way, people will find out how many bits are set. Then shift the mass left and then one. If you look at it once, it will become zero one zero a, we will wait for 32 bits, hence Moscow 32y, if we do left shift, then what are we going to do next, we are going to move if that is our number which is I. Is left shift equal tu one value national one left shift and move on end with this | Counting Bits | counting-bits | Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)? | You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s? | Dynamic Programming,Bit Manipulation | Easy | 191 |
1,026 | hello friends so today in this video we're gonna discuss another problem from lead code on trees the problem name is maximum difference between node and the ancestor so as you can see i'll tell you in simple terms it says that you are given a binary tree in this format and then you actually have to find out what is the difference between any two nodes but like the difference between them is just that they should be ancestor like ai and bi like if you take out two nodes a and b a should be in system b like it means that you cannot take out like this and this node you're not finding out the difference between any two nodes in this whole tree but finding out the difference between two ancestor like ancestor and current pair of nodes in simple terms it says that you have to take out two nodes such that one node is an ancestor to another and then among those nodes only you have to find out the maximum difference the absolute maximum difference as you can see in this example like the example can be if 8 and 3 because 8 is ancestor of 3 so you can find out the difference between 5 you can take out this these two nodes which is like 8 minus 1 which is 7. you can take out these two nodes you can take out these nodes does that like one node is above the another you cannot take out two trees in like two nodes in different sub-halves i hope you understand the sub-halves i hope you understand the sub-halves i hope you understand the logic but now not the logic the question part so you have to find out the maximum value the maximum absolute difference so as you can see this is the absolute difference which is the maximum is like eight minus one which is seven okay so now what you can like think about this problem is i always think of these type of recursive problems in like what i can get from the left sub half and the right sub hub like how can i traverse this tree such that i can find out like whether so let's see that this is the node like what i can get from the left and the right sub half or like what i can travel like how i can travel down to three and what information i can get up the tree so now what you can simply like the first thing which come to my mind is okay what if can i find out for every node can i find out what is the maximum and minimum below like in the subtree in the sub trees of the current node if i can get that then for every node i can check that so because every node is the insistence on the node okay except the leaf nodes but you just like think that every node is ancestor to some other nodes in the subtree of that and then if you take that node into consideration while finding out the answer you have to find out what is the minimum or maximum value in the like if you find out the minimum or maximum value in the sub half tree in the sub tree of that particular node then obviously that's that is an ancestor that is the children and like this like the nodes in the subtree and then what you can do you can just find out the absolute difference and that's the answer because you are taking out one node which is the maximum minimum in the subtree and you're taking the concentration of the particular node you are taking that particular node into consideration and then the answer will be obviously from the maximum minimum only now because the other nodes will not give you the perfect answer i hope you understand the logic part so you have to recursively get for every node you have to call out on the two subtrees for every node if there exist some subtract as you can see there is no subtree on this part but for every node if there is some sub tree on the left and the right side just call that function which will send me the maximum and minimum value in the sub half of that tree and then if you when you get that value you will take that value and the current node itself and then match out what like whether this is forming a maximum pair and then you will send out like now i have the maximum minimum value in the subtree so let's assume that for 10 i will get that the maximum value is 14 below it and 13 is the smallest value below 10. then i will find out the difference and now this 10 will also send out the maximum and minimum value for this subtree now so now consider that what is the maximum value now like because now this will again form a subtree so now i will again reupdate my maximum and minimum for this subtree and send it to the above node and that's the whole recursive problem i'll move on to the code part now because in recursive problem you have to first define the like the end case of almost all the tree problems is when you reach the root there is no null like okay just think that okay when i reach the end node for the end node when i reach a root like when i reach a node which is null there is no like the node itself is null this node exists okay but when i go to the left side of this node that is null which means that if it is null the maximum and the minimum is zero like there is no node so you will return at zero which is like returning out the maximum minimum value the first is the minimum and the second is maximum okay but for the current node let's assume that you are on a node which is having no left or right child if you are or like if you are on a node which is having no left or right child then obviously what you can think what is the maximum value the maximum and the minimum value is the node itself because the node is having no left on the right child what you can compare to so the node itself is the maximum and the node itself is the minimum so if the node left and right child null then you will return out a pair which is having the minimum and maximum value which is like the root value itself okay but what you'll do you and for any other nodes which is having some left or right child what you'll do you will call the function again which will give you the left and right child but maybe the left child doesn't exist so that's what i've done here i have called the root left i have checked that whether the root left is null if it is null means that i am not getting any maximum values from the left side because it is null if for this node if it calls on the left side give me the maximum minimum value there is no subtree on the left side so it will not get any value so like instead of returning out any absurd value because 0 is not the value which is there i have seen in the constraints okay 0 is the minimum value okay so like it doesn't matter uh so like this is no dot value like it's the like the smallest value like it doesn't matter you can also make it minus one if you want but what i've returned here is i have made up here because everything is working in pair i'm getting a pair of minimum and maximum value so i have returned out and i have made this value making 0 and 0 which means that like if there is no value on the left side if there is no subtree the minimum maximum value is 0 which i have also standardized here if there is no maximum meaning value i have a return on zero and if there is some like if there is some subtree then i will recursively call this okay function to get the maximum value because this okay function is returning out the max like the minimum and maximum pair for the subtree okay just think over that in a recursive form this function which i'm writing out is actually recursively giving me the minimum and maximum value pair as you can see i have to call this function out recursively on the left side and the right side to get me the maximum minimum and minimum value okay what is the base condition if it reached out to the null value it will be giving me zero if both of the children are not there then obviously the maximum and minimum value is the root value itself okay but now i have gotten down on a root so that like as you can see there are three type of nodes the node which is null i've written on the case for that a node which is having no children i've written down the case for that a node which is having one or two children now i'm writing down the case for that node what i have to do i have to first find out if i have taken this node into consideration i will go down the maximum value and the minimum value from the left side and the right side so i have to now find out like what i have to find out that okay whether the like the left part is not null which means that i have got something so i have to find out the maximum value can be the maximum itself or the absolute value of the root value minus the left first which means that the minimum value from the left side the left subtree minimum value or the left subtree maximum value subtract them out from the root value and then that's the absolute value will give me the value i hope you understand because i have taken down this node into concentration and then i have to find out the minimum maximum value from the left side and the right side and that's what i've done and then what i actually have to do here is i have to find out what is the like because now i found out the maximum value considering the left subtree and the right subtree the maximum difference now this node actually also have to send out the maximum and minimum value to its parent also keep that in mind so i have to find out the current maximum current minimum it means that what is the current maximum till now if i have to consider down this tree if this node into the subtree now this sub tree have to also send down so current maximum for this is like the root value itself but now i have to also compare it with the minimum and maximum value i have got down from the two sub trees that's what i'm comparing it if the left subtree exists then for the left subtree i have to also compare that whether my maximum value the second is electron value is more than if that is the more than then i have to return out i have to update my current maximum if the l dot first which is the minimum value from the left subtree if that is smaller than the root value then the smaller value for the whole sub tree will be that value you know because see if the as you can see in this if the left subtree is giving me value 1 which is minimum and my current value is 3 then obviously the subtree value minimum for this part it will be 1 not 3 because i have to compare it with the current value and the value from the left sub tree because that can be more minimum i have to send the to the above node what is the minimum among this whole subtree okay that's what i'm updating here for the left part and for the right part you can look down to the code i will put the code in the description you can check that code out also but i hope understand the like somewhat the correct part i am recursively calling out there are three types of nodes null at the node which has no children and a node which is like an intermediate node and i have to take out for all the cases and then i have to also recursively call the function again to get the information back and then i have to also as you can see i've written down when there is no like the root is null then i have returned down up here which is 0 if there is the both the children are not there then i will return on a root which is having both the values same but when there is some intermediate value i have to turn down the maximum the minimum and the maximum pair among the whole subtree and that's what i'm returning out here so i hope you understand that i have taken down the condition for all the like all the proper conditions and all the proper node values and that's the whole problem and that's the whole lot i hope understand the logic and the code for this problem if you still have not you can mention convox i'll see you next time then keep quoting and bye | Maximum Difference Between Node and Ancestor | string-without-aaa-or-bbb | Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105` | null | String,Greedy | Medium | null |
1,541 | hi everyone my name is steve today we're going to go through a little problem 1541 minimum insertions to balance a parenthesis stream let's take a look at the problem description first given a parenthesis a string s containing only the captures open and close parenthesis a parenthesis string is balanced if it meets these two conditions number one any left parenthesis must have a corresponding two consecutive right parenthesis any left parenthesis must go before the corresponding two consecutive right parenthesis for example this one and this are balanced and these two are not balanced and it's saying that you can insert the characters close and open parenthesis at any position of the string to balance it if it needed return the minimum number of insertions needed to make s balanced let's take a look at a few examples to help us understand to catch all of the test cases for example test case one this one left and left right and right one left needs to correspond to two consecutive right parenthesis so one corresponds to these two all right so these two are just the balance style and then there is one more left parenthesis but on the right side there's only one right parenthesis so we need to add one more right parenthesis right that's how the explanation put it we need to add one more right parenthesis at the end of the string to make this one a balanced parenthesis string that's why the output is one for this test case and for this one left maps to two consecutive right parenthesis so the output z is zero because the given input string is already a balanced parenthesis string all right let's take a look at the third one is given input like this the first two the right parenthesis so we need to insert at least one left parenthesis in this case to match to counter out these two right parenthesis right so that is one insertion and then here this one maps to two consecutive right parenthesis so these three characters balanced out but there is one more left parenthesis left out so we need to add two more right parenthesis in the end to match out the last left parenthesis so one plus two is three so that's why it's three the same reasoning goes to example four and example five let's just walk through a little bit longer a little bit lengthy string to help us really understand how this balance out really works suppose we're given this long string this string has a length of 17 and down below the second row i'm just mapping all of the indices over here so the first capture is left parenthesis and this index is zero this is what it means let's see how many insertions do we need to balance out this entire given input so first one two okay this is fine so first what we found is this one this left parenthesis balances out the two right consecutive parenthesis right so these three are balanced out and then we're left with the first left parenthesis okay so we need to add one more right parenthesis to balance out this one and this one so that this one can be balanced out so all of the characters either left or right parenthesis that we need to add to make the original input string to be a balanced parenthesis is added here so in the end we can just calculate we can just count how many additional parameters in the clothes are open that we added here then that's going to be the answer for this one so then these three are balanced out now let's move on from left to right so here two left parenthesis all right but we got two right parenthesis here so these three are balanced out these three are balanced you see this one there's only one right parenthesis here but there's one more left parenthesis here so we need to add one more right parenthesis here right so two balance out these three all right those three are gone now we have this one and this one so apparently we need to add one more right parenthesis here so that these three can be balanced out because it needs to be consecutive two right parenthesis right now these three are balanced down now these three are good one left maps to two corresponding right parenthesis so these three are balanced out now we have two right parenthesis that means we need to add one more left parenthesis here so that these three could balance out all right now we're done in this case you can see as i said previously we can just count how many additional left or right parenthesis we have above the table that is one two three four that's why it should be returning four in this case i see quite a few people are confused in the discussion board of this league problem why this input array the output is four instead of one so this is the reasoning behind this it needs two consecutive closed parenthesis so that it can meet the definition of the code of the balanced parenthesis stream all right looking at this problem thinking about this problem a very natural idea that comes into mind is using stack right stack has the feature of first in last out that's going to help us take care of all of the things that can be balanced out where we can just pop them out right anything that is still remaining in the stack we can take care of them as we iterate through this given input array and at the end if there's still after we go through this entire input array if there is still anything remaining in the stack we can take care of them in the end that's the idea let's just put the id into the actual code and i'll explain more as we type in the code so to figure out all of the possible cases to solve this balanced parenthesis string problem all right first let's initialize a stack and the type of the stack is character that's good enough and i think should be the most appropriate for this problem and then what we need is we'll need a for loop to go through to be more specific i'm using a for loop of an integer i so that we can go through uh length go through this entire given input stream and then what used um we'll just call it c um as char at i so there as the problem states there are only two possible characters left or right parenthesis all right let's do fc equals left parenthesis if c equals to left parenthesis or c equals to right parenthesis these are the only two possible calculators in the given input stream all right if this is the left parenthesis let's check there are also two cases in here and two cases in here let's do them one by one if stack is empty else if stack is not empty if stack is empty in that case that's totally fine if this is the left parenthesis we can just push that under the stack that's it we can add it to the stack right that's for this case we're done but if the stack is not empty so there are two possible cases in this branch right which means the stack is not empty the first case is that the stack contains in left parenthesis in that case what we can do is so we'll just peak if stack equals left oops in that case we can just simply add one more left parenthesis into the stack right which is going to be something like this which is totally fine the second case is that the one that we are peeking at this stack it's this case it has a closed parenthesis it has a right parenthesis on the top of the stack in that case it's guaranteed that there is a left parenthesis here there is a left parenthesis prior to the right parenthesis how can we guarantee that we'll do that in the else branch later on this is going to be guaranteed in this case there is a left parenthesis prior to this closed parenthesis so in this case can we directly add a left parenthesis here can we directly add one here can we directly add because the current character that we are iterating on is in left parenthesis can we directly add a left parenthesis on top of the stack no we cannot what we need to do is that we need to insert one more closed parenthesis that's why okay let me initialize one as quiet insertions needed start with zero let me copy this one in this case we need to insert one more closed parenthesis to balance out this these first two so and then we need to stack pop the existing close parenthesis and one more time stack pop the one prior to this which is a left parenthesis and here don't worry about the stack is going to be empty and throw stack and element doesn't exist exception or something that's not going to be the case because again it's guaranteed that there's going to be one more left parenthesis prior on the left side of the closed parenthesis and we're going to do that in the else branch so after this then we can add this close this left parenthesis on top of the stack right so we still need to do that so that means we have popped all of this off and then we add the left parenthesis on top of the stack all right um apparently this could be further simplified because the stack adds the stack at c in both branches and they then so let me just oops let me just simplify this move this out of this because both of them need this and use this one instead of else all right because both in both branches we need this so instead of if else we can just put this one outside of the files and remove the else all right these this is how we can handle if the current character that we're iterating on is in left parenthesis now let's move on if the current character that we're iterating out is a right parenthesis so also two cases first is if stack is empty the other case is that stack is not empty so if the stack is empty that means so that is this case and right now we're iterating on a right parenthesis that means we need to add one left parenthesis in that case so let me just copy this one insert so remember we actually do need to insert this left parenthesis on top of the stack and then we can add c this c is in right parenthesis and in the other case if the stack is not empty there are also two cases so first cases which is the peak again would peak if the one on top of the stack so it's not empty so two cases first one is empty stack second case it's not empty but not empty has two cases one is that it has a left parenthesis so if this one is in left parenthesis so if this one is a left parenthesis and the one that we're iterating on is in right parenthesis in else branch so we can simply add one more right parenthesis on top of the stack right that's it because that's going to be the first parenthesis that's going to match out the left parenthesis in the other case which is why stack peak equals to close parenthesis that means we have one closed parenthesis already so and we got another one that means we can balance out the prior left parenthesis so we're happy in that case so what are we going to do we're going to stack in that case that is going to be guaranteed like this so then we're going to have one more right parenthesis so we need to pop the this one off we need to pop this one off and then we'll pop again to pop the left parenthesis off boom pop this one off yes all right that's the case that we can handle that means the stack is boom back to zero or anything else prior to that should have been matched so this is the entire for loop that's going to help us sort out the logic when we eat when we iterate through this string that's going to and the insertions needed this variable is going to be updated along the way and does that mean that's going to be finished no it's not the case again as i said after we break out of this follow so we need to check if the stack is empty or not if stack is empty if the stack is empty that's going to be easy that means everything has been balanced out already let me copy this so we can directly return the insertions needed variable directly as the final result because everything on the stack has been removed that means that after we insert all of the left and right parenthesis the entire given input string has been balanced out already but if that is not the case that means there is some remaining characters on the stack so we need to take care of that so else while stack is empty is not true in that case what we need to do we need to keep popping everything on top of the stack off of the stack now let's do c stack pop so again two cases there are only two characters we can easily check if the one that popped off of the stack is a left parenthesis that means we need to add two right parenthesis so insertion means to plus two and then we need to pop we already pop that one off that's fine and if the one that we just popped off here is the right parenthesis right else that is a right parenthesis that means we need to add one more right parenthesis so and then we need to pop that one off that this part is popping off the left parenthesis prior to that is guaranteed again that is the case because we are making a valid stack always and then in the end we'll just return insertions needed that's it now let me hit run code all right accept it let me just hit submit and see all right accept it 100 um this is one way to solve this problem um i believe there are other ways just comment down in the comment section let me know how you solve this problem i'll be happy to see how you guys approach this problem this is just one way again um i'm using a stack it's a very natural way to solve problems like this you keep popping things on top of the stack and stack gives you the first in last out feature which helps us organize all of the characters time complexity of this problem is o n since we are going through n is the length of the given string how many captures say the character the number of calculus is n in this given stream so time complexity is o n and space complexity is o n as well because the worst case is that we are building well adding all of the characters on top of the stack right so for example in this case right um this is the worst case we are adding all of the five or six left parenthesis on top of the stack before we can get anything that means we just add everything on top of the stack and we just break out of the for loop that we go into here that's the worst case so space complexity is on as well let me know how you guys approach this problem and if you think this video helps you understand this problem please do me a favor and hit the like button and just make that like button go blue i really appreciate it and also please subscribe to my channel as i have accumulated quite a few lego uh tutorials for different data structures algorithms and also for amazon web services i've so hopefully those tech videos could help you understand some problems better again thank you so much for watching hopefully i'll just see you guys in the short few seconds | Minimum Insertions to Balance a Parentheses String | top-travellers | Given a parentheses string `s` containing only the characters `'('` and `')'`. A parentheses string is **balanced** if:
* Any left parenthesis `'('` must have a corresponding two consecutive right parenthesis `'))'`.
* Left parenthesis `'('` must go before the corresponding two consecutive right parenthesis `'))'`.
In other words, we treat `'('` as an opening parenthesis and `'))'` as a closing parenthesis.
* For example, `"()) "`, `"())(()))) "` and `"(())()))) "` are balanced, `")() "`, `"())) "` and `"(())) "` are not balanced.
You can insert the characters `'('` and `')'` at any position of the string to balance it if needed.
Return _the minimum number of insertions_ needed to make `s` balanced.
**Example 1:**
**Input:** s = "(())) "
**Output:** 1
**Explanation:** The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(()))) " which is balanced.
**Example 2:**
**Input:** s = "()) "
**Output:** 0
**Explanation:** The string is already balanced.
**Example 3:**
**Input:** s = "))())( "
**Output:** 3
**Explanation:** Add '(' to match the first '))', Add '))' to match the last '('.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of `'('` and `')'` only. | null | Database | Easy | null |
225 | Dream II car has a family If I knew I was in this row I would wear it and solve a math problem to say well for more detailed information please go to the book I don't like available Mine you will go to the first question First, to understand how we work, welcome to 32 of the Daily, so today we will decide on the card with ID 225, Lemon stiles, about the same card as last time. Before, we found ourselves again using 2 start, this time we will but you do Style using 2 Kyu and we feel again the operations are foot sport top And MC boltzmann pushed into our Style Peel is to take out in Stata Talk is to take the molecules on the head of our Style, I check the situation to see if Stark is the same or not and we can use our green library to save us. use basic operations such as foot speak when turning on drunk So the MT of this style Ok let's repeat for the book a bit, our book is a picture A cup into which the bonus pictures will be in order 1 2 3 as follows and when we squeeze out the light order is three the order will be the opposite two ok Now how do we emulate this operation as if this operation please click Ok first is we determine that this is our engineer and go down do we know that our call has only one direction that is in one direction that comes out a million e Yes ok Now suppose with the first we will show about the minute method But certainly when the pen goes in so we have to push and one then we here we call when one goes this we go again needle two we will minute is imagine part 12 33 you Ok So now Now when our one has 1 2 3 elements now when we use the minute again method now with Vo Phu Sa How can we just let this element number 3 return? Ok then the method of Our motif will be to exchange molecules between these two types. Every time we take a part from this object, we gradually increase the molecules from a CO2 to a celebration post 1 website seconds and we minutes turn like that then we will lose this molecule comes first which type Late again we only have one part then we stop we push the last element of it ra ok Why Because we are using the wrong type of drug we will minute extremely one green there or As long as its error is greater than 1 So when then enter one then it is correct minute note element finally go out ok that's the top Yes so with this operation we can remove the element number three from our status and now how about we call the next method Yes Before, here we put our 1 back to empty, but now if we squeeze again, we'll pour in those blue q2 molecules 1 Q1 degree next one over here As long as the error of q2 is equal to one in Korean now when we minute one blue when one hour like this says hay is the last element and then will be equal to one ai again this is equal to a paragraph then we leave or go out ok Because of this operation we will repeat Repeat in post Just simply switch from one type to the other Switch from Q1 food switch from Q1 green skill 2 when wrong it is still greater than 0 and greater than 1 - when you get greater than 0 and greater than 1 - when you get greater than 0 and greater than 1 - when you get drunk on round 1 then push it out In addition, yes, with the top, it's just Yes, you're a k-pop star. You Yes, you're a k-pop star. You Yes, you're a k-pop star. You just need to swipe so we can simply attach the colored hook to the stroller and the 1A rule, yes, okay. We see that after the first time The first change is that our q2 is contained in the remaining data trees and we need to go through 19 knowing that after this first step we will need to have a step that we will use. Using the first rule is always the Menu. That means it will always edit our elements like that after changing everything. If the element is transferred from this Menu to q2 , we will think that the swap is easy to , we will think that the swap is easy to , we will think that the swap is easy to replace. This rule is the rule. Instead of this rule, we will make sure it is a rule for a country but there is always a molecule called the Menu. Ok here, let's add one more step. When the center is the 2nd quarter team, province 11 ok In order for this formula to always be correct, we can produce only q200, forget one. We must not skip working in the opposite direction at all, resist in the evening. Okay, now let's tell internment the first one we will use hackers maybe you guys we won't have a special library before we just have in the face to save but already I'm alone by our Elise 97m when declaring a sentence in Java , we will sell it as follows. Good luck, , we will sell it as follows. Good luck, , we will sell it as follows. Good luck, our call will be in the English style. Yes, Ok, to have a better understanding of the style of this link list, please learn more about the print part. The face and inheritance are implemented in Java so we can better understand why we save a style as Venice. Ok in this exercise , we will only understand the way , we will only understand the way , we will only understand the way we declare or kill. Let's say it's okay. Now we've got two calls and this is asking for a movie because it's a nice skin, but as we said, in the Thao hair minute, we're just fine. And when buying, but here we will use the force method because this is our language, it will be equivalent to 18 minutes Okay with the top love market we already know, we will move it to the green menu element second Ok in addition to make you is MC As long as what we keep is the width, we need to continue making our call dot Wrong with one at this time we need to pour out the last molecules then the part hey, we'll get the problem later, now we'll come to the case where it's greater than 1, then it's greater than one, then we just need to change from these molecules to something else, but if it's equal to 1, we'll get the order. right out Yes ok then come now we will insert both the self light and the secondary area over there make you this we need a remote then this buyer method it will delete the molecules and finally Let's save our baby okay, name the first elements, you said the same thing with our top pop So if the tea is still here, we will command the modi menu answer buy box we will both put a variable here call back the variable Return Three Dwarfs on the table - 1 call back the variable Return Three Dwarfs on the table - 1 call back the variable Return Three Dwarfs on the table - 1 hey when do we cover the ground again here we come similarly play Ok and here as we will say now we will need you hey we are contains data and we don't want when running this place we wonder where the river is coming from, so why in this step we will assign and swap this type of side that has just been researched so that we can always Now Is it okay to wear this style? I asked for it. Yes, ok, this will be the operation to start the number of skin areas. Looking for these swap operations, it should also be a swap operation or a normal transformation of a and b. Nothing special. especially this place remember Ok so our top operations for our nominated top will be equivalent to top pop Only here we will get the data and we will still force it in Here we get the data and then we guess And this type of event we have that's why the data doesn't change. We'll get the value here and this type of construction always contains all the elements. molecules leave the main menu so that the 2 liter su30 here wears and we always say that this Mickey always contains all that we call we need main with you and want to check this I see no problem for you need to check make you have me. Test is ok. Now let's try to click a little. I want to get that. We have to declare the wrong washing machine ratio. Okay, we'll go in, ok now. Now after starting up the initialization of our ester, here we will Monitor the other side is ourselves. This Menu will contain all of us Yes ok Formosa so cute we have a wireless molecule for only 1 Yes ok add the second element add the third element top after we call top 1 to play then there are only 12 left. That's correct, we press 4 and multiply by five and now the pop continues to play again, what should it take? only 124 left to go Yes ok Wow that's so good why do I believe in the new program I gave us it's made right then come up we're from sungmin Ok eat [ __ ] in London 22phim mo native sons ah Yes ok and bring Follow me ah Yes Ok we're still here we're still working in this moment in the top there's really only one guy but we come back and use it a lot and don't know how to make it ok End My friend, I'm here for you right now. I don't know if I've been busy since the holiday. We'll focus now. I'll focus on making videos and every weekend. Please like, subscribe and share with your friends. need this series Ok hello | Implement Stack using Queues | implement-stack-using-queues | Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`).
Implement the `MyStack` class:
* `void push(int x)` Pushes element x to the top of the stack.
* `int pop()` Removes the element on the top of the stack and returns it.
* `int top()` Returns the element on the top of the stack.
* `boolean empty()` Returns `true` if the stack is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid.
* Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
**Example 1:**
**Input**
\[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 2, 2, false\]
**Explanation**
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `top`, and `empty`.
* All the calls to `pop` and `top` are valid.
**Follow-up:** Can you implement the stack using only one queue? | null | Stack,Design,Queue | Easy | 232 |
1,293 | hey everybody this is Larry this is day three of almost uh Halloween and almost the end of the month of the Lego day challenge hit the like button hit the Subscribe when join me on Discord let me know what you think about today's Palm uh I try to celebrate my victories and as you know on my contest I've been doing poorly lately so I'm just gonna show up a little bit uh not really that show up but just it's nice to kind of finish top 32 contest uh which kind of humans out the horrendous one died in the morning so I gotta you know show it off a little bit hope that's all right anyway today's problem is shortest path in a grid with obstacle elimination okay minimum number of steps to work from upper left corner to the okay um what it constrains so M and M is 40 and K could be four uh 40 square um well K is a variable though so yeah okay let's put that quick so the key part to doing it I think it's going to so the number of possible States in this case is going to be 40 cubed which is 16 or sorry 40 to the fourth um if you want to do a naive um you know M times n times K which means for each cell you can get there with you know K number of apps to go um a remover um so this is probably going to die straight for that reason because we don't want to visit all of them and we probably could get to the end very quickly um and given decay we should be able to get to Most states quickly hmm I'm trying to think about it well actually so I did Lyle or I was wrong just not lying per se I was wrong because I did say it was 40 times 40 and K could be you know 40 times 40 so then this would be number States but actually if you think about it just a little bit um if you the longest path from top to bottom oh sorry from upper left to lower right without hitting like the laziest path is just going down and then right and that's actually not 40 times 40 that would only hit you 80 um 80 obstacles so what is that let me plug in my calculator for you so that is 128 000 States so that should be good enough so that gives me confidence that we can do diister so let's do diastrophic or dextra I call it dystra but sometimes people correct me and I don't know I just get confused um anyway so I don't know which one let me know in the comments how do you say it but in any case yeah I guess I could just move it here uh okay so yeah so we barbecue that's a heap am I ah it codes new things sometimes when you move stuff you can't type stuff apparently I typed it up here banging on it because I couldn't tell uh okay um now I forgot what I was doing so this is General dystrous stuff uh I guess technically we would start at zero and it has K usage um and also zero distance right or civil steps okay so then now we go back with steps we have x y k right um and let's just say we have a best away Matrix where it is um Infinity say times C other times see right something like that yeah I'm really slow today but okay so here we pop Q and then we just do regular um Direction stuff right this is a grid so yeah and then now we just kind of you know uh yeah for dxdy and directions NX is NY is equal to X Plus DX y plus d y um okay so then now sorry I got distracted by something uh just you know bound checking and then let's say steps is going to be plus one but new K is you go to k if grid of NX and Y is equal to one I think then NK and command by one and then that's pretty much it so now we go if best uh NX and I oh and K so I actually messed up here huh hmm so the thing I'm pausing is because I don't want to put all of K because that may actually give us way too much space usage so let's actually do a uh um a lookup thing and then here we will just do something like key is equal to NX and Y and K um and then we have key as in best or if it's not in best or best of key is greater than and um greater than steps plus one then best of Q is equal to steps plus one and then we to uh push right so we push N X and Y and K and that's plus one okay foreign quick thing of is the obstacle at the bottom what do I want to know I gotta no that's not and the beginning so I think there we have to keep track of the beginning and the end so actually this one will require um so NK is equal to zero if grid of 0 is equal to one we set it to one okay so yeah we also have to keep track that um okay so if this happens if NK is greater than k then we continue with the directions otherwise we do this other thing right um okay so otherwise we would turn negative one also otherwise if n x is equal to R minus 1 n and y is equal to C minus one then we return steps plus one uh oh I was looking for this one okay I guess I moved it to the other side hopefully this is right uh okay I got a wrong 10 instead of six what um K is equal to one oh this is you go to oh I use K in two different ways uh K Max so this is K and if n k is equal to K Max then we do it okay silly mistake but that's okay let's give it a submit oh I messed up it may timeout but wrong answer I guess oh huh that's silly because I put it here instead of here okay fine if x is equal and that's such a silly catcher but okay but the other thing that I need to do is also if um best uh x y k is greater than steps then we continue so that basically we don't process stuff that don't matter the reason is kind of a slow optimization or whatever oh I have to do just all right huh no whoops okay I guess that works again what's the test case that I got wrong in okay it doesn't tell me so okay fine I'm gonna see if I messed it up again okay cool a silly mistake but otherwise pretty okay just gotta think about it cases 9 and 43 days wow really slow actually what I did last time that's asked I did mostly the same thing hmm I guess you didn't need a heap but I don't know I guess this is always unclear uh but yeah let's go back yeah but this is daistra so the complex is just a dice dress algorithm um definitely read up on it if you like and also in case you're foreign case you want to Google it up that's what I was talking about and because my pronunciation is weird but yeah let me know what you think that's all I have so it's a very standard e setup um so I don't want to dwell on it too much today I'm a little bit tired my apologies so yeah let me know what you think stay good stay healthy to good mental health I'll see y'all later and take care bye and also remember that uh one more thing that I want to add is that I um this is way expected on interviews so definitely know it uh but yeah that's what I have so stay good stay healthy it's a good mental health I'll see y'all later take care bye | Shortest Path in a Grid with Obstacles Elimination | three-consecutive-odds | You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**.
Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _given that you can eliminate **at most**_ `k` _obstacles_. If it is not possible to find such walk return `-1`.
**Example 1:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[0,0,0\],\[0,1,1\],\[0,0,0\]\], k = 1
**Output:** 6
**Explanation:**
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> **(3,2)** -> (4,2).
**Example 2:**
**Input:** grid = \[\[0,1,1\],\[1,1,1\],\[1,0,0\]\], k = 1
**Output:** -1
**Explanation:** We need to eliminate at least two obstacles to find such a walk.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 40`
* `1 <= k <= m * n`
* `grid[i][j]` is either `0` **or** `1`.
* `grid[0][0] == grid[m - 1][n - 1] == 0` | Check every three consecutive numbers in the array for parity. | Array | Easy | null |
513 | we are going to solve the problem find bottom left tree value in this question given the root of Bin return the leftmost value in last row of the tree so basically question what is saying question is left most value in the last row of the tree what is last row there is in level water travor in the last level is the last row in this tree is first row and second is the last row and the last in last row we return the left most value in this case is one so answer is one for this first row second row third row and this is the last row it is only value then you return s so what we are going to do in this question we Traverse level wise uh BFS method and then we store all value in a vector and return the first value so this is a question we are going to solve uh we going to apply BFS we first uh restore root in this and size of the how many element we Trav the and every element we store every element level wise element store in a vector the while loop Trav how many time the is Trav the time how many element in the level if a are one element we it Trav one times if there are two element it D two times in there this case there are three Li in Traverse three time and we take uh its row if traversing this we Traverse this and we store first El left then right if there no right go far there it store left element then right element we store all element in this Vector there here I we can see we Travers if three node we front first we pop front then we if Vector do size then push element in this and we push left element and there right element we return in that leftmost value Vector Z it will be the left most last row left most value because we are storing level wise in this min 4 5 6 if and when we return the first value Vector zero it will be the first leftmost value and in the last and every time answer will be change in the last answer will be updated by the left bottom left most value and then answer will be returned here we are going to submit this question thank you for seeing video | Find Bottom Left Tree Value | find-bottom-left-tree-value | Given the `root` of a binary tree, return the leftmost value in the last row of the tree.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,2,3,4,null,5,6,null,null,7\]
**Output:** 7
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | null |
440 | are you stuck on a coding challenge don't worry we've got your back let's dive in and solve the KF smallest in lexicographical order problem together the problem is to find the KF smallest number in the lexicographic order of 1 to n this code is using a binary search approach to find the KF smallest number in lexicographic order it starts by initializing a variable current number to 1 and decrementing the value of K by 1. then it uses a while loop to iterate through the numbers and at each iteration it calls the count steps method to count the number of steps between the current number and the next number in lexicographic order the count steps method uses a while loop to iterate through the numbers and variables current number and next number to keep track of the current number and the next number in lexicographic order if the number of steps is less than or equal to K the current number is increment and K is decremented by the number of steps if the number of steps is greater than K the current number is multiplied by 10 and K is decremented by 1. let's consider an example where n is 100 and K is 90. in the first iteration of the while loop the current number is 1 and the number of steps between 1 and 2 is 9. since 9 less than 90 we increment current number by 1 and decrement K by 9. the new values of current number and kr2 and 81 respectively in the second iteration of the while loop the current number is 2 and the number of steps between 2 and 20 is 18. since 18 less than 81 we increment current number by 1 and decrement K by 18. the new values of current number and kr3 and 63 respectively in the third iteration of the while loop the current number is 3 and the number of steps between 3 and 30 is 27. since 27 less than 63 we increment current number by 1 and decrement K by 27. the new values of current number and kr4 and 36 respectively in the fourth iteration of the while loop the current number is 4 and the number of steps between 4 and 40 is 36. since 36 equals 36 we return 4 as the kth smallest number in lexicographic order the while loop runs log n times and at each iteration it calls the count steps method which takes log n time to count the number of steps between two numbers therefore the overall time complexity of the solution is O log n into login the space complexity of the solution is o one because we are only using a few variables and not allocating any additional memory thanks for following along I appreciate your attention and I hope you found this explanation helpful if you found this video helpful make sure to hit the like button leave a comment and subscribe for more content like this | K-th Smallest in Lexicographical Order | k-th-smallest-in-lexicographical-order | Given two integers `n` and `k`, return _the_ `kth` _lexicographically smallest integer in the range_ `[1, n]`.
**Example 1:**
**Input:** n = 13, k = 2
**Output:** 10
**Explanation:** The lexicographical order is \[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\], so the second smallest number is 10.
**Example 2:**
**Input:** n = 1, k = 1
**Output:** 1
**Constraints:**
* `1 <= k <= n <= 109` | null | Trie | Hard | null |
905 | hello guys and welcome to a teacher before we get started I like to thank everybody that has left a comment or subscribe on my channel if you haven't please do so they're going to be solving problem 905 sort array by parity this is an easy problem by a classification it states given an array a of non-negative states given an array a of non-negative states given an array a of non-negative integers return an array consisting of all the even elements of a followed by all the other elements of a ok you may return any answer rate that satisfy the condition so we're given the input array 3 1 2 4 and then we output 2 4 3 1 so you can see that off the even numbers are in front of all the odd numbers and you can have their outputs as long as the odds are in the back and the events are in the front the answer is reported as correct ok so any of these variations will actually work so let's get started so what I'm gonna do here is just copy this signature here this method signature function signature and I have an old project I'm just gonna use that using going here and create a new Java class I'm gonna call this one parity alright just for short and let me go into presentation mode ok bit bigger and I'm just gonna go ahead and paste that function here it's just completely because we haven't returned anything all right so there are two ways we can do this first we can actually allocate an extra array right and return that and we just have to use two pointers for this okay so we want all the odds to be in the back and all the events in the front so if we have two pointers when we find and even we just increment from the front and we place it in the front and when we find and odd we put that in the back and then we just take Freeman okay so all you can do is you can say int right front turn it equal to zero and int back it's going to equal to a dot length minus one all right so now we just need to go through the digit in a all right well the values in a we're going to say for int value all right you can use the for each loop and a right so in the same if write the value right and one is equal to zero so and one can replace with mod - zero so and one can replace with mod - zero so and one can replace with mod - all right so what you're saying that if the value mod 2 is equal to zero but we're using bitwise and here to dictate to see if a number is either even right so the number here is even then all you have to do is we have to then create that extra race I'm gonna say here I'll say parity ray is gonna equal to u into a and we just pass in a plant right now you can just say that parity right and then we can say the front right plus they're gonna call the value house do a parody and they will do back - - do a parody and they will do back - - do a parody and they will do back - - right it's going to equal the value so here we're just saying that if the value is odd is even right if the value here is even then we're gonna place it in the front and then we're just going to increment that in the explication for the next even that we find all right and if it's not even then definitely it odd so we're gonna place that in the back and then we're gonna decrement that so we create a space that put that in the next odd in the back all right so once we have this we're pretty much done we just need to go ahead I return the parity ray all right so let's go ahead here and just create main so little public static void main string array oops string array arcs all right you can also do this too if you want the more that I do this is kind of safely typing all right so we can create a new array so it's an int array gonna equal you and Ray and just pass it some value so we're going to pass in let's say three one two and four right and all we want to do is just do a top t here and do arrays to string and we need to pass in the sort parity and also to make this easier I'm gonna make this static right so we can just call it here so I'm going to go the solar array and we're gonna pass in the array all right kind of mix a little bit smaller so you cannot see and let's just run this here alright and you guys can see that we do get all of the values in the array in the order that the problem after the states so we have all the odd all of the even numbers in front of the odd numbers all right and so we're good with this part so the thing is that can we do this also by not using write a new allocation a new array right yes we can okay so we can also do this without having to allocate a new array by swapping values all right so that's going to be a second place I'm going to show you guys so I'm just gonna go and I'll copy this signature here all right and I'm just gonna go ahead and paste this here and I'm going to change this from just put in place all right so we have days so what I want to do is we want to still do that I want to go when this duels here the int it was let's do low and high do a length minus one I just you just don't want to put everything sort of a four loop on make it a little bit I'll use a while loop here so I'm going to say while the low right is less than high all right so want to say that if write a and so I'm reaching Java complains every time you use the and without having to place them inside of another bracket a brace so I don't know why but if a that low right and one right is not equal to zero meaning that it's actually odd right and you want to do a that and then high right and one is equal to zero so if we have this we want to go ahead and actually swap so I'm just gonna come here and finish this later on because I have to go ahead and write a swap function you can do it inside of here as well it might be even be better right because you can create the temp outside off the loop and then when you do the swapping you don't have to recreate temp again which actually makes your programs a little bit faster so you have to recreate the variable over and over again all right it's optional how you guys want to do this you can also swap by using the XOR operator if you want to use that if you know how to use the XOR operator you can do that too okay but I'm gonna do that in this video because I'm trying to just remark for clarity alright so you can recreate this as well you can do this in Python in one line of code okay so it depends on the language just get the logic of the problem right first before you try to implement it next going to say if I'm gonna do if a low right and one that is a equal to zero then what I want to do is we want to say low plus and we just have to reverse this logic for high so I can just go ahead here copy this and this paste is here and here when changes to high and if this is not equal to zero then we're going to decrement high we're gonna say hi - - and what I'm gonna do gonna say hi - - and what I'm gonna do gonna say hi - - and what I'm gonna do here is just write the swap outside so I'm going to say public static void swap read array so I'm just going to create that enter a here in low and in high next we want to create a ten variables once a temp is equal to a low I'll be right back just may I ask somebody knocking on my door so let's go ahead and finish this and they're gonna say a low right just going to equal a high and a high it's gonna equal alright so now we're at this portion all you have to do is just pass in that swap from the swab a low and high and then you just need to go ahead and return a and this portion is done all right so it makes a little bit smaller so we can kind of see this don't do SLT again and do erase to string and I'm going to do a sort right by parity in place and we're gonna pass in the rate so this will still produce an answer for us I'm gonna go ahead and run this alright and it should be done so you can see the difference here is that here the four actually comes first because of the way that we actually run we checked the numbers before comes first here alright and then the two however the even numbers are still in front of the odd number right off all of the odd numbers so we still get the same solution right so this solution will go ahead and match exactly what they want it because if we have either four or two right or two and four doesn't really matter all right so there are still are acceptable there are acceptable solutions all right guys this be it for this tutorial if you like you just give me a thumb up you don't subscribe to my channel yet please do so I will see you guys in the next tutorial have a good day bye | Sort Array By Parity | length-of-longest-fibonacci-subsequence | Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers.
Return _**any array** that satisfies this condition_.
**Example 1:**
**Input:** nums = \[3,1,2,4\]
**Output:** \[2,4,3,1\]
**Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted.
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 5000`
* `0 <= nums[i] <= 5000` | null | Array,Hash Table,Dynamic Programming | Medium | 1013 |
895 | Hello hello everyone welcome to my channel it's all latest hot problem send maximum text message happy implement the frequency of clans between two methoded such and population will addicts number in tracks in to-do list acid to design tracks in to-do list acid to design tracks in to-do list acid to design and I hope this will remove with written the Most Frequent Element in Time for Frequent Element to the Top of the Word for Example We Are Not Getting Duplicate Element Will Think of Elements and Different Elements 12345 If You Subscribe to This Will Guide Multiple Accounts of the Numbers and Happy Return Which are the number one reader volume maximum frequency and this sex last most element in alwar distic how will feelgood samadhi sirf every element 151 what will oo create a text 9483 below 1000 like this and frequency subscribe video give and 1997 subscribe channel and Question number 100 is Pour dictionary in python so what will we create common in this country when we find difficult 351 Note 7 days will update 751 And frequency of when we do it in the same style 052 Nod to go into the next 100 years will Create ft step to the frequency of over 500 similarly nov to 30 nov 29 2012 the state of karo quot 24 hours left for r 9505 frequency come 300 will create distic over this will create and they directly five weaver subscription to change from the fennel and disturbance Frequency And Stop Element Subscribe This Element And Turn On This Is The Population Returning From To Subscribe From Which Will Assist You From Doing So Will Me Sunday Guilty Chest Focus Half Expression First Now Dr Reddy Labs West Macrame Frequency To End Top Element On Frequency To This 12557 Have And Written Over 700 Difficult Yourself From To One Similarly Listen To A Pop Album 558 And Willingly Say Z5 Pro M2 Lineage Not Office Fair Will Remove Poverty For Her Returning Officer Will Be Difficult For 120 Service How It's Work You Must Have You Tried And Tried to implement food and novi user has no status for maintaining and I will create a discussion to know what is data structures to wikinews different data structure to handle this first data structure schemes in mind like attitude and solve this problem long back I will Use This Cream And Some Water Stream Ape Will Do The Trees Pages In Solitude And Feeder's Value Pierce What I Will Do I Will Create Life Twenty One And Five Step 110th Mistake Similarly When They Get Another Frequency White Is Two Frequency Between Explode And Create Unrest And Left Over It's Not Related To Any Example First Five Thursday Subscribe Now We Are To Do You Will Get The Maximum Key That Inform The Team Of Immediately Facilitate Method Values And Last Key Values And Last Key Values And Last Key Entry Map Will Give What Is The Maximum The value that comes from the dream will love you till and will give the element from this is the president will remove all subscribe to a code for this channel subscribe width definition of give zero plus one in his life in the defense estate they competition organized and Create a new state president and chief justice holiday this for the frequency services what they are getting frequency of mother [ __ ] women and getting frequency of mother [ __ ] women and getting frequency of mother [ __ ] women and in case of pop bihar cutting glass thing maximum frequency half of the elements from last stand and sacrifice of elements and you will last its difficult Subscribe to element What will be the space and time complexity of operation in frequency symbol of do I am getting from and removing all rate average Dhowan operation violin key software like adding this and also getting last key suiting glass key from paytm app this tax Of Login Time How Big Boss Paytm App Internally Implemented A Balance Point Mystery Solve Every Time For Finding Maximum Which Pen Go To There Right Sophie Teaser Balance With Toys Scent Of Height Of The Tree Maximum Will Open The System Operation Will Take Off Time Show Her Lover That Aap Sandop Method Very Lagi Wedding 21 Also Can Take Law And Time Should Decide How The Time Complexity Of Dissolution Is Life And Space Complex Meanwhile Store All The Element In Our Method Chords Beach Is Open Can Us For The Improve Time Complexity Let's Porn Video And Think Mitawat So Instead Of Using Tree Map SB Nidhi Maximum Can We Use To The Muppets Flight Map And Enter Maximum Frequency Variables What We Will Do We Will Create A Maximum Frequency Variable Dad Wheel Drive Differential Oil Co Maximum Frequency Fennel 8V shift next9 depend want some against maximum frequency in the same approach life par map 20 laundry frequency will create and easy steps so will update maximum frequency royal every time they in the adds vaccine to our grab till the time valve Battery grab till the time valve Battery grab till the time valve Battery Saver Mod 500 W 1000 v5 will update soon be similarly when will be the one who will win more than 272 seats to know what is the full form of be 2 and elements with which will be subscribing to do and will pop up but element subscribe to jhal let's move and Implement this approach to have already done this course is quickly modified to digest it finish line from the fair and user name and next9 Jab Hal Sun Dhairya World Will Keep Track Of And Maximum Frequency In Tears Away Even So Lets Say Qualities I Expect In It's So Well In His Life In To The Constructor Is Sorry Maths Frequency This Life Way Or Know When They Here Will Update Our Max Frequency Variable Over Supermax Frequency Variable Updated From Thoughts From The Match David And Frequency Of The Amazing In To The Road Map And Her In last key incident Map And Her In last key incident Map And Her In last key incident frequency and they will update which top element from the distic after that is this distic president hustle experiences and stir well maintained will remove this straight from the mexico instead of removing this can we use to our video The 108 Subscribe to this channel to unmute Court Accepts Know the Time Complexity of Pushp Operation Is Open SBI During His Mind and Map Your Observations Time Complexity Import Data 9 Remove Operation Is the Time for the Position of Power Rangers Wild This Pest Subscribe and element in frequency and subscribe my channel thank you | Maximum Frequency Stack | shortest-path-to-get-all-keys | Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the `FreqStack` class:
* `FreqStack()` constructs an empty frequency stack.
* `void push(int val)` pushes an integer `val` onto the top of the stack.
* `int pop()` removes and returns the most frequent element in the stack.
* If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.
**Example 1:**
**Input**
\[ "FreqStack ", "push ", "push ", "push ", "push ", "push ", "push ", "pop ", "pop ", "pop ", "pop "\]
\[\[\], \[5\], \[7\], \[5\], \[7\], \[4\], \[5\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, null, null, null, null, 5, 7, 5, 4\]
**Explanation**
FreqStack freqStack = new FreqStack();
freqStack.push(5); // The stack is \[5\]
freqStack.push(7); // The stack is \[5,7\]
freqStack.push(5); // The stack is \[5,7,5\]
freqStack.push(7); // The stack is \[5,7,5,7\]
freqStack.push(4); // The stack is \[5,7,5,7,4\]
freqStack.push(5); // The stack is \[5,7,5,7,4,5\]
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,5,7,4\].
freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes \[5,7,5,4\].
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,4\].
freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes \[5,7\].
**Constraints:**
* `0 <= val <= 109`
* At most `2 * 104` calls will be made to `push` and `pop`.
* It is guaranteed that there will be at least one element in the stack before calling `pop`. | null | Bit Manipulation,Breadth-First Search | Hard | null |
787 | hi everyone it's Orin today we have a problem when we are given n CDs for example in this example one CD 0 1 2 and three and we need to find the cheapest way go from The Source City to the destination in our case the source city is zero the destination is three so to go from zero to three with the cheapest price and another important requirement is that we need to do the trip with the K stops so for example in this case the K is equals to one so we can make only one stop Al now let's say that this road from 0 to 1 from 1 to two and from 2 to 3 is 400 then we cannot pick that as a solution because in this case we are making two stops so we are picking this one from 0 to one and from 1 to three which is 100 + 600 gives us 1 to three which is 100 + 600 gives us 1 to three which is 100 + 600 gives us 700 okay uh let's take a look at one more example let's say that we have five CDs and we need to go from the cd0 to CD 4 with one stop so which algorithm we are going to use we need to use one of the shortest path algorithms in our case we are going to use D algorithm but a bit modified version of the dyos algorithm because if we are going to use D algorithm as it is it will not work for our case because it's grey approach and uh in our case we need to make a case stops which uh D algorithm doesn't consider let's first try to use it as it is so in our D in our in Dess algorithm we are maintaining a minimum hip that gives us the next shortest distance and we are also keeping track of the visited nodes the nodes that we have visited so not to revisit them again and we are setting the values to infinite to Infinity for all other nodes from our source node to all other nodes from 0 to 0 it's zero and to all other notes is infinity let's try to run the dexas algorithm first as it is so we are starting from the zero and so the next shortest path is to one which is 100 so we are updating this value right 100 and we are also adding that to visit it and the next one is from 100 from 1 to two so it's um 100 right so we are again updating this value to 200 now we also visited two so right we also visited two but the problem here is that so in this case we will not revisit to it means that this path we will not explore this path and this is the only path that is in our case with the one stop that will take us to our destination to four so instead of using D exas algorithm as it is we are not going to so we need to revisit our notes right so we will abandon this visited bu visited Boolean and also we are not going to use minimum hip instead of that we are going to use a Q and uh we are using a queue and we are exploring every option that every path every road provided that the our provided two results our if it's less than if the option that we have if the rad that we have it's a if we are making less than case stops and also that if the value is the less than current value or current price right current price let's now try to run the with the Q right our algorithm so first what we do we start from the zero again let's also remove these values so let's start we are starting again from the zero and uh so we are the P the distance from 0er to one and two is 100 and 500 we are updating these values right away 100 and 500 and also we want to explore both options so we are adding one to the Q 100 right 100 and also we are adding two to the Q with the 500 okay so we have added that and now we are first in first out we are taking one and we are exploring this option and this option gives us what it gives us 200 going to two right it gives us 200 going to two so we are adding so we are actually at this point we have already exhausted one stop that we have we cannot explore further right so we will not add any so we cannot go anywhere from two so that's it so let's explore the next one two and the 500 right two and 500 so two and 500 in this case right so what is the where we can go from two we can go to three and four to three it is 500 + 250 it gives us to three it is 500 + 250 it gives us to three it is 500 + 250 it gives us 750 and the from this is the path that we need so from 0 to two it gives us 500 and the from 2 to 4 so this road right it gives us 100 so 600 we are updating this value also and we are popping that from we are taking that from the we are taking that from our um from our que okay uh first thing that we do here we are creating a map of neighbors so for example for the zero the neighbors are one and the two so we can go to one with the 100 and the two to two with the 500 respectively so we are check going over the flights and taking the source and the destination and the cost if that if our source already exist in the map we are if it does not exist we are creating a new array list if it already exists then we are taking the value we are taking the list for that source and adding our destination and the cost to the list the next one we are initializing minimum cost array and we are setting the value for all other nodes to Infinity in our case we are just setting that to integer max value then we are running our D algorithm so the we are starting we are creating in our d extra algorithm first thing that we do we are creating a que right and we are starting with the our with our source node right we are adding Source node from s and the destination from source to source is zero and we are at starting with our stops and we are setting the minimum course to source so going from 0 to zero it's zero so we are setting that to zero now we are starting to explore the options so we are taking from our or Q whatever the value is there for example in the first one we are taking the zero so we are taking the C current note which is the zero in this case current cost is zero and the current stops in our case is one if we are considering the previous example so if our neighbors map does not contain our node so we are just um skipping that and if it contains then what we do we are exploring the options so we are taking for the zero the for example the neighbors are one and two right so we are taking the neighbor cost neighbor note which is let's say one and the neighbor cost which is 100 and we are calculating the total cost is current cost which is 0 + 100 gives us current cost which is 0 + 100 gives us current cost which is 0 + 100 gives us 100 right and we are comparing with the neighbor node so in this case for the one it's Infinity right so it's actually max value of the integer so our total cost is less than that so we are setting our so we are setting the for the neighbor note we are setting the cost our total cost 100 and uh we are checking the current stop if the current stop is more than zero so it which means that we can go and explore the other options let's say in this case we can go because we have one stop and we can add other notes right so we are adding them to our que if it's not an option then in that case we are not adding those to our queue um and at the end as we run our dtra algorithm so we are have we set in our minimum cost array we are setting all the values at the last we are checking if our minimum cost for the destination right if it's still Infinity if it's still max value it means that we haven't reached our destination in that case we are returning minus one if we have reached our destination we are returning the minimum cost destination which is the price for to go from the from our source to our destination um that's it um the about the time and space complexity for the time and space complexity is the uh V plus e so number of vertices which means that the number of nodes plus the number of edges right and the same is for the space complexity okay uh 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 | Cheapest Flights Within K Stops | sliding-puzzle | There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`.
You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`.
**Example 1:**
**Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1
**Output:** 700
**Explanation:**
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops.
**Example 2:**
**Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1
**Output:** 200
**Explanation:**
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
**Example 3:**
**Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0
**Output:** 500
**Explanation:**
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
**Constraints:**
* `1 <= n <= 100`
* `0 <= flights.length <= (n * (n - 1) / 2)`
* `flights[i].length == 3`
* `0 <= fromi, toi < n`
* `fromi != toi`
* `1 <= pricei <= 104`
* There will not be any multiple flights between two cities.
* `0 <= src, dst, k < n`
* `src != dst` | Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move. | Array,Breadth-First Search,Matrix | Hard | null |
3 | hello web developers this is pg web dev and welcome to another lead code challenge solution and in this episode i'm gonna explain the longest substring without repeating characters problem and in this problem we need to find the longest substring with our repeating characters in a given string i will also explain the sliding window technique that we're gonna use to solve this problem so let's take a look at the example and here we have three example strings and we will look at the strings and try to find the longest substring without repeating characters we can see we have for example number one we have three characters from example number two we have one and for example number three we have three characters to solve this problem using programming language we can use the sliding window technique and in this technique we gonna be going through the string letter by letter and we have two pointers we're gonna use these pointers and try to find the longest string one by one so we move pointer number two and currently we have the longest substring with one character and we're moving it letter by letter so currently we have two and then three and as we can see the next character is letter a and this is the repeated character so what we need to do is to move the first pointer also so we don't have any repeating characters and we are repeating this process until we reach the end of the string and each time we store the maximum result we found during that process so we've reached the end now and the maximum result we found during the whole process is three for this string so now let's take a look how to solve this problem programmatically in php and we're going to be using sliding window technique so first we need to create max string variable where we're going to be storing the maximum current string then we have max length variable where we're going to be starting the maximum length of the string next we need to split the whole string into individual characters so sub array is going to be an array of elements and each element is going to be a letter one letter in the string now we're gonna loop through this uh array and every element of this array we're gonna assign to a letter variable so now we're gonna check if the current letter already exists in the maximum string we have and if it doesn't exist we're going to add the current letter to the maximum string to form the longest string and now we need to check if the longest maximum string is the length of the current max string or the previous max length we had in previous iterations and you were using max function to determine this but we also need to account for the scenario if the current letter already exists in the max string and then we need to remove everything from the beginning of the mac string until the first occurrence of this letter including that letter and then we need to add this the current letter at the end of the max string and we're repeating this look for every letter in the given string and then at the end we're just returning max select which should be the maximum length we found in the entire process so let's submit it now and as we can see that our solution was accepted if we run this code for all the examples and then if we submit it is also a success which means we successfully solve this problem so this was the longest substring without repeating character solution using sliding widow technique if you have any questions or suggestions let me know in the comments and subscribe for other coding tutorials and web development knowledge otherwise thank you for watching and see in the next video bye | Longest Substring Without Repeating Characters | longest-substring-without-repeating-characters | Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces. | null | Hash Table,String,Sliding Window | Medium | 159,340,1034,1813,2209 |
134 | hi friends welcome to my channel i was exhausted last week as i switched from array to linked list for race the most difficult part is to understand the problem to come up with a solution but for linkedlist the easiest part is to understand the problem and coming up with a solution i have no problem understanding the problem come up with solution but in terms of writing code recursion it's like you switch from reading essay to saying tongue twisters and this week i'm working on tree the easiest part is to come with recursive solutions there's always a surprise okay let's show our respect to this array problem the only challenge part is to understand the solution and that's it if you like this video please give a like and subscribe that helps a lot in this video i'm going to walk you through everything about gas station problem including the mathematical proofs i will go through brute force solution first and then one pass solution and then i will explain some properties that back up when passed solution also i will try to make it easy to digest for beginners in this problem there are ungas stations and they form a circle you can add gas of i at each station and then to view at the next station again nobody entered your tank guess it's accumulated however there's a cost of guests to travel from one station to the other one like here and you can start at any station start from a sub from b c d um it's up to you but the tank is empty it's asking us to find a starting station where we can travel around all the roots for example if you start at c you wouldn't be able to arrive at d just because the cost 2 that is larger than the gas you feel but if you start from the first station you will be able to do a circular travel because if you start from a when you arrive at b there will be two minus one gas in the tank um and you fill up one gas at b so you will have two in the end and when you arrive at c you will have two minus one in a tank before you fill up the yes and if you have one you will have to see then when you're arriving at d you will have 2 minus 2 in the tank so basically you have no gas in the tank um nothing left um but you can have four gas here so when you're arriving at e you have four minus three which is one in the tank and three here and you have four and that will sustain you to uh passing this route and the revenue a so starting with a is just enough also there can be multiple successful rules for example iris reach in this example so you can basically start with anyone and do a circular channel so what conclusions that we can infer it looks like at every station there are two things that contribute to the income gas one is the gasoline field let's get some eye and the other one is a remaining s and we'll need to add the map together and compare with the cost so we have this formula to calculate the remaining guess while arriving at the next station there will be three cases if we start with a and the remaining guess is less than 0 at some point then we are not able to start at a because we are not able to pass it for example if we start from c and when we arrive at d the remaining gas will be 1 minus 2 and that will be a negative number so that means we're not able to pass d the second case is remaining gas equals to zero we will successfully arrive at the next station but while we're running the tank will be empty good luck if the ribbon gets larger than zero we will successfully arrive at the next station while revving there must be some gas remaining they can reuse all right these conclusions are good enough for us to understand brutal solution we'll need two pointers i and j i is a starting point and j simulates the moving car when i equals to 0 we start from a we calculate the remainder as based on j so when j is here that means we are calculating the remainder s for the next station that is two minus one okay that's positive then we move j from a to b to the next station and then we calculate the remains gas again which is this and it's okay to move j it's okay i'll move j until we reach the last station um if at some point the remains is negative we change the starting point to the next one and keep doing this until we find a successful route what is the time cost it's all in square because we have two pointers one is nested in the other one and both of them moves all n times so that is an o n square after coming up with brute force i always ask myself are all calculations the moves necessary the answer is no i will first review the procedure of the solution called one path and then explain it to give you a big picture it runs on three properties and i will prove them and then explain how each one saves us a bunch of work compared to the proof for solution first we calculate the total gas and total cost if the total gas is not able to cover the total cost we stop and return -1 the total cost we stop and return -1 the total cost we stop and return -1 that means there's no successful route if the total gas can cover the cost we continue we also set up two pointers i and j and starting from the first station and traverse when we arrive at each station we calculate the remain gas if it's larger than zero we move j to j minus one okay pay attention here it's very important if it doesn't work out the remaining s at c would be two minus five okay that is less than zero it doesn't work out then we move the starting point i to j plus one it doesn't work out so we restart i from here this is totally different with brute force in brute force we set up i to the second one but here we set i to the j plus one we skip b lastly where does j end up with j ends up with the last station which is the fifth one in this example here this is also different with brute force because in brute force we need to look back to check if the starting point is c we need to go through d e a b c to check but in this example we don't have to check stations that we already passed very simple i was like pretty confused about this solution it seems like incomplete is it there are three underlying properties to back up this solution i'll walk you through and provide good enough proofs to convince you by myself the first part is if the total gets less than total cost then the successful route doesn't exist this is no like we will just return -1 directly like we will just return -1 directly like we will just return -1 directly think about conservation law the challenge part is to prove this if the total gas larger than total cost there must be a successful route we don't know exactly where the starting point is but we're sure that if we keep searching one by one we'll finally find at least one successful route i'm using proof of contradiction to prove this and i want to prove the contradiction is wrong so this is a contradiction if total gets larger than total cost then there's no successful route i want to prove this is wrong um let's assume we start from m and we stop at x m is the start point and x is a point that we have remained as less than zero then we have this function the total gas from m to x plus the total gas from x to m minus the cost from m to x this cost minus the cost from x to m so basically these two is the total gas and this two is the total cost since we have the condition here we know that if we use total gas minus total cost that would be this and if you take a look at this part that is the total gas minus total cost so that is exactly the remain guess so this part is less than zero like it's negative a it may be like negative 1 negative 2 negative 3 for example okay and if a negative number has something that is larger than zero what is this number so this number would be larger than zero and that's not enough it has to larger than a if this part is minus one then here should be like two or three or four if it's negative two then this part should be three this part should be four if this is negative three there only in this way the addition could be larger than zero does this part have some meaning that'll be the remainder if we start from x to m so the remainder s from x to m is larger than a if this is the case then we can just simply start from x instead of n because we start from x when we're y and m will have gas larger than a say a plus one and we know that if you start from m with an empty tank when you arrive at x the gas remain would be minus a but this time we have a plus one so the guess would be enough for us to arrive at x therefore this is wrong so we're able to find the successful route if it's wrong then the contradiction will be right which is this one so this is proved you may ask what if i start from x and stop somewhere here since you only proved that the total from x to m is larger than a but maybe i could fail other somewhere here for example in this case this is m this is x we are not able to start from m to x the remainder s and x is negative if you start from x there's no guess letter here and you add one you're not able to reach y so just start here if this is the case then y is a new x according to a proof x is a station where the remaining gas will be less than zero we know if the total gas is larger than total cost there must be a successful route with this property we check total gas and total cost at very beginning if it doesn't qualify then we return -1 we hope this trick then we return -1 we hope this trick then we return -1 we hope this trick can help figure out some obvious silly input i like to put it before the algorithm just because my brain works like this as well the third problem is if we start from a to d fails then you'll also feel if we start with any station between a to d for example b to d fails c to d fails consider this we increase the cost here from c to d in this way if we start from a we're now able to arrive at d in the brute force if it doesn't work out we have to start with b to check is it necessary nope we don't have to check from b because we know that it won't pass d for sure why these two are totally the same except the guess at a reduced from two to one and if we start from b that equals two we start from a but adding only one gas will cause a gas so the remains will be zero at b so that equals to a doesn't provide us any benefits we know that a to d fails so even if a provide us some extra benefit like we have some remaining gas at b but one woman gas at b that gas doesn't sustain us to arrive at d let alone it doesn't provide any benefit we could provide by contradiction if b2b works then a to d should also work because a may provide extra benefits extra gas for the chip this contradicts with the assumption that a to d is a failure with this property we further conclude that once we find the failure path we can set up the starting point at the next point the third property is with enough total gas if there's a successful path from x to the last station then the starting point x must be valid you'll need to look back and check for example ij starts from here then j comes here and i comes here so start point reset as here and j comes here lastly j comes here so starting point is c in this case and when j reached the end at e it doesn't have to look back to check a or b before c the property is not that intuitive it even sounds unbelievable that's proof in this graph the whole rule is divided by green path and red path and we want to prove that if the green path works the red path must also work x is a star and z is the last issue okay the third property works under the condition of total gas larger than the total cost the total gas we filled from x to z plus the total gas we filled from z to x that's the total gas minus the total cost from x to z minus the cost from z to x so that'll be the total cost that is larger than zero what is in the green box what does it mean it means if we start from x the total gas we add from x to z minus the total cost from x to z so that is the remainder we have at z let's say the remainder is k that means when we are arriving at z we have k remain k plus gas from z to s minus cos from z to x larger than zero k plus gas field from z to x is larger level cost from z to x it means with k the main gas we will be able to look back therefore as long as this part works then we must be able to go back to x with k remaining guys with this property we'll have to circle back to check the stations prior to the starting point so loop is this j starts from zero and ends at gas status what is the time cost it's all n because we only need to go through one pass from the first session to the last one no more is needed alright that's what i have if you like this video please give a like and subscribe that helps a lot and if you have any questions feel free to leave a comment oh i benefited a lot from online resources and i put some videos that are really helpful for me in the description so you can check it out and they are very good they have very good animation | Gas Station | gas-station | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique**
**Example 1:**
**Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\]
**Output:** 3
**Explanation:**
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
**Example 2:**
**Input:** gas = \[2,3,4\], cost = \[3,4,3\]
**Output:** -1
**Explanation:**
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
**Constraints:**
* `n == gas.length == cost.length`
* `1 <= n <= 105`
* `0 <= gas[i], cost[i] <= 104` | null | Array,Greedy | Medium | 1346 |
155 | hi fellow alcohols today we're going to have a look at the problem called mean stack so the problem description is the following so we need to design a stack that supports push pop top and retrieving the minimum element in constant time so let's have a look at the example provided we want to follow the following instructions that are given to us so let's do this with our stack so we want to push -2 first then 0 so we want to push -2 first then 0 so we want to push -2 first then 0 then -3 then -3 then -3 then we want to get the minimum in the stack is -3 so stack the minimum in the stack is -3 so stack the minimum in the stack is -3 so we return -3 we return -3 we return -3 then we want to pop the element so we remove minus three then we want to call the top so the top is zero so return zero and then there's the last call to get min which is minus two so in that case the minimum is minus two so we return -2 return -2 return -2 all right so the trick here is to achieve the get minimum in constant time the naive approach would be to do this in linear time it's actually not too hard if we have like values in our stack we can just scan the whole stack find the minimum and then return this value when there's a call to getmin but that's not very efficient right so let's have a look and how we can do that in constant time the approach is to actually use two stacks what we want to do is we want to have a stack for our elements and we want to have another stack to store the minimums so let's run the same example with those two stacks first we push -2 so we add -2 to the first we push -2 so we add -2 to the first we push -2 so we add -2 to the data elements and we push -2 as well to the mean stack because -2 as well to the mean stack because -2 as well to the mean stack because it's empty and we don't have anything to compare against then we push 0 to the data elements and then we check for the minimums is 0 less than -2 no so for the minimums is 0 less than -2 no so for the minimums is 0 less than -2 no so we keep minus two as our minimum currently then we have a push to minus three so we push minus three to our data elements then we check is minus three less than minus two it is the case so we push minus three right then we have a call to pop so we remove uh minus three from the top of this data stack but what we want to do is like when the top of the data stack is equal to the top and the min stack it means that we are going to remove both elements from both stacks so in that case minus 3 and minus 3 are going to be removed together then we have a call to top so we just return the top of the data which is zero and then we have a call to get mean and get mean always returns the top of the minimum stack it's -2 minimum stack it's -2 minimum stack it's -2 and we're done so we have actually managed to solve that problem in constant time but we have a trade-off here with some but we have a trade-off here with some but we have a trade-off here with some extra space right because our space now is going to be n elements for the data stack and about an element in worst case scenario for our minimum stack so it reduces to oven so now let's have a look at how we can call that solution as we have seen in our example we're going to need two stacks one stack for the data for data elements we call it data it's a slice of end another one for the minimums it's a slice serving as well now for the constructor we just return mean stack an instance of mean stack we're gonna have a look at push and all those methods so let me change this real quick for simplicity now that we know that the top and get me are going to return the so for top we're going to return the top of the data stack and get me in the top of the main stack so let's do this first so return as data lan as the data minus one so for get min it's going to be the same except replace with s dot min so now let's have a look at the push method in the push method as we have seen in our example we want to push the data element on the top of the data stack so let's do that so s.data s.data s.data equals happen as the data and what about the mean stack as we have seen in our example we want to push the current value on the top of the minimum stack only if the minimum stack is empty or if the current value is less or equal to the top of the stack why less or equal because we need to account for duplicates so we need to be able to push multiple values that are actually equal so let's do this if the length of the mean stack is zero or if the value the current value that we're given is less or equal that get mean which is the top of the mean stack then we want to happen to the minimum stack the current value all right and now we for the pop stack as we have seen our example so for the data elements we want to remove every time there's a call to pop for the min stack we want to remove the top of the mean stack if it's equal to the top of the data stack so that's what we're going to do so basically if s dot top equals s dot get min then we're going to remove the top from the minimum stack so in that case what we do is we just re resize our slice to blend enough as that means minus one and we want to do the same for the data stack we just want to remove the top element all every time so it's going to be as the data something like this so as you can see it's a pretty simple code let's test it looks like it's working let's submit it all right as you can see it's a pretty efficient solution it's able to return the minimum in constant time so i hope you enjoyed that video and i'll see you next time 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,800 | This is all it's discuss question of written test question is button of maximum setting to the you who have doubt then this issue national to find and replace trick like share and tricks Mirwaiz entertain registry will do a question on that this is sexual enhancement on maximum till final [Praise] Director Shyam's That Ahead To Final All Angry Chilli Macrame For Example Debit The Receiver India And Pirates Took Place Half Inch This 2030 Forces Third In The Big Wedding Places Like 100 Meters Away From There Good 12345 Start From This Thank You two quid one ingredient iodine great to take medicine bread to and typing gomage and time positive way and subscribe dark skin question Suresh Kushwaha's Udaipur Pradesh High Court witch was held during protest on that Rajkumar Yadav decided definition If You Might See a Pimple Tattoo and Won't Give Them All 242 How They Can Improve Your Website Lasting Sexual Pleasure That Depends Function Find The Hague Said That Particular Subscribe Streamed During His Writing A Resident Welfare Service Proof Vitamin B-12 1000 Mumbai Contact Proof Vitamin B-12 1000 Mumbai Contact Proof Vitamin B-12 1000 Mumbai Contact For Android In The Witnesses Page 125 Equity Trading Services Are Provided Me Cheel Ka Samay With You And You Will Be Amazed This Question Angry Birds Sports Fans We Place Tune On | Maximum Ascending Subarray Sum | concatenation-of-consecutive-binary-numbers | Given an array of positive integers `nums`, return the _maximum possible sum of an **ascending** subarray in_ `nums`.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is **ascending** if for all `i` where `l <= i < r`, `numsi < numsi+1`. Note that a subarray of size `1` is **ascending**.
**Example 1:**
**Input:** nums = \[10,20,30,5,10,50\]
**Output:** 65
**Explanation:** \[5,10,50\] is the ascending subarray with the maximum sum of 65.
**Example 2:**
**Input:** nums = \[10,20,30,40,50\]
**Output:** 150
**Explanation:** \[10,20,30,40,50\] is the ascending subarray with the maximum sum of 150.
**Example 3:**
**Input:** nums = \[12,17,15,13,10,11,12\]
**Output:** 33
**Explanation:** \[10,11,12\] is the ascending subarray with the maximum sum of 33.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100` | Express the nth number value in a recursion formula and think about how we can do a fast evaluation. | Math,Bit Manipulation,Simulation | Medium | null |
1,926 | show you how to solve legal question 1926 nearest the exit from entrance in maze it's a median legal question so basically you're given our m multiplex and matrix mace something look like this and it's zero indexed which meaning is index starting from zero with empty cells represented as this dot so like empty cell here and then this one is empty cell also and then walls represented as plus so like a wall and here is wall and you cannot uh you are also given the entrance of the maze like where you enter it's your beginning point where entrance equals row and columns it gives you the number it denotes the row and column of the cell you are and standing at in one step you can move one cell up down left or right so basically it's four directions up down left and right and you can step into your cell with a wall so let's say if you're standing from here right you can't step to the right side because it's a wall but you could step into the mt cell like up and or left in this case and you your goal is to find the nearest exit from the entrance basically from here you want to find the nearest exit an exit is defined as an empty cell that is at the border of the maze so basically the border is this line and this line here right but the wall doesn't count so basically your exit option is this one is the exit this one is an exit and then this one is at exit so the entrance does not count as a exit so either way where you start it doesn't count as a exit so just in case they give your entrance from here they will tell you that this one does not count so return the number of steps in the nearest shortest path from the entrance to the nearest exit so they want you to return the shortest path and return -1 if no such path exists so like return -1 if no such path exists so like return -1 if no such path exists so like you see this maze here it's represented in the dot and plus and the entrance they give you here is this position is row one and a column two yeah it's uh row zero row one and column zero column one column two right so then the output is one it takes one step for this entrance positions to get to the exit and you can see the explanation here there are three exits in this maze at one zero 2 and a 2 3 in this case right so initially you're at the entrance cell one two and you can reach one zero by moving two steps basically one two get to one zero right and then you can reach zero two by moving one step up like right here right and you can um which it is possible to reach two three from the entrance oh it is impossible like this is like totally impossible because the wall are blocked so thus the nearest entrance is zero two from the entrance which is one step away so that's why the output here is one and then they give you another example here and if the if your starting point is one two and one zero does not count as an axis since it is an entrance cell so initially you're at the entrance cell one zero and you can reach to one two which is another exit by moving two steps right so one two right thus the nearest exit is one two which is two step away so this function that you're gonna write needs to return the answer as 2. and then for example like this example it's like impossible there's no exit in this maze then you're gonna have to return -1 in then you're gonna have to return -1 in then you're gonna have to return -1 in this case and there's some constraints here um and uh mace i j either this entrance dot length and um row colon is smaller than that and entrance will always be an aptis empty cell um this is a question asked by amazon and facebook in the last six months so let's think about this problem any time that when they ask you like the shortest path and the first you your first reaction should always be breakfast search because breakfast search like it always returns to return the shortest path to you because they always try to visit its neighbor when it moves one layer up the idea of the buffer search is that you wanted to add the queue is always used together with the buffer search so you always wanted to append the initial the beginning point of the cell row and column count to the queue and then you start popping from the queue every single time when you pop from the queue you want to go one step further basically one layer or one level up and then when you go one level up you want to add these this cell and this cell that is possible added to the queue to make sure that they're appended and then you can continue to go through the queue and continue to pop and move one layer further so in the end you are guaranteed to find the shortest the path the other thing is like in order to not to visit the cell that you have already visited already then what you need to do is use a visit set in this case to avoid the duplicates so i'm going to show you how to do this in the code so what i like to do is i want to um define the rows and columns first and the it's a graph problem so rows equals to uh length of maze and then the calls equals to um maze 2 here and um this is the uh definition and then i would say the start point is so i'm gonna just change the entrance of the entrance to a two pro because the way that they give to you is entrance uh one two like a list if i'm using a list i'm not gonna be able to add it to the hash set that i'm gonna use to avoid the duplicates so if i would say the queue that i need to use is a dq and then i'm just gonna append the start to the dq right and then i will set the result in the end i need to return how many steps and i'll put the steps as zero and then i'm gonna append the uh start the beginning of this start to the hash set to make sure i don't visit it again so the while loop should be while q exists i'm gonna start popping and then add its neighbor and basically the next layer so for i in range length of q right so that's how many times that i need to go through the for loop rc and the row and column equals to q dot pop left so whatever i pop from the queue basically is the initial value the entrance one and two one is the row and two is the column and after i'm popping i'm gonna do um a condition check basically if the row count does not equal to entrance and r equals 0 or c equals 0 or r equals rows minus one or c equals cos minus one this um these four conditions right here like the r zero is basically to find out if this is a or exit on the uh side of the maze like uh it i think i mentioned it somewhere here that oh our exit defined as an empty cell that is at the border of the maze so if um the rc it does not equal to the entrance and it's or exit at the border what i'm gonna do if i'm already so basically i'm already at the entrance then what i will be able to do is um i can return the result immediately that's like a base condition because if i'm at the exit at this point i'm already find the answer so in that case i want to return it but if not then what i wanted to do is dr dc in all four directions i'm just gonna not gonna use the directions here i'm just gonna write it uh directly because it's like four directions and a pretty easy to write and zero one zero and then in this case is um it's basically all four direction then you wanna do zero minus one and then 0 plus 1 in this case for dr dc in all four directions i'm going to calculate the neighbors row and the call so the neighbor's row and call equals to the original row plus the r basically dr is 1 minus 1 0 and 0 right so c plus dc in this case so now i'm i have already calculated its neighbor it's basically is this layer and this layer when i calculated this layer i wanna um do uh check condition to make sure that um first of all it needs to be within the range right it's it has to be inside of the maze so then i want to make sure it's bigger than zero or equal than zero but then smaller than the entire rows um within the range not the border or anything and then i'm gonna check the calls uh calls yeah there's a equal sl as well because it could be equal to zero and then i wanna check if maze um the row value of the row call and the maze is uh equals to has to be an empty cell right because i'm not when i'm at this guy's neighbor i'm only gonna add this guy and this guy so it has to be empty cell if it's like a wall here absolutely i'm not gonna add it so then also another condition is that the roll call has to be not in visit something that i have never visited before then i will i would do the following is like i'm gonna append it to the queue the row call and then visit i'm gonna add it to the visit set so then i won't visit it again and after the entire for loop what i'm gonna do is i'm gonna every time for every time that i need to go through the for loop i will need to add the one to the result so each layer i'm adding one step if that makes sense so then in the end i'm going to be able to calculate the staff value but if i go through the entire queue like i have to pop everything from the queue i couldn't find it then i'm gonna have to return minus one in this case i think that's it for the code let's see yep it went through okay great so if you think this is helpful uh please like my video and subscribe to my channel and i'll have more legal questions coming for you soon and i'll see you soon bye | Nearest Exit from Entrance in Maze | products-price-for-each-store | You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit.
Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_.
**Example 1:**
**Input:** maze = \[\[ "+ ", "+ ", ". ", "+ "\],\[ ". ", ". ", ". ", "+ "\],\[ "+ ", "+ ", "+ ", ". "\]\], entrance = \[1,2\]
**Output:** 1
**Explanation:** There are 3 exits in this maze at \[1,0\], \[0,2\], and \[2,3\].
Initially, you are at the entrance cell \[1,2\].
- You can reach \[1,0\] by moving 2 steps left.
- You can reach \[0,2\] by moving 1 step up.
It is impossible to reach \[2,3\] from the entrance.
Thus, the nearest exit is \[0,2\], which is 1 step away.
**Example 2:**
**Input:** maze = \[\[ "+ ", "+ ", "+ "\],\[ ". ", ". ", ". "\],\[ "+ ", "+ ", "+ "\]\], entrance = \[1,0\]
**Output:** 2
**Explanation:** There is 1 exit in this maze at \[1,2\].
\[1,0\] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell \[1,0\].
- You can reach \[1,2\] by moving 2 steps right.
Thus, the nearest exit is \[1,2\], which is 2 steps away.
**Example 3:**
**Input:** maze = \[\[ ". ", "+ "\]\], entrance = \[0,0\]
**Output:** -1
**Explanation:** There are no exits in this maze.
**Constraints:**
* `maze.length == m`
* `maze[i].length == n`
* `1 <= m, n <= 100`
* `maze[i][j]` is either `'.'` or `'+'`.
* `entrance.length == 2`
* `0 <= entrancerow < m`
* `0 <= entrancecol < n`
* `entrance` will always be an empty cell. | null | Database | Easy | 1948 |
232 | one so today we are looking at lead code number 232 it's called implement a queue using stacks okay so here we have uh we want to implement first in first out q using only two stacks the implemented queue should support all the functions of a normal queue so we have push peak pop and empty and so here we can see that the push method is going to take in an integer and it's not going to return anything it's going to return void the pop method will return an integer peak will turn into integer and boolean will return an empty and some notes here is that we must only use standard operations of a stack which means only push to top peak pop from top size and is empty operations are valid okay and depending on your language the stack may not be supported natively so you may stimulate a sac uh using a list or dec double ended q as long as you use only a stack standard operations okay and then we have a follow-up here okay and then we have a follow-up here okay and then we have a follow-up here can we implement this q in such that each operation is in constant time complexity in other words performing n operations will take overall o of n time even if one of those operations may take longer okay so let's think about this okay so we're gonna have a stack so let's go ahead and figure this out we're gonna have two stacks okay and we wanna have a cue that's gonna work with two stacks and so how would we go about that let's say we have a stack one i'll call this stack one and we'll call this stack two actually a better way of naming this is we can call it a push stack and a pop stack okay so we'll call this a push stack and we'll call this a pop stock okay and this will make sense in a little bit so let's say we have numbers 1 2 3 and 4 and we're gonna push this into our push stack we're gonna initially put these elements into our push stack so let's say we push in one we push into three and four okay now we wanna dequeue okay and so with cues it's first in first out the first element that was in was this one now we need to have this element be the first one out but we can't because we have this four here if we try to remove it from the front we're going to have a linear operation because we're going to have to re-index have to re-index have to re-index everything so that's not going to work so what we can do is when we try to pop we will have one linear operation and we can check is this pop stock empty okay is this pop stock empty if this is empty then what we want to do is we want to take everything out of the push stack and put it into the pop stock okay so we'll go ahead and take out this four put it here push out or pop off this three put it here pop off this two and put pop up this one and now you can see in the pop stack we do have the correct order to dequeue the correct element which is this one okay and so now let's say we add more numbers we add five six seven and eight this is going to come into the stack i'll just write it over here on the side so it's a little bit clearer but we'll have five six seven and eight that's okay it's gonna when we go to pop these are gonna be constant time we'll pop off this one pop off this two pop off this three we can add a 9 here we can add a 10 here pop off this 4. when this pop stack becomes empty and we want to call a pop a dq operation all we do is take whatever's in our push stack and pour it into our pop stack okay so we'll go ahead and take this 10 and put it in here take this 9 put it in here and so on and so forth so i'll just put it over here i'll create a new stack here just to make it clear but we'll go ahead and put this 10 here we'll put this 9 here is 8 7 6 and 5. and you can see then when we pop off this 5 it's going to be in the correct order after this 4. okay so that's the basic idea what is our time and space complexity well we do have a linear time operation because you know we could just push onto the stack indefinitely and then when we go and do a pop we're going to have a linear time operation but we'll only do that once when that pop stack is empty after that uh the dqs and the pushes will all be constant time okay so let's go ahead and code this up okay so we have this uh different syntax we'll use the javascript uh class syntax here i think it's just much cleaner so we'll do a class my cue okay and we are going to have a constructor and here we're going to have a push stack set it to an empty array and then we'll have a pop stack and we'll set that to an empty array okay and so now we're going to have the methods push pop peak and empty so let's just go ahead and punch these out that way they're there so we'll say push val okay we're gonna have a pop method here we're gonna have a peak method and then we're gonna have an empty method okay and so now what do we want to do what we want to do is we want to for a push we don't need to do anything all we need to do is push that val that value onto our push stack okay so this will be constant time we can just say this dot push stack dot push val and it's void so we don't even need to return anything now if we want to pop something off what do we need to do well first we want to check is this pop stack empty okay if it's empty we have to get everything in the push stack poured into the pop stack okay so we can check that we can say if this dot popstack dot length okay if this is equal to 0 this will corres to falsey then what do we want to say while this dot push stack dot length while we have a length there what we're going to do is we're going to pop off the push stack and pour that into the pop stack okay so this dot pop stack dot push and here we're going to pop off the push stack this dot push stack dot pop i know this seems a little confusing but it's really not it's re all we're doing here is we're checking is this pop stack empty if it is then let's go ahead and remove each one of these elements from this push stack and put it into the pop stack push it into the pop stack and because we're checking the length as our while loop condition while there's a length when that length reaches zero meaning that push stack is empty it's going to break out of that while loop okay and then so now once we've done that we know that the elements in our pop stack are in the correct order so we can just return this.popstack.pop so we can just return this.popstack.pop so we can just return this.popstack.pop okay so all we're doing here is just go ahead and returning that we're just popping off our pop stack the last element in our pop stack okay peak is going to be very similar we're going to have to check is that pop stack or is that uh pop stack empty so if this dot popstack dot length if it's empty then we want to do the same thing we're going to say while this dot push stack dot length go ahead and remove everything from the push stack and pour it into the pop stock so this dot popstack dot push this dot push stack dot pop okay and now we're not popping off the pop stack we're just returning the last element so we just go and return this dot pop stack this dot topstack dot length minus one just the last element in that pop stack okay and then to check if it's empty all we have to do is just make sure that both of these stacks are empty okay so we can just do a return um if this dot push stack dot length is null and this dot pop stack dot length is zero not null but zero okay and let's go ahead and run that okay and we are good to go okay so let's take a look at time and space complexity here uh time complexity is worst case we are going to have linear but we're only doing that once we're not doing that on every single operation so our average time complexity is actually constant for uh our dq method or our pop method okay so we can we do achieve constant time on average and then space is linear okay because as we add more inputs we're going to have to create more space okay and so that is our space and time and that is lead code number 232 implement a queue using stacks this is a great problem i really enjoy this problem i think there's it's a nice clever way to look at creating a stack out or creating a queue out of a stack and you get great um great performance uh using this method on it as well okay so that's leadco232 hope you enjoyed it and i will see you on the next one | 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 |
944 | If there are as many stings inside it, if I represent them in the form of grid and then in the form of matters, okay, then basically I have to find out in which column all the alphabets which are not in luxury sorted hotter, okay? I basically need to know which one I have to treat then @ I have to find out then @ I have to find out then @ I have to find out how many columns I have to delete ok so I understand it from the example also so if you look at the example number van then see dafgh in it ok so I have read it If we represent it in the form of then which is the first column C di ha sorry ok what does it mean basically what is B it comes only once but here what is B already what does it mean Geography is short what else I basically have to hit, so I got my one in the column, okay, so let's see the last column, what is there in it, A, then F, then I, okay, this is the shortcut in the column, okay, so if I complete all the three columns, how many columns will I get? You will have to delete it, I have given the same output, read it is clear, if I see the example number as per your request, then A and B are this one. If I represent it in the form of grade, then there will be only one column and it is correct in the order. So how many zeros have I made, okay, I understand it from the example on the next page, so basically if I look here, I was given a question, then what do I have to do? First, I have to present the format of the greeting from it. Okay, all the strings are better than this. What can I do instead of storing them, let's do it like this, first I take out the number of columns, okay, I call it number of, meaning number of columns, I am calling it M with letters, okay and number of days. I am saying let's n ok so what will I do I will do normal travels which is 2D means travels inside the breed ok so what do I have to do I will have to star the column or I will have to check for each column that it is luxury sorted or not No, ok, so first I took this column late, ok, then what to do after that, I will have to check inside every row, I will compare these two, ok, is this luxury sorted or not, if it is sorted, then these two If I will compare, then I am just doing the same here, what is Si is small, Di is smaller than Han, it means the same thing, I will compare Di with Ji, Ki if Ji means the element which is the previous one, if I am, then the previous element has to be smaller. Yes, it is fine if it is a valid response, then it is fine where the condition fails, what does it mean that what will be that column, there will be no shortcut, so in this case, let's see when I come to this column, then I will try again. When I will travel from A, it is okay because there is something before B, otherwise I started, what is there before B? Okay, so what is B, which is bigger than A? What does it mean, there is no Alexander here, okay? When here I will have to hit delete, okay, stop it in increments, okay and where, just how many columns are there, how many days are there, see 1 2 3 days, from late to late there were 10 days and the first form when I will do the comparison. I got the value there which means it is not luxury so what to do there like I will implement the answer is ok then just put break statement there so that it is needed later in the terms, it is ok because basically one statement means one The condition will fall anywhere, it means that the whole column will be there So as soon as we come to the last column, we will do the same process, then what is F, meaning one, what is small app, it is okay, it is like if it is small app, so here For this we asked how much will be the answer, it is ok in the court, find out the number of columns, ok then how many will be the number of days, as many number of offs will be, ok because we are wise, the form of the grid is ok, see, in this, you are three raw because Basically, how many strings and how many columns will there be? Basically, it will be a particular string, meaning like when is it ok? So, the number of alphabets or the number of letters in it, what will be the number of columns, everything is ok, I have declared the answer to store it is ok. We are filling the driver first, there is no traversal in the column, okay, that means for the outdoor look column, then for each column, basically where will we start the loop, from the van, meaning like I told you, if we have 4 days late, you From here we will compare with the previous one, okay, that means, should this be the previous one put break statement because we get a condition where the luxury order is not valid inside the column, okay So if when I complete the travels, then I will do the dating, okay, if I stop the scale time, then submit it, okay? | Delete Columns to Make Sorted | smallest-range-i | You are given an array of `n` strings `strs`, all of the same length.
The strings can be arranged such that there is one on each line, making a grid.
* For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows:
abc
bce
cae
You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1.
Return _the number of columns that you will delete_.
**Example 1:**
**Input:** strs = \[ "cba ", "daf ", "ghi "\]
**Output:** 1
**Explanation:** The grid looks as follows:
cba
daf
ghi
Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.
**Example 2:**
**Input:** strs = \[ "a ", "b "\]
**Output:** 0
**Explanation:** The grid looks as follows:
a
b
Column 0 is the only column and is sorted, so you will not delete any columns.
**Example 3:**
**Input:** strs = \[ "zyx ", "wvu ", "tsr "\]
**Output:** 3
**Explanation:** The grid looks as follows:
zyx
wvu
tsr
All 3 columns are not sorted, so you will delete all 3.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 1000`
* `strs[i]` consists of lowercase English letters. | null | Array,Math | Easy | null |
1,046 | hey so welcome back in this another daily Eco problem so today it was called last stone weight and it's an easy level problem um it's a Max Heap solution um for this actually I think that's the most common way I don't think yeah I don't think anyone really solves it any other way um so that's what I did was using a maxi now we're using Python and they don't really have a Mac seat they only have a Min Heath but just by like negating the values inside the Heap you're able to actually kind of create a maxi so it's a bit of a hack but that's what everyone seems to do and so what you're given here is prong called elaststone weight and you're just given an array of stones and these are the weights of the stones and so you just have two rules here for this game that you're playing where you just want to take turns and smash the two heaviest Stones together and so in this case if you first had to smash two stones it would be seven and eight because they're the largest weight and so you just keep going until there's at most one stone left and as you're smashing these Stones together there's two rules here one is okay if they're equal then they're just destroyed and you just remove them from this all right otherwise if they're not equal you just take the difference and whatever that difference is you just insert that back in into this array okay so as you keep smashing you know just based on this algorithm it's just inevitably going to be that you only have at most one stone or like none at all so yeah so let's go ahead and implement this what we're going to do is you first just create a new array here because we don't really want to modify the input array and we just want to negate all the values just so that we're able to actually like keepify this array and turn it into a Max Heap and so to do that you just say convert this every stone to a negative Stone so for every stone in our Stones array let's just negate it and insert it into this new array then we want to heapify it so that's just Heap Q Dot heapathi and we want to convert this array into a Max Heap so from here we just want to continue our game and the end condition is when we only have at most one stone left so while the length of our I keep here I think we should call this Heap like Max Heap Maybe or since we're in Python we should use the stake case back seat so while the length of our Max Heap is greater than one we know that okay we're still playing this game and so but at the end of this we want to return zero if there's no Stern Stones left we return zero so if the length of our Max Heap is zero otherwise we want to return whatever is at the top of our Heat which I guess is really there will be only one thing so we can just really just return like the index of zero because there's one thing that will be remaining okay and so while we have more than one thing on our Max Eve we want to smash the two largest Stones together and since we converted this into a Max Heap whatever we pop off from that Heap those first two things will be the two heaviest stones and so just to keep the theme with the X and Y variables we'll use that so X will be equal to the first thing that we pop off our Heap and you can do that using keepq dot heat pop we want to pop from our Max Heap and then we want to do this again but insert the second largest value as y and so just to follow the rules of the game we want to say okay if x is equal to y we want to just continue on we don't want to add anything to our heap if these are the same values we want to do nothing so you could just type like continue here but in this case when we just say we don't if they are equal to each other we'll just re-loop otherwise we want to consider re-loop otherwise we want to consider re-loop otherwise we want to consider this case and we'll just say okay let's just take the maximum value and subtract it by the smaller one and so in this case well since X is the larger value what we want to do is I think they have it like this actually I did it differently when I coded it but just realizing now so they don't equal each other then all we want to do is we want to push to our Heap um y minus X that makes sense and we need to specify our Max Heat so we're pushing to our Max Heap this difference and since we're popping off y first that'll be the maximum value and then we want to take X now one thing that I haven't fixed here is that we're doing a subtraction right now but we've actually negated all these stones and so in that case what we're going to have is we want to take the addition of this and that will be the difference and so we'll still retain the negative values here but we just want to add them instead of minusing them because it's all like the logic's all like inverted and the other thing here is we want to take the absolute because we don't want to return the negative value of this let's go ahead and run that oh I see we got a wrong answer hmm let's print this out so let's print out so print Y and X negative 8 negative seven so we added that oh that's y is we don't actually want to add them because if you add two negative numbers becomes a larger negative number so we want to do minus and double check here accepted okay that makes sense and let's just get rid of that print statement and just do that I think this all looks good here let's go ahead and try submitting it and success so yeah that's the algorithm so for time complexity I believe so since we're inserting everything into our Max Heap here we're going to have a space complexity of O of n where n is the size of the zones array so space is O of n and N is the size of the stones array and for time complexity well um that will be like n log n which is time complexity to heapify this so it's n log n for time complexity so yeah I hope that helped and good luck with the rest your algorithms thanks for watching | Last Stone Weight | max-consecutive-ones-iii | You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000` | One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on. | Array,Binary Search,Sliding Window,Prefix Sum | Medium | 340,424,485,487,2134 |
499 | hey let's continue our journey to bfs and let's stop the maze three go ahead and read the question so there's a ball in the maze with the empty spaces and the walls and the ball can go through the empty spaces by rolling up down left or right but it won't stop rolling until hitting a wall and when the ball stops you could choose the next direction so there's a hole in the maze and the ball will drop into the hall if they're loading on top of the hull so given the ball's position host position and the maze find out the ball could drop into the hall by moving the shortest distance so we're still looking for the shortest distance but the output is slightly different right now so let's go ahead and keep reading so the distance is defined by the number of the empty space is traveled by the ball from the starting position all the way to hole and the output of the moving direction is by using four letters and this stands for up down left or right and since they can be uh several different way shortest ways so you could output the lexical graphically smallest way so what that means is that if you have several paths have exactly same or shortest path and then you can sort it by using the letters that letters combination with the directions and that's how we uh understand the problem and now we understand what the question is talking about and let's think about how we solve it and from the maze 1 to maze 2 we added up one more dimension so it used to be we just want to find out if there's a path to lead from the starting position to ending position but from maze 2 we know that hey not only will i find a valid path but we are going to know what is the value path and what is the short shortest distance so that's why we convert the problem from bfs to dice draw and by solving that using the shortest distance and sorting everything shortly sorting the distance by using heap which is a mean heap in python and a short distance and we pick the lowest distance every single time from a node then we start calculating for the next uh for all the neighbors so we don't change much from the maze to maze three except that we adding actually react we're actually adding one more dimension so we had a chord two coordinates that's the first two dimension we have the shortest distance that's uh the third dimension uh we talked about in the maze two and now like we have the another dimension which is the letters so we want to record what exactly the direction we picked in the history so we're going to put that into our uh code as well so um shouldn't be like really hard uh this is hard problem but i would say this is like a harder problem for medium questions um the reason is that we have one more dimension but generically most of the code we should see will be still similar to uh what we see back in means two so let's go ahead and start writing some code and we're gonna figure out uh how we do this along the way um we still gonna have the boundary right just in case we are across the boundary so we let's define the mains and that's row and column and we're gonna have a uh hip as well and what's gonna be in the heap right now so let's think about it right initially we definitely need a distance like before right and we're gonna have ball zero uh it used to be like a start zero and start one and that's our initial position but now they change this uh initial position as the ball and they change the destination to the whole so just remember that uh now like we have this so this is exactly same thing with the previous problem but now we have one more dimension because we want to track what exactly the direction we picked before so and we're going to use the string to represent that so we need to adding up start appending the directions we went to what we went before or you can use a list to tracking that eventually convert the list to uh to a string that works too but i'm gonna just gonna use a string to tracking what directions we wouldn't perform so that's the one more dimension we had so initially like the first problem we only have the coordinates and the maze two we have the distance and now we have a pattern to tracking where we up to like what directions we pick in the history so that's the differences we have and we're still going to have all the directions and let's go ahead and put all the directions right there and let's go up and let's go down let's go left let's go right okay so we've we had the first uh four directions and then we're still gonna have the distance so the distance is gonna be just like before we're gonna has a hash map uh default and the value is gonna be the shortest distance so it's gonna be just a editor and uh okay so distance let's initialize the distance for the ball one right uh the ball one like the starting position so let's put the let's put a tuple right there and that will be equal to zero okay so perfect so uh now we can start writing the bfs so we're gonna up out our distance l and the pattern and inj so those are the values we're gonna pop out and we use q hit pop and we're gonna pop up from the heap okay so that's the initial position so we have the distance we have the pattern and we have the coordinates for x and y so we put inj as our initial parameter and so just like before if we already reached the destination and since we are actually sorted by the heap and then so we just return a pattern so why can we return a pattern and uh it's kind of interesting because the heap will sort based on the first parameter so when the first parameter is equal between two paths so for example you have two paths having the same distance and the heap was sorted by the second parameter so which is the pattern and that's how we defined in here the lexicographically smallest way and that's why we sort it in this way and the keyboard automatically tackle that so you can directly return the pattern because the heap already sorted for you and once we have that we can start exploring the all four directions so how do we explore for all four directions we i think we talked about this before and we're going to use dfx and the x and dy stands for the change of the directions and we have the directions right there and then we're going to have the staff and x and the y uh equals to the distance and i and j so we did this a lot of time as well and one of the caveat like we keep saying in the previous two problem is that so when the ball is starting from here if i want to go up i'm not going to stop right here because it says the ball will not stop until it hit the wall so it will keep scrolling in the empty spaces so for example if i pick the up direction so the ball will go up and it will stop right here you'll stop right here because i'll stop right here because the wall is right here so it's not gonna stop within the empty spaces so let's go ahead and write how do we do that uh so we're gonna need a while loop and as long as we so there are two to i just learned this actually so there are two ways to write this right so we can pick the next direction so uh this is our current position because we take the x as the i rate so this is our current position and this is the change of the direction so we provide four different directions we're gonna try every single directions so we pick the new direction and we compare with the boundary so if it's within the boundary and this is x and y plus d y and less than n so if we are within the boundary and then we can definitely uh keep growing and this another condition is as long as we are not seeing the wall and then we can keep growing right so that's why we gotta put uh if the maze the new direction for the maze it's not hitting the wall and then we can keep going so if we are not hitting the wall that's that means like we are not equal to one because one stands for the wall and then we can keep going up you can use the old way that checking if the x and y are not equal to uh zero that means like we are still in the white spaces or the empty spaces we can keep rolling and then after the while loop it can you can backtrack so we can write in that the other way so it's the same thing it's just three different lines three more lines okay um and then we add uh the directions we have the step plus one as well and we are done and once we are done and we can keep going uh another caveat so for example if the hose right here if the hole is right here and then if the ball is crossing the hole that means like we are done and then but we are not directly returned because the return value is going to be from here because we want the shortest distance so the return value should always from here but what should we do if we already across the whole that means we can do another computation but how do we do another computation is by doing this uh if x and the y is equal to the whole that means like we are in the meanwhile we are prematurely reaching the hole and we will not break that we're gonna break out after break so we're gonna do some computation so we're gonna put out the position into the queue and start calculating if this is the best position or not so we're gonna push everything into the heap and let hit hip decide if we uh once we reaching here once we reaching the hole if this is the best position or not if this is the best path or not so we let the hip decide so how do we let the heap decide and that two things to check one thing is we are checking if in this x and y in this coordinates did we already calculate this or not if we already calculated okay good so we can keep going or the step is less than the distance for um x and y so that's exactly what we did before right just like in the last problem and oh okay just like the last problem so if the new steps we are calculating is less than the distance then we have a shorter distance so that's why our distance will recording the new distance we have and we're just recording the steps all right and once we have that oh one more thing so we have to push let it let the hip decide whatever we want to calculate right um and then we put a step and pattern right here's the thing we're missing one thing so most of the code are good except right here patterns so we have the step is being updated but it seems like our pattern is never being updated but we have to update it right because eventually we want to return the pattern so if the pattern never changed and we can't do that so what's the right way to update the pattern it's actually we want to record every single time that we moving to one direction we pick one direction and we want to record which direction is that so for so the best way to do that is actually right here because we know we have the four directions right here so we just record hey if we minus one for the x coordinates that means we are going up and this means we are going down and then this is going left and this means we are going right okay so we are going for the four directions and we already add everything into directions and also the distance will also change as well because the distance will not measured only by the steps but also it's lexical graphically right and that's why the distance will not only be the distance so we're actually modifying the code on top of the mix 2 so i'm actually initially writing the code from h2 and then we start modifying the code and then we keep going uh and then uh if we reach the whole so we just return the pattern otherwise we keep going and um if x and y equal to the whole so we break and we do the another computation and we put everything into the steps but since the distance is measuring the steps and also the pattern so we just put the patterns there pattern and what's the directions we have in this case right now so we just use d as the direction to recording where we up to like what's the directions do we pick and the direction we pick we are adding that to our pattern uh we'll add that to our pattern okay so we're gonna add that to our pattern so when we compare with the distance we also have to modify that as well so that's gonna be step uh which is the integer represents like how what's the shortest distance and also the pattern plus d represents like the historical pattern like all the directions we picked before and also the directions we pick at this run the direction we'll pick in this run and we compare everything so if none of this worked and then just like before it used to be returned uh negative one now we're gonna return impossible it's a lowercase or yeah it's lowercase okay let's try that yeah it works yeah so let's go ahead and recap so what we doing we basically have our boundary defined and we have the initial position being changed the reason we changed is because this problem requires us to return the sequence of the directions we picked before so we're going to record that by using this but why don't we put this at the first spot we also want the shortest distance so we the first condition is we want the shortest distance so if we have server path having the shortest distance and then we can pick by lexico graphically smallest way and that's why we have the shortest distance on the top priority and the second priority is going to be the lexical graphic graphical and we also have the direction every single time we pick one direction we wanna we don't know if it's going up or going down or going left or going right and that's why we add one more parameter on top of the here and we know that if we pick up and we record that into the pattern and our distance will be also changed it used to be just recording the shortest distance but now we are sorting by two parameters one short one shortest distance another one is the patterns and we put everything into the distance and then we start doing everything just like before and the heap and it's distraught we're sorting by the shortest distance and we're popping out the pattern and the coordinates so if the coordinates already reached the hole and we just since we're directly popping this out from our heap the heap already taking care of the minimum looking for the minimum of distance and the pattern so we already did that so that's why the node we're popping out from the heap will be the smallest pattern and also the smallest distance so once we get that's our terminal position once we break from the terminal position and we can start looping for all the neighbors we have if we are never reached here and we can go ahead and exploring all the neighbors four directions for each direction for up we'll pick the direction up u stands for up so that's why we have the third parameter d to tracking the patterns we have and then we can start using three parameters to tracking where we go which direction we go and the distance and x and y will keep going and then so as long as we are not hitting the wall and we keep going oh we can modify this actually equal to zero and then like right here you have three more lines like the previous problem so we can backtrack one step um but look right here so what we did is we checking if the next position if we pick a direction we check if the next position will hit the wall if it doesn't hit the wall we keep going and we add the distance so the distance will keep rolling until we hit the wall until or until no i'm sorry until we uh we are going on top of the hole that's our destination so once we reach to the destination grid we can calculate it so we can see if the historical pattern plus this run will less than when we go into the hall in the previous time so we can reach a whole from a whole bunch of different ways we can reach from the up from the bottom from the left or from the right and if the new calculation is less than what we stored before great we find that even shorter distance or shorter pattern like even smaller pattern great we store that into the distance and then we push that into the queue great and the x and y remember it's going to be whole because we'll break from here and we're going to pop it out from here and green we got the solution and that's how we solve this problem by using bfs okay uh i think we're done and we're gonna move on to next problem i'll see you guys in the next video | The Maze III | the-maze-iii | There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole.
Given the `m x n` `maze`, the ball's position `ball` and the hole's position `hole`, where `ball = [ballrow, ballcol]` and `hole = [holerow, holecol]`, return _a string_ `instructions` _of all the instructions that the ball should follow to drop in the hole with the **shortest distance** possible_. If there are multiple valid instructions, return the **lexicographically minimum** one. If the ball can't drop in the hole, return `"impossible "`.
If there is a way for the ball to drop in the hole, the answer `instructions` should contain the characters `'u'` (i.e., up), `'d'` (i.e., down), `'l'` (i.e., left), and `'r'` (i.e., right).
The **distance** is the number of **empty spaces** traveled by the ball from the start position (excluded) to the destination (included).
You may assume that **the borders of the maze are all walls** (see examples).
**Example 1:**
**Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], ball = \[4,3\], hole = \[0,1\]
**Output:** "lul "
**Explanation:** There are two shortest ways for the ball to drop into the hole.
The first way is left -> up -> left, represented by "lul ".
The second way is up -> left, represented by 'ul'.
Both ways have shortest distance 6, but the first way is lexicographically smaller because 'l' < 'u'. So the output is "lul ".
**Example 2:**
**Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], ball = \[4,3\], hole = \[3,0\]
**Output:** "impossible "
**Explanation:** The ball cannot reach the hole.
**Example 3:**
**Input:** maze = \[\[0,0,0,0,0,0,0\],\[0,0,1,0,0,1,0\],\[0,0,0,0,1,0,0\],\[0,0,0,0,0,0,1\]\], ball = \[0,4\], hole = \[3,5\]
**Output:** "dldr "
**Constraints:**
* `m == maze.length`
* `n == maze[i].length`
* `1 <= m, n <= 100`
* `maze[i][j]` is `0` or `1`.
* `ball.length == 2`
* `hole.length == 2`
* `0 <= ballrow, holerow <= m`
* `0 <= ballcol, holecol <= n`
* Both the ball and the hole exist in an empty space, and they will not be in the same position initially.
* The maze contains **at least 2 empty spaces**. | null | Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path | Hard | 490,505 |
33 | hello and welcome to this video today we're gonna solve the problem search and rotated sorted array so in order to understand the solution of this problem it is necessary to know how to implement binary search and how to find the minimum element and a rotated sorted array but luckily for you I have made two video about two requirements so stop this video and go watch them and get back to this one so let's get started first what is the meaning of rotated sorted array a normal sorted array would have looked like this but a rotated sorted array is a type of data structure in which the elements of the array are sorted and ascending order but the array has been rotated by a certain number of positions for example considering the following array 3 4 5 then 1 and 2. this array is sorted in ascending order but it has been rotated by three position to the right so the question here is that they give us a rotated sorted array and then integer Target they ask us to return the index of the target if it's inside the numsler array otherwise return -1 and also you must write an algorithm -1 and also you must write an algorithm -1 and also you must write an algorithm with all flow gain runtime complexity so the Brute Force approach to solve this problem is to iterate throughout the rotated sorted array and try to find the index of the target but this solution has a Time complexity of all fan which will not pass and call in interview so we're going to use binary search algorithm to find the target but we know that binary search only work in a sorted array so how do we gonna Implement binary search in a rotated sorted array in sorted array there is an inflection index as the rotation so the first thing we're going to do is to find the inflection and Implement binary search and the two sourced arrays so let's say we have this input array we're going to do binary search and four five six and seven and do another binary search in 0 1 and 2. it's like two sources array inside one array first go watch this video where I explain how to find the minimum which is the inflection point and a rotated sorted array and go back to continue this video so once we're gonna find the minimum and rotated sorted array we're going to implement binary search algorithm from index 0 to the inflation point or to the minimum Point minus one so here we go we can't find the target so we return -1 and find the target so we return -1 and find the target so we return -1 and another binary search algorithm implementation from inflection point or we can name it the minimum to the last index so here we're gonna find it's at index four so we'll return index four then finally we return the max between the return value from the first binary search in the first sorted array and the return value from the second sorted array so let's jump according to solution the first thing we're going to do is to find the minimum Point inside the rotated sorted array so we're going to initialize a variable called minimum point and assign his value to be a function that's going to return the index of the minimum number inside the list and we initialize the find the main function that called with the input nums to find the index of the minimum elements and the rotated sorted array using binary search algorithm we initialize to pointer left and right then if the length of the list is equal to 1 will return 0 and also we check if it's not a rotated sorted array means that the left is smaller than the right number will return zero and we start the iteration well the left is smaller than right we calculate the middle then we set our condition if the number of the middle is bigger than the numbers at the right we move the left to Middle plus one otherwise we move the right to be the middle index finally we return the left index which is going to be the index of the minimum number inside the rotated sorted array so now that we have found the inflection point we split the array and use binary search algorithms to find the target inside the two sorts of the array we initialize a variable called Left array and assign his value to be a function that return the index of the target so the first array starts from 0 to the minimum Point -1 and another variable minimum Point -1 and another variable minimum Point -1 and another variable called right array that does the same work as the left array and the binary search for the right array start from the minimum point to the last index so the function binary search uh gonna take the renounce arrays and the Target and the left and right pointer then we started the iteration while the left is smaller than right if numps at the middle is equal to the Target we'll turn the middle index else if the middle number is smaller than the target we move the left to be the middle plus one otherwise we move the right to be the middle index -1 middle index -1 middle index -1 and if we don't find the target we return -1 finally we return the max between the -1 finally we return the max between the -1 finally we return the max between the left array value and the right array value foreign complexity for this solution is all flow again because we perform multiple binary search algorithm and space complexity is a constant time means of one because there is no extra space memory using thanks for watching see you in the next video | Search in Rotated Sorted Array | search-in-rotated-sorted-array | There is an integer array `nums` sorted in ascending order (with **distinct** values).
Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`.
Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 0
**Output:** 4
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 3
**Output:** -1
**Example 3:**
**Input:** nums = \[1\], target = 0
**Output:** -1
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* All values of `nums` are **unique**.
* `nums` is an ascending array that is possibly rotated.
* `-104 <= target <= 104` | null | Array,Binary Search | Medium | 81,153,2273 |
551 | this one is question number 551 student attendance record one so you're given a string yes and it's an attendance record for a student where each character signifies whether the student was absent late or present on that day the record only contains the following three characters a for absent l for late and p for present so the student is eligible for an attendance award if they meet both these uh following criteria so if we go down this criteria is the student was absent a for strictly fewer than two days total the student was never late for three or more consecutive days return true if the student is eligible for an attendance award or false otherwise so let's say what that condition is so we have two conditions one is a absent for a for fewer than two days so absent for freeware then two days the other one is el was never late for three or more consecutive days so for less than three consecutive days so what when it says this was never laid for three or more consecutive days that means uh more or equal to three but we're getting the rest of it like so it will be less than three here so not more bigger than three that means less than three so that's why we do for less than three consecutive thirds okay so this part is done so we understood the problem we got our two conditions now we want to uh as usual loop over uh our string so i think it's easy to understand that for f for character in s if you see okay so let's do the late first if um so if char equal to l right yeah then we add to our late let's say we have a late variable and it starts from zero so when we see an l we add to it okay um just um to understand this uh this is consecutive days so you don't just add it whenever you steal l in the next cases uh when you see something else you have to say late equal to zero so that it's just tracking the consecutive days also uh when you do that you also have to add the max value of that late inside a variable for example you want to have let's say max yeah let's do max underline late for example so you say uh and this one should be initialized to server first yep and you say if length is bigger then max underlying length you say max underline yeah so in this way you have that max linked value yeah so that's it um so if char character is l late plus one if late is bigger than max late max a equals to mate uh alef um okay so what does this alif do uh we want to check the absence now okay so the absence would be if char is equal to only um okay so that would say absent in this case you don't really need to make it through in any uh statement because you're not tracking down the consecutive days here so that's done and okay so that's for a and there's another case else i mean actually there's the rest of the cases here and in the rest of the cases you basically do date equal to zero here yeah so that would uh work let me just uh print out late and asset here yeah and this should be the max late actually yeah so in the case that we have ppa llp present absent lately present so what did i print out first we did max late so the max length is actually two yes and the absent is one so that should work so if we basically say return my slate less than three and absent less than two uh am i correct yeah fewer than two days for a yeah less than three consecutive days yeah that should work and it will return truth that it sees those two conditions so yeah that works for this case and yep it works for other cases so this is how you solve this question of student attendance record one you | Student Attendance Record I | student-attendance-record-i | You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
* `'A'`: Absent.
* `'L'`: Late.
* `'P'`: Present.
The student is eligible for an attendance award if they meet **both** of the following criteria:
* The student was absent (`'A'`) for **strictly** fewer than 2 days **total**.
* The student was **never** late (`'L'`) for 3 or more **consecutive** days.
Return `true` _if the student is eligible for an attendance award, or_ `false` _otherwise_.
**Example 1:**
**Input:** s = "PPALLP "
**Output:** true
**Explanation:** The student has fewer than 2 absences and was never late 3 or more consecutive days.
**Example 2:**
**Input:** s = "PPALLL "
**Output:** false
**Explanation:** The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.
**Constraints:**
* `1 <= s.length <= 1000`
* `s[i]` is either `'A'`, `'L'`, or `'P'`. | null | String | Easy | 552 |
643 | Hello Hi Friends Welcome Back Today We Are Going To Solid Problem 868 Maximum Average Saver 110 Problems Prevented Previously Was By Google S You Can See Date Of Birth Details Of The Problem Is Want To Mention The Type Of Account Created Has Videos For Live Today People While Preparing for Coding and Java Interview Activate the List Play List 2010 Solve Problems Explained with Examples Send Code and Job Interview Related Play List of Frequently Asked Questions Asked by Big Companies Like Amazon Google Apple Facebook Microsoft Please go through them Also please subscribe to The channel is so let's look into it and description happy lifestyle consisting of pain in teachers appointment as wearing of given link date has maximum average ballot unit and maximum average value 119 daily exclusion equal to absolute daily 1230 and elements of given here will win the Range of - 10020 the Range of - 10020 the Range of - 10020 middle-aged person to examples and share middle-aged person to examples and share middle-aged person to examples and share hundred-hundred is you can see father for example hundred-hundred is you can see father for example hundred-hundred is you can see father for example enemy is the area high the longest largest emperor f10q divide by four that is the same average 108 12.75 600 800 land for sale in 108 12.75 600 800 land for sale in 108 12.75 600 800 land for sale in districts will have to Written test will point to loud answer so let's look into this problem in more detail visit us with one another example and how they are going to solve this problem solve 2012 users sliding window of research to solve this problem so first merge will go through this example In Details So You Will Know About Sliding In Life A Process That They Are Going To Solid And Sliding Window Approach Lipstick Shoulder Of In Health Soe Latest Tech This Important For The Casual Vacancy 243 I Am One 4 112 212 That Hand To Right Members In This Foreign Direct ok so hai otherwise your request you to soul will have to take any white with length tubelight and how to find the maximum average survey report handed house sliding window approach pocket swift to and a text average hundred-hundred worship se 10 problem rate summit Summit hundred-hundred worship se 10 problem rate summit Summit hundred-hundred worship se 10 problem rate summit Summit objective and average is that so I lose average and sum so you can see taken place for is equal to six is the sum and average will is equal to six is the sum and average will is equal to six is the sum and average will be divided into this threat to avoid conflicts year maths average also sum maximum average rate 220 will keep track of What Makes Average Were Getting So In The Beginning Mitti Screen So How Sliding Window Actress Vriksh Is That's The Next Welfare 980 And Like Peeth * December And Will 980 And Like Peeth * December And Will 980 And Like Peeth * December And Will Subtract The First Woman's Liquid Will Soften 31 Pallu And Will Add New Value * Soften 31 Pallu And Will Add New Value * Soften 31 Pallu And Will Add New Value * Dasham Which Mins That Listen Will Update and Maximum Average from Three to Senior Day Will Keep Continue Sun Will and Three * Tenth and They Will Fight Three * Tenth and They Will Fight Three * Tenth and They Will Fight for Toilets Objects of Writing That Is So Voice You Can See in Twelfth Class 3 Minus Point to Minus Point Plus 302 11-11 -11 Point to Minus Point Plus 302 11-11 -11 Point to Minus Point Plus 302 11-11 -11 New Song End Average 55.58 5.5 Should Not Have To New Song End Average 55.58 5.5 Should Not Have To New Song End Average 55.58 5.5 Should Not Have To Update Our Maximum Average Because If Average Is Already More Than The Current Average Lutu Forwarded To Next Element And They Are Moving Fast Element Right Doing This Liquid For Example In This Way You Can Shake you can imagine that is sliding window size sliding window ac window so you can see in new window 8 strength from the current president 11123 plus one ride it to poori dhawan minimum and average will be four divided by two is equal to e Don't Have To Updater And Maximum 21 Maximum It's Already More Than 250 Shyam Pure Sliding Window Approach Workshop But Now Again We Wish You A Knowledgeable Tools Lights And Disawar New Window 98 Per Against Wind Up To Software Redmi 4 * 4 And Were Subtracting The Part One 4 * 4 And Were Subtracting The Part One 4 * 4 And Were Subtracting The Part One Like for the previous element which moved out of the window free mode of the bina height to three will support you in a lift plus furious 8 divider maint is 5.5 is the furious 8 divider maint is 5.5 is the furious 8 divider maint is 5.5 is the new Sampann and five divided by two is 2.5 to zinc 2.5 to zinc 2.5 to zinc chavinath update vmax sun yang We are going to our sliding window selection window will move like and share thoughts and next to eliminate element will come into hello and one is out of the Wind reduce voice out of the window name soul will attract one from the current comment will develop into Corruption 0 Mins Total Will Be 5 - One Is 4 Plus Two Equal 216 December Total - One Is 4 Plus Two Equal 216 December Total - One Is 4 Plus Two Equal 216 December Total Right Now So Total 1616 Divided By Two Is Back Now You Will Update And Maths From Six 28000 Is More Than 6% Javania Maths Now You 28000 Is More Than 6% Javania Maths Now You 28000 Is More Than 6% Javania Maths Now You Will Again Movers Sliding Window 98 b coming let decide software remove inform and they are doing to into the window which mins that will attract row from sure restore plus to equal 214 officer appointed committee that and proteins vitamins finserv average vowel current average is more than seven say will leave It is city and power sliding window has reached a point where I can created all data and after doing so will just returned maximum value of average exam answer right short hair you can select 6323 powder sliding window and fennel hui hai sliding window of Side servi record to that was leading man to have two sides and tips movie so sliding window mouse what ever you element with added into the window and will be added into time what ever most out of the window will be stopped from the prosperous to calculate the New Average 34th Sliding Window Approach Used To Solve This Problem Of Mass Am Amazed And The Big Of This Algorithm Will Be Order Of Android Viewers Bluetooth Patience 150 Shoulder Option To Calculate Maximum Average Kabir 110 Problems Of Force Google Hangouts Look Into The Implementation Details Not 123 You Can't Sit Per Come First Features Create 1800 Average Way Receive New Updates Reviews To Calculate Average Of Power Window Write And Start Blogging For Calculating The Average Of Window Side For Example Difficult To Calculate Average Of Air Filter Element Subscribe Skin Hair And You Get From Is Going From 0258 Calculated And After 10 2009 Sliding Window Approach A That And Its Order VPN To en-light Will Order VPN To en-light Will Order VPN To en-light Will Create A Double Variable Contact Max Average And Definition Of Wasted With Current Average Height Reviews Average Dhawan Tattoo User Like And Internet And The End Tweet Keep Updating During The Process Of Wedding Window To What Happens Name Is A Will Have Enter Suzy Ko 125 Plus Karat Is Not Starting From Zero And Is Going Under The Name Spelling Including Namaste Are Angels Equal To A Pencil Eye Plus Gorgeous Subtracting Norms Of soil from the average and they are adding name subject * average vehicle yes you can senior subject * average vehicle yes you can senior subject * average vehicle yes you can senior producer difficult sliding window things so what ever elements going out of the window courier subtracted cervi and water element is getting married into the window wedding get into every year and You Yaar Visiting Thank Yaar Tips Hai Bridge In Greater Than Maximum Commercial Maximum Average Yadav Favorite Product Will Always Have The Maximum Average End Of The For Loot Incident Looters Ne Aadam Actor Wages Subscribe Just Want You To Understand 108 Dual Air Show Amazing Going To Take Medicine Types Of River Distinct Wise And Used To Get To Show You 200 What Friend One Year Doing This For Watching Hui Calculator This East Direction Windows Live Rate Fair Reward Fight For Plus Two Equally Divided By Two Is 309 Water To English Now In This Follow What This App Does Water Into Every Statement Do It Is A Window Was Discovered The Wind Of Previously Known Here May Creating Window Light Moving The Wind Of Some Window Will Be Dushman Na Vrat This Is The New Window Sonth It Is Doing This Previously Calculated Summit Will Subtracted From December Lizards Six - To It Will Do And Talked About What Ever Visit Will Attend This December Lizards Six - To It Will Do And Talked About What Ever Visit Will Attend This New Elements Class And Right To That Is What This Statement Will Do Electronic Solid Will Get New Average Distracting The Previous Value Hair Salt Cleaning And Adding Plus Norms of Great Soldier One Teaspoon Cardamom Sisai And Destroys Sorrows And Subtracting Aaye Dushmani Rai And Descending Heaven Lights Of Which Is Equal To 8 Plus Splitting - To Hai Ki Is Equal To 8 Plus Splitting - To Hai Ki Is Equal To 8 Plus Splitting - To Hai Ki Record 22512 16 2012 Average And Will Divide By Tv Chintu Lal Pandey Tweeted 6 From Date 34 Water And Tool Update It Is Necessary Facts Regarding What Is Means Of Third Sliding Window Approach We To Latest One Set On Maximum Were Discussing Sadhi Se Example That They Have Discussed And Share Bilkul Tutu Sauveer Wikileaks Vacancy New Year Greeting Output S8 Bizarre Correct Front This What Do You Were Also Getting Out Put A Previously Pic WhatsApp Text Look Dus Saanp Pahere Will Be Twelfth Class Forest Department Gears Up To Date With Maximum Average Software Plus 1416 Divided By Two Is The Rate Come So Common So That's The Work's To-Do List Suno Latest Work's To-Do List Suno Latest Work's To-Do List Suno Latest Modified Depend Subject Handsfree So I Have Increase The Sliding Window Size 239 So Let's Shift Change Lining Joint Suno Officer Maximum Average Advisor 6 Develop You Can See 6 Mins A Special Place For Sudesh One Is Not The Maximum Festival 34 Points Is The Maximum Air Filter Element Twelfth Class 1416 Plus Two Is Equal To Canteen Divided By Three Layers Is Equal To 680 23.2 6 And The Strong Layers Is Equal To 680 23.2 6 And The Strong Layers Is Equal To 680 23.2 6 And The Strong Answer Is Senior Right Solidarity Was The Sliding Window Problem Works And Pandu Maximum Early Morning Solid Shrinkage Take Care Pimples Day Time Jab To Make More Than 200 Grams Pal Summary Work In Points Quick 1234 Uske 12.75 With Answer Hai 12.75 With Answer Hai 12.75 With Answer Hai Tu Yaar Cutting Correct Answer Clear Solid Gold And Difficult Test Cases Wealth A Fruitful Gittu Mature The Given Test How Kind Also Passed In This World Can Submit There Solution Hai To Aap The School Was Recommended Tube Test Oil From Which Suno Pimple Software Getting Married Soon They Are Confident Question Submit Power Solution Hai Which 27.8 Par Cent For Dasha Mission Which 27.8 Par Cent For Dasha Mission Which 27.8 Par Cent For Dasha Mission School This Very Good Sudheesh Bhavesh Hi Hui Can Solve Maximum Average Morning Problem Sad Paaye Google Using Sliding Window of Fresh Approach Share the Time Complexity for the Solution His Staff When He Is Written Down for You Dare to Time Complexity is of the order of one clear 5000 years Of using couple of constant no external data structures and liquid is on time nothing like cataract so let's white sperm complexities and duckworth sogdu submitted the solution and it's getting into contact with talking 100 am a few of preparing for job interviews also check out my list Play List Details and Harold Problems Explained with Example Sanjeev Ko Details Visit Consist of Variety of Different Problems Black Dynamic Programming Binary Search Earliest All the Best and Different Problems Priority Queue Related Problem Optimization Problems Dry ginger and Gokhru Definitely Behavior Preparing for Coding Interview and Also for Job Mein Interview Teri Playlist College Jaun Interview Sauth Aur Gokhru Battle Solitaire Lot Of Fun And High Nice Screening Interview Questions Were Raised By Limited Company Slide Amazon Google Facebook Microsoft Fennel That You Find This Video Helpful And If You Like This Video Please Subscribe And Like It Please subscribe The Channel Show The Video Can Reach To More People Who Are Preparing For Coding And Divine Truth They Can Also This Video And I Can Also Be Benefited By Watching It To Uske Hriday Par Preparation For Interview Subscribe Fit And Thanks For Watching The Video | Maximum Average Subarray I | maximum-average-subarray-i | You are given an integer array `nums` consisting of `n` elements, and an integer `k`.
Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted.
**Example 1:**
**Input:** nums = \[1,12,-5,-6,50,3\], k = 4
**Output:** 12.75000
**Explanation:** Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
**Example 2:**
**Input:** nums = \[5\], k = 1
**Output:** 5.00000
**Constraints:**
* `n == nums.length`
* `1 <= k <= n <= 105`
* `-104 <= nums[i] <= 104` | null | Array,Sliding Window | Easy | 644,2211 |
986 | hey guys persistent programmer here and today we're going to do another leak quick question interval list intersections and this is an awesome question and this question reminds me of the meeting room's question in lee code so let me know down below if you want me to do a video about that as well but um the theme of these types of questions are to check if you understand how to calculate intervals in given arrays right so that's what we're gonna do today if you haven't subscribed to the channel go ahead and hit that subscribe button okay awesome let's get started great so for this question we're given two arrays in sorted order and the order of this arrays is that this is the first element here is the start time so this is the start and the second element here is the end time right so this is the case for all the items in the array um for both a and b now what we need to find is um the interval and there are a few things that we need to notice here to understand what is meant by an interval here right so we are already given this in a sorted array so what i've done here is i have mapped out the interval for a and the interval for b great so first let's see how we check for an interval given our start and end points for one case so what i've done here is i've taken um this first item in a and the first item in b and i've mapped them over here so we can see that a start is at zero okay and we can see that a's end is at two so this is zero and this is two right and we can see that b start is at one and b's end is at five so what we're looking for is this intersection here right so that's how we find one interval and how do we compute this how do we what do we tell the machine to do to get us this result so what we need to check is we need to first find out is b start um less than a's end so b start is 1 and a's end is 2 so we are checking if b lies within that framework right so if this is our case then yes we do have uh intersection here and the other thing we need to check is if a start is less than b's end so here you see 0 and 5 so we're comparing 0 to 5 and we need to check hey does this start before the b ends and if yes then yeah there's a possibility of our intersection happening in the between so let's look at this these numbers again and validate what we just learned so i need to see if my start is less than this end these end right so if we put this in a linear scale that means yeah there's an intersection that exists between 0 and 5 because there are numbers that are less than that since our array is sorted right so okay so that is the first condition that is the first thing we need to check okay great um so yeah i do have an intersection and what is the next condition i need to check is if this b start is less than a's end so these are the two things we need to check so we can see that b start is one here and a's end is um two here so this is all we are going to get from this so stay with me here i know it looks like a little bit strange at first but once you do these kind of problems um this is in most cases for intervals that's what we're checking we're either given a sorted input or we're given an unsorted input and we need to sort it and then do exactly this so we will check our overlaps by taking the start of the first element and comparing it to the end interval that so yeah this is what we're doing like we just need to check if our interval exists between these range so this is the first check and then this is the second check so is our b start less than our um a's end okay so i hope this helps you understand the idea of how we calculate intervals now let's take this perspective and apply it to our bigger picture here in this graph great so we just saw how we uh found this overlap here now how do we calculate that and get our answer here as one and two right so what we need to do is we already know there's overlap because we are checking the start of a and we're seeing if that is less than our end of b here so if that's the case we know that there is an overlap for sure in this range um now how do we calculate that this is the amount of overlap how do we calculate that right so what we do is we take our maximum value from these first two starting positions so what is the max of 0 and one the max is one so we take the max of that and for the end we need to take the minimum value because the maximum value is over here at five and that won't be the correct overlap if we give it five so we need to take the minimum value of the last two points right so we need to take the minimum value of this point and we need to take compare it to this so the minimum of two and five is two so that's how we get a 2. all right so now we can't just be staying here at the same spot we need to check if there are other overlaps in our graph right so how do we know when to move forward so we can check if a's end is less than the b's end right so b's end is here so if i can see that oh my first endpoint is done and my b's end point is further away i know that my work for this overlap is done this green overlap is done there's nothing else to do here so that's when i move my a pointer to look at the next position the next overlap so that's how that's when we move from the first position to the second position so now we're here in this second position um in between five and ten and our b pointer is still here in the first position so what do we do now we do the same thing so we check if our five is less than or equal to five right so we're comparing the first element in the a to our last element in the b and yeah five is equal to five so that's how they're getting this five and five value and our second case still holds true where we check if our b's first element is less than our a's end all right so that's true that's why we can say yeah so five is um our next element that we need to put in our result array so this is the result array we need to return so yeah this question actually asks you to find these overlaps as well where there is the same number so we need to consider this 5 and also put this in our result array so five and once we have that five we can tell that okay a's end so we need we're checking this is and again so b is still here and we're checking the a's end now a's end is greater than um b's end which is still at five here right so this is when we know okay well our work with b is done because we've covered all the possible overlaps we can cover so there is one here and then there is one here at the five right so these two are already covered so there's no more work to do here and that's when we move the b's pointer forward in this position great so we're looking at this range now between 5 and 10 and 8 and 12. so we know that the overlap is between 8 and 10 right so this is our overlap so again how do we find our this value so what we do is we take the maximum between five and eight and the maximum is eight so this is where our interval starts and from here what we do is we take our minimum between 10 and 12. so you see here 10 and 12 and the minimum is 10. so what we need to put in our results array is 8 and 10. okay now i want you to go through the rest of this on your own and solve it manually the same way we were doing here so that will help you understand um the solution and help you manually move the pointers so you're able to see okay at what point does my interval end and start okay so i will go ahead and discuss the time and space complexity for this and then review our solution before we look at the quote so the time complexity for this will be of n so we will only iterate over the array once and the space complexity is going to be o of n if you consider the result array to be part of the space but if you don't consider it to solve this problem we don't really uh have any auxiliary structures that we are using so the space complexity will be off one if we don't count the results array okay so what do we need to do so let's go over our um steps in conclusion before looking at the code so we want to find the overlap range and how do we find that overlap range we are going to see if a start so i will say a start is less than or equal to our b's end and that's what we did here right so we saw between um 0 and 5 right so there exists an interval if a start is less than or equal to b's end and b start is less than or equal to a's end right so we are just seeing if this b and b start fall within the range of a that's all we're checking here right so that's the condition to find the overlap so this is the case we need to consider and the second case is how we calculate the results so we take the maximum at the first position so max of first position and then the min of the second position so again we looked at our example so in the case of 5 and 10 we took our max here right so 5 and eight we got eight is the max and the interval starts over here and it ends at the minimum between 10 and 12. so that's how we push the values these are the values we need to push in our result array and the last thing we need to do is move our pointer so we move our pointer when we have a case where a's end is less than b's end so here we saw that okay a's end is 10 and b's end is 12 that means i have already covered this green section of the input array and found the overlap here so i have no more work to do and i'm gonna move on to the next position so that's what you need to check and if this is not the case then that means that um the b has ended so that's when you need to move the b pointer so that's the third thing we need to do is move our pointers awesome so if this all makes sense we'll go ahead and write the code awesome so i'm back in the code and what i've done here is i've just initialized the a pointer and the b pointer and this will keep track of how we move through the positions in the a list and the b list so i've done that and i've also initialized my result array so this is what we're going to return and push our values to so what i want to check is while my a pointer is less than the length of my list a and the b pointer is less than my list length of my list b so this is when i'm going to check because if we're at the end of the list that means we no longer need to keep moving our pointers because they will be out of bound so that's why these are the conditions for the while loop so to make my life easier what i'm going to do is i'm just going to declare the start and end points for a so if you remember we're given um we're given the input like this so we have our first start and our end positions here so this is a sample of how we're given the data so what we need to do is we just want to grab this first position from the first part of the array and the way we do that is we just say okay where does a start right so ace i'll just call it a start so it's very easy to follow so a start is my first element uh in where my pointer is so if my pointer is at this position i need to grab the first element from this so that's at zero index right so i'm gonna say a pointer and at position zero so this is just grabbing me the start and end position of the pointers great so i just put all the values here and i'm able to grab the start and end pointers at each of the list a and list b so after i have that what i need to check is if there is an overlap and this is the case we discussed in our solution so we need to check if a start is less than equal to b end and b start is less than equal to a and so this is how we find if the overlap exists so if b end is existing so if b start and b end exists between um a start and a and that's what we're checking here and if that is the case then what we need to do is we need to calculate what values to put in our result array so we will say result dot append and we will put um in the first position remember we need to take the maximum value that we can find in the overlap so we will put take the max of my a start and b start and then in the next position we need to put the minimum of our a and b end so that's all we're going to do here oh b okay so that's how we're populating the result array and after we're done that all we need to do is just move our pointer so we're going to check is if a end is less than b and so that means a has already ended and b is still ongoing so there is no more work to do in that interval for a because a's and is already done right so after we've done that what we can do is we say a pointer just move the pointer forward so a pointer plus equals one okay else what we need to do is if b's end is less than is and that means b has already ended and there's no more work for b to be done over there because its interval has already ended right so we just need to move the b pointer forward so we'll say b pointer plus equal one and what we need to do after this is just go ahead and return our result so we'll say return res okay so let's make sure there's no typos okay run code okay awesome so yeah that works so let's go ahead and submit the solution awesome accepted thanks guys if you like this video please go ahead and subscribe to the channel give this video a like and if you have a different solution please post it in the comments below it could be in any other language it's just gonna help other people look at the solutions and understand and solve this problem themselves thanks guys happy coding | Interval List Intersections | largest-time-for-given-digits | You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**.
Return _the intersection of these two interval lists_.
A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`.
The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`.
**Example 1:**
**Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\]
**Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\]
**Example 2:**
**Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\]
**Output:** \[\]
**Constraints:**
* `0 <= firstList.length, secondList.length <= 1000`
* `firstList.length + secondList.length >= 1`
* `0 <= starti < endi <= 109`
* `endi < starti+1`
* `0 <= startj < endj <= 109`
* `endj < startj+1` | null | String,Enumeration | Medium | null |
1,031 | hey guys this is jayster how does everything going uh in this video i'm going to go guys one zero three one maximal sum of two non-overlapping sub arrays are during non-overlapping sub arrays are during non-overlapping sub arrays are during the array we need to return maximum sum of elements into non-overlapping elements into non-overlapping elements into non-overlapping contiguous sub-arrays which have length contiguous sub-arrays which have length contiguous sub-arrays which have length l and m and then get the maximum sum of them so if suppose we have a ray like this we need to return one element and two elements so we could choose nine and the six five so we got twenty if we for this we turn three eight one and eight nine so we got 29 yeah so how should we do it well what's so let's first analyze how could we solve this when there is only one when okay when what for one subarray with specific and then well suppose we are going to return uh length of two and the maximum sum would be just uh yeah just uh use sliding window right sliding window to get the maximum max sum right so this is o n we go n so for two there will be two sub arrays is we suppose if we have uh fix the left uh array let's separate here then we get need to get the maximum amount and the rest right if you choose the sub array in the middle we need to get the maximum to the left and to the right and if we move the sub array along this away from left to right it means we need to get the maximum from left to right and uh get the maximum from left to uh against the maximum from for the head and for the tail but when we are moving on to it the leftist max could be derived uh while we are looping through it but the max to the right is not right we need to pre uh pre-calculate the maximum from right uh pre-calculate the maximum from right uh pre-calculate the maximum from right to left well cool so the idea is simple move through the uh a for size l for each we need to get the max the teal uh get max of m uh at the head and they get uh get max of get the maximum of m at the rare right this needs to be pre-calculated to be pre-calculated to be pre-calculated so yeah so that's it let's first gets the pre-calculated uh sum first gets the pre-calculated uh sum first gets the pre-calculated uh sum m at the rare maximum of m elements okay cool so uh let's do it so this is max m star okay so start the index should be eyes from this is length minus one so this is n minus two so this is two element so i start from a dot net minus m i should be bigger than z equal to zero so we move the start index from right to left right so let current max minus infinity ah no i made a mistake can we shoot i from the length one let current sum zero if we only update the maximum array when there is enough event email uh element right so we uh sum plus with a i yeah and then if i smaller or equal to a dominant minus m we the maximum right so let's max current max minus infinity so current max equals mathematics current max current sum and do we update the array max m start from i equals current max so we now we get the uh data here so now we need to uh process l cool oh okay so we need to also keep track of the maximum of m and the sum of l right cool so uh they will be let current sum l zero and let current sum m zero let them current max m minus negative infinity and now we do loop through it start from left to ah i plus l element one elements itself so l minus one this is the last index uh which is smaller than eight on end okay so we update the sum ah i made a mistake this is a problem if there this is it we uh-huh gets this sum and then after we get the max we need to remove the previous one yeah i made a mistake this is it so if i smaller than a dot n minus m this is sliding window so current sum should be subtracted with um a i plus m right if there's one element the yeah this is the current sum right this is the current right uh this is the right current sum cool so we need to do the same to the m from left we plus with a i and if i is bigger than m minus one we need to current sum uh m subtract it with a i is the target this one this is net this is star phone so and it should be if it is one element then it should be previous one so i minus m is two yeah minus one cool so this is get we get the curve right uh current sum m and what we do we just get the maximum right so current max m would be math max and the current summit okay and also we need to get the max sum minus infinity so we get the maximum from left and we also oh there's a problem we get the maximum here we need to actually keep track of the maximum because the m suppose the l is like this string we need to get the maximum here i see so actually we need to keep track of that also okay um here let's you say cost max m and add now basically it's the same if it is this bigger than it then we update it to the right sum and if i is bigger or equal to oh what happened excuse me oh something wrong about my keyboard i didn't modify any code right oh here okay and bigger than one bigger than it we actually need to update the current max and then update the array which is current mag max m in that max and that i equals current max m yeah this is it and by the same time we need to calculate the sum of l also so uh calculates the sum for l we do the same uh current summary l plus equals a i is bigger than l minus one we current sum else subtract with a i subtracted my l and this is the sum so this is the update the final max so here's the most exciting part max sum should be maths max up oh max with okay seems like my keyboard doesn't have any batteries wait a second okay now it has a power okay for i uh we should likes for l likes option here we need to get the max from left ending at here and then this right so we get a current max end at what is it should be i subtract yeah right if i is one element then it's pure yeah this is right and plus current sum l plus max and start from i plus one right so the maximum sum will be up updated with a second sliding window and finally we could return the maxis up allow me to review this code one more time before i try to run the code we keep the start from array to keep track of the maximum sum for f for m we do through from right left i found a start from so yeah start from yeah this should start from zero and then calculus current sum if it is uh longer than the m we subtract the element then to the right this is the get together right sum and we start updating the current max and set cache it to this array cool and now we are doing the same to do to catch the sum for m which is ends at update i uh this looks good and then we do the same to calculate the sum for l yeah uh-huh yeah uh-huh yeah uh-huh so here's a problem i found it if only we only update the i here right yeah this and there is a problem actually this might not be this might be negative so this will be uh undefined so i'll say cost max and max left okay max sum m left like hey uh from lab cools if i minus l smaller than zero then it should be zero if not it should be this and max m from right i plus one is smaller than then we should use is smaller than then we should use is smaller than then we should use it if not we should set it to zero cool so now we will handle the uh boundary and finally we could just return the max um it's right on code ah exact we got the not a number so uh yeah let's log the mag the array well it's right and let's log the this zero is uh hmm ah made a mistake yeah it's not actually smaller than zero it should be sad should be um this is the key if it is smaller than m minus one then it should be zero right and again from right if i plus one like a plus m and minus one if it is this is a start and this is the end right yeah if the end yeah this should be right oh okay something larger really some we getting this wrong let's so we are getting um let's log the current sum l a slice i minus l plus one i plus up one and gets a maximum from left maximum okay we now handle five six five l is one so i think i made a mistake here we need to oh this is right ah yeah okay for six current sum is six and this zero and this is 16 13. we're getting you right and for two we get 11 and 13 so 20 the l i know what happened you should be gets either not both but i found some problem i is bigger than this one if it equal to this then we still could calculate the sum right so i think i made a mistake here current sum i'll say if i is bigger than or equal to i minus 1 i can do the update yeah oh nice looks great oh come on what return i did this like one year ago let's see what i did wow it's very uh concise oh did i write it anyway so this solution actually and logic here actually could be moved into a function right and let's see what happened here we got it minus infinity what 10 1 6 9 10. so i think we should turn sound plus maximum this i let's see what happens infinity there's no zero one two three i means the end i mean right yeah stupid i am stupid okay ah this looping conditions just uh makes my brain miserable okay come on yeah okay finally we did it but the code i think we could make it better like separate them into a function right like something okay like this and cost max no it should be sum l and constant max m in that and then we created separate function and finally we will move through all the uh index find get the sum l and just to calculate so the for loop for this one could be much conciser yeah and let's analyze the time and space time this is a linear this is linear yeah so linear time space we use one two array to hold the temporary maximum so it's linear space cool so that's all for this one hope it helps you next time bye | Maximum Sum of Two Non-Overlapping Subarrays | add-to-array-form-of-integer | Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`.
The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlapping.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[0,6,5,2,2,5,1,9,4\], firstLen = 1, secondLen = 2
**Output:** 20
**Explanation:** One choice of subarrays is \[9\] with length 1, and \[6,5\] with length 2.
**Example 2:**
**Input:** nums = \[3,8,1,3,2,1,8,9,0\], firstLen = 3, secondLen = 2
**Output:** 29
**Explanation:** One choice of subarrays is \[3,8,1\] with length 3, and \[8,9\] with length 2.
**Example 3:**
**Input:** nums = \[2,1,5,6,0,9,5,0,3,8\], firstLen = 4, secondLen = 3
**Output:** 31
**Explanation:** One choice of subarrays is \[5,6,0,9\] with length 4, and \[0,3,8\] with length 3.
**Constraints:**
* `1 <= firstLen, secondLen <= 1000`
* `2 <= firstLen + secondLen <= 1000`
* `firstLen + secondLen <= nums.length <= 1000`
* `0 <= nums[i] <= 1000` | null | Array,Math | Easy | 2,66,67,415 |
123 | hey guys welcome back to another video and today we're going to be solving the lead code question best time to buy and sell stock version 3. so normally these type the stock based questions i personally find them a little bit confusing but one thing once you understand the concept of how to utilize uh state machines to solve these problems it actually becomes a lot easier to understand so what i'm going to do in this problem is i'm going to explain what they are from scratch if you don't know what it is don't worry it's very simple concept and we're going to go step by step of building our state machine and then we're going to try to convert the data or the visualization we came up with and we're going to try to convert that into code okay so let's just start off by reading what the question actually is so in this question say you have an array for which the i element is the price of a given stock on day i so what this means is uh the first element is going to be the price on day one the fifth element is going to be price of day five so on and so forth we need to design an algorithm to find the maximum profit you may complete at most two transactions okay so also saying is that once we buy so buy a stock we can sell it we can buy another stock and we can sell it so we can't do more than that so we can do a maximum of two transactions and that actually makes this question a little bit easier according to me anyways uh now we need to know so one thing we need to note is that you may not engage in multiple transactions at the same time so what that means is let's say i bought a stock and now i'm holding it i cannot buy another stock in that period that's not possible i can only buy another stock once i have sold what i currently have so let's take a look at a quick example before we go on to the whiteboard okay so over here uh we have these prices right so uh just a quick example so this is at the index two so that means that's the price for day two pretty straightforward so what do we do over here so what we're doing actually is we're buying on this day over here we're buying on day four and we're gonna sell over here so on day six so what is the profit so let's just go step by step on this day since we're buying for zero rupees or dollars or whatever uh in that case um we're not going to be spending any money zero is basically free so our profit as of now is zero now we're going to sell that for a price of three and when we sell that we're gonna be gaining profit so now we're gonna get plus three so our profit is going to be zero plus three which equals to three again what we're gonna do over here now is we're gonna buy over here so when you buy you need to spend money and where you're spending money you lose profit so we're doing three minus one and right now our profit is two and finally we're going to sell at a price of four and over here we're selling at a price of four so our profit increases by four two plus four is six and we get our answer over here so we just went through it real quickly just to understand the question but how can we do this step by step in order to get the solution in the most optimal way so to do that let's uh look at the idea of state machines all right so what are the conditions or cases that we have so our stock or our program per se can be in several different positions it could be in a resting position right so this could be like a position where it's not doing anything we could be in a holding position so think of this position as you bought a stock and now you're waiting to sell it so that's one of the positions you can be in and the other position is when you sold a stock sorry stock so you sold a stock so now you might be waiting for a time where you can buy again or you're done with uh selling for a total of two times so over here we have the very uh we have a restriction and the restriction is that we can make a maximum of two transactions so these are the things that we kind of have to keep in mind and we can use this to draw our state machine well what is a state machine in very simple words it's used to represent a different the different states the program can be at one point so let's just look at all of these four states or how many of our states so in the beginning we're going to start off with a zero state right so uh this is a zero state this is the state that we're always going to start off in and at this stage we don't have anything we don't hold any stocks our profit is going to be zero all the time if we stay in the state so what can happen here we can rest right so what this error represents is that we can stay in the state for however long and when we're staying in the state we're trying to look for a time when we can buy that's when we move on to our next state so let's say we found something for a good price right and we want to buy it so now what we're going to do is we're going to buy and when you buy you move on to the next state i'm going to call this state a so in state a you have now bought a stock and right now you're holding the stock so you bought the stock and you're just waiting for a time when you could possibly sell it right so this is one of our states and the profit over here is going to be negative because when you're buying it takes away money from you right and we don't make money until we sell it so let's say we now have a time when we can sell it this is when we move on to our next state so i'm going to call the state b right and this is going to stand for when we have sold so right now we were holding a stock but now we sold it so now we're going to switch states so over here once we switch states uh we have made profit hopefully so we're going to just add whatever value of price it is to our profit so uh and after this we can stay in this state for however long since we're waiting for the next time we can buy and again similarly we have a c so state c is going to be the same thing where we end up buying something and we're going to stay here while we're holding that stock and finally we reach our end state and so that let's call it d so d is going to be our last and final state that we could reach and over here oh we are done we sold our stock and there's nothing left to do we're just going to stay here and we're done with the program so these are the four states we have and i'm not really going to consider this state per se and the reason for that is because it's always going to be at a value of zero so now that we have this i think we have a pretty good clarity on what the question is and how we could possibly approach it so what we want to do is we want to convert this diagram or the state machine that we made and we want to convert it into code form how can we do that over here we can kind of split it up into two main sections uh the first being buying and the second being selling right so those are kind of two actions that we have right and that's what determines how we change states so that's pretty important so let's take a look at buying so in both of these conditions we are starting off at a state called state right so think of state as a variable and it's going to be the current state that we are on so when you buy you can actually be in two states so when you before buying you're currently in a state which uh you still didn't buy anything you don't have anything but you're waiting for waiting to buy so you could do one of two things you can keep waiting so if you keep waiting you're still going to stay in that same state your other option though is to actually buy so what we're going to do is we're going to take the previous state so let's just say the previous date is called x and what we're going to do is we're going to subtract that with whatever the current price is and the reason for that is because when you're buying you're spending money so our profit is going to decrease so these are the one of two things that we're going to have that is gonna happen and in order to choose between which one we want we're gonna take the maximum between these two okay similarly let's look at selling so when you're selling you can do one of two things you currently have a stock and you're waiting to sell so right now you could stay in your same state you could stay at this current state that you are in and your other option is to actually sell it and when you sell something you're moving from one state to another and you're making profit so you're going to add that price to your profit so you're going from state x plus price and if you still don't understand what x means just think of x as the previous state which you're coming from right and so we're going to take that plus price so and again to choose which value we want to stay in we're just going to choose the maximum of it pretty simple and uh why maximum you might ask well if you just look at it logically when you're selling you want to be able to gain the highest profit and when you're buying you want to lose the least amount of money possible and it's just the concept of buy low sell high pretty simple okay so now let's actually transform this into code so our first step is going to be to check whether the prices list actually has values in it and to do that what we're going to do is we're going to see if so if not prices and in that case we're just going to end up returning zero okay so now that we took care of that we can start with making our state machine and let's just take into account all of the states we had so we had a we had b we had c and we had d right uh these are going to correlate to the previous diagram so if you want to draw that comparison try you can try doing that so a is going to be initialized with whatever is at the zeroth index so the first element so price is zero so over here it's actually not just going to be priced at zero it's going to be negative prices zero and the reason for that is that we're actually just going to be looking at the profits directly so when you're buying the profit will be negative right or at least it would decrease and for everything else we're going to give it a value of negative infinity and the reason for that is because all these values are going to get overwritten regardless so that's why we want to just give it a value of negative infinity and to do that in python you do float and then negative n so that's the value of negative infinity okay so now that we uh kind of now that we've initialized our variables we're going to iterate through each of our prices so for price and prices now we're going to kind of change out the values of each of our states and we're going to do that similar to how we did it in our diagram so let's start off with a so when we're at a we have one of two options we can either stay there so that's uh this represents just staying in a or we can buy that stock so if you were to buy that stock it would be negative price and again price is the current price of that day okay now let's go on to b so now we have b and in b similarly we have two states one we can stay in b so when we're staying in it we it means that we're waiting to sell a stock and two what we could do is we can buy the stock from a and sell it at whatever the current price is so we're gonna go from a to b so we're gonna say a plus price and it's gonna be plus price because we're selling it okay so now we're going to go to c and similarly max between c and c is going to be the current state it's at or we could buy it and when we're buying it we're going from b to c right we're changing states so what we're going to do over here we're going to do b minus our price and finally we have d which is going to be considered as our last state and over here we're going to take the maximum between d and the pre so in d we're going to be selling right so we're going to go from the previous state and increase our profit so we're going to c plus the price and that's it and sorry and we're going to end up returning the value of d since d is actually going to have the highest value and over here i know it might be a little bit confusing well you might be thinking well what if we actually just only make one transaction and to explain that let's just go into debugger real quick and i think it should be pretty clear over there okay regardless when you submit it our submission did get accepted so yeah okay so over here you can see the value so these are the prices that i chose this is same from our first example three five zero three one four okay and this shows us the value of our variables so in the beginning a has a value of negative three b c and d obviously have negative infinity so legit let me just show you what happens as we move through it so negative 3 stays as negative 3 and over here b is actually going to change in value so what are the two options it has it can either stay in b so that's negative infinity or it can move to a plus price so a has a value of negative three and the price is three so that's going to be zero so i think you understand that but what i really want to explain over here is through our first iteration even though we iterated through it only one time we somehow still got the answer for the value d and this sounds a little bit confusing because when you think about it or go back to the diagram which we found d actually represents the value of when we sell so we buy sell buy and sell again so we perform the action a total of two times so how is it that in the first iteration we have a value for d that actually doesn't even make sense and the answer to that is actually pretty simple so all the value of d is doing it's kind of doing two of the transactions in the same day so it's buying on day one selling on day one and it's repeating that again buying on day one and selling on day one again so uh currently our price value is three so that's the first one let me just iterate through the next one okay so now that we iterate to the next one our d value still exists it's a value of zero so what happened over here now is we bought on the first day sold on the second day and then afterwards we bought on day two and sold on day two so if you want to see uh you could keep going on and i would highly recommend you to use the debugger if you still don't understand it you can go buy it step by step and see how the variables are changing at each of the step i'm not going to do that since it takes quite a lot of time iterating through each of the prices but i highly recommend that you try it out if you still have any doubts and finally thanks a lot for watching guys do let me know if you have any feedback or if you want me to solve any specific leak code questions and don't forget to like and subscribe if this video helped you 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 |
473 | okay guys welcome to our channel with sunny and in this video i will be talking about the problem matchsticks to square index is 473 and problem is one of the medium type problems of the lead code okay so let me give it a like over here because this problem has explained me or you can also say taught me a very new good concept that i'm going to deliver to you now how to optimize your code how to make your code have a good runtime and what are the sequence of steps that you need to follow for a good optimization technique to make your code much more readable as well as so it will run very fast okay so moving further to this problem okay so we have been given an integer array matchsticks where matchsticks of i is going to denote the length of the ayat matchstick that is we will be given a sequence of arrays you can see and every number is going to denote the length of a particular matchstick you want to use all the matchsticks to make one square right and you should not break any stick okay though one thing's that you need to focus over that we are going to use all the matchsticks right and uh that is you cannot lift one matchstick and check it out if there exists something that is favoring our answer you are not going to do that we are going to use all our matchsticks and to make one square this is also important you have to we have to make exactly one square and we should not break any stick to make it suitable to forming a square right so all the sticks should be taken uh that is as it is but you can link them up and each matchstick must be used exactly one time okay so if a particular matchstick has been used we are not going to reuse it okay so return true if we can make this square otherwise false that is following this sequence of conditions if we can make a square we are going to return true otherwise we are going to return false okay so i am also going to discuss the example right so for now let's look over the constraints and whether it is going to help us or not and what is this is what does this constraint is going to convey to us right so matchsticks is length is like 15 okay so can this help us like whenever the constraints are going to be very small like n here the length of the array is like only 15 okay so one thing that i want to suggest to you guys that whenever you will find some length exactly equal to very smaller value like around 10 15 or uh in worst case like 20 or 20 we are not going to say like 16 17 18 or all of that then you must think of a recursive approach of your solution or the backtracking approach backtracking for like n is around 8 or 10 okay like recursive approach backtracking you are going to think for these of the approaches when n is going to like very small okay and when n is like around thousand or ten power five you're not going to think like a recursive approach and traverse all the possible cases and check it out okay so here n is very small we are going to use a recursive approach okay one doubt that arises in your mind how this recursion is going to help us to solve this problem okay the same doubt arises in my mind also when i was solving this problem and i have got some suitable opinion suitable thinking when i have blowed over my mind over this question then i have got the logical answer also i am going to share all of these to you guys for now let's uh move further to understand this problem in a little bit detail and we will first look over the example and understand how the answer is coming and what are the sequence of optimization that we have to do to reach the best solution for this problem and okay for now let's move further okay so first let's understand how the answer is coming suppose we have some array right and we have the sequence of elements like 1 2 and it's again 1 and again 2 these are the 5 elements of the array and we need to find a square such that we are not going to break any matchstick okay so let me remove this one we are not going to break any matchstick also we are not going to reuse any matchstick so there are two conditions right so how we can build any square where every side length is exactly same it is like a build a length 2 over here and again build a length two over here and now we are going to use two things right uh build a length one over here and then again join it with another one again build a length of one over here and as you can see there are two ones we are going to use each one exactly one time that is this one then all the remaining twos okay so you cannot break any matchstick like you are going to break these two into two ones and you are going to use that also reusing any matchstick is not possible okay so this is the basically example or explanation of this problem okay so let's move further to understand how we can uh move further or build up the idea to solve this problem in the best efficient way okay so first i am going to discuss what are the base cases these cases that you need to consider or you can also say that you need to take care okay these are the common conditions that when you start solving this problem you are must you must have been thinking these base cases and what are these base cases suppose we have been given some array area of matchsticks and this is actually the sum okay so this is actually the sum of all the matchsticks right suppose you have to build some square okay now suppose s is the sum of one of the side and s is again the sum of another side because since it is square all the sides are same now 4s big must be equal to this sum right so when you check it out if uh okay so if sum is not uh being divisible by 4 or if sum is not a multiple of 4 you can't get the answer right so for a given uh matchsticks array of matchsticks first thing you have to check it out for building a square where every side length is going to be exactly same the one of the first thing that you are going to check it and what is that the sum of the all matchsticks must be a multiple of four okay so then only you can proceed otherwise you can't be proceeded okay so this is one of the best cases i'm going to write down here like this sum must be a modulus 4 must be exactly equal to 0 okay now another thing that i need to write it about what about okay so when this condition passes like sum is now a multiple of 4 then you need to check more conditions and what are these conditions now let's say we are going to denote t as our target and target is now sum by 4 and we need to build a square where every side length has the value exactly equal to t right so i'm going to build a square where every side length is exactly equal to this t value okay now you have to think upon that uh what about the case when any matchstick length let's say mi when any m i is going to be like strictly greater than the value of t this is going to be like really very important like when any of the matchstick length is going to be like greater than strictly greater than the target that we want to achieve that is the square that we want to achieve if any of the length is going to have the side length exactly greater than the target value we cannot get that is we cannot build up any square with a given series of matchsticks right so we need to ensure that uh any of the length that is all of the length sorry all of the matchstick length must be what uh at most the value of t right so i am going to write down one condition uh another that is the next condition okay so i'm going to all mi so matchstick length must be at most this t value okay now if this condition passes and also this condition passes then only i can move further okay and what are the more conditions okay just tell me one thing that we okay so i'm just writing down one thing we are going to use recursion okay and what is the basic idea of recursion that is you have to include this any of the matchstick into your answer and consider this as that including this matchstick can be like can give us the correct answer or we cannot get that is we cannot pitch the correct answer also there are two possibilities including a particular matchstick mi can give us the uh like can give us the correct answer like we can get a valid square or in does not including this mi that is a if we are not going to include this mi at a particular side length what about the next one we need to check all the possible cases right if you are not going to understand this right now no need to worry about i am going to explain this recursive step in a little bit detail in just a few moments later okay so for now you need to ensure one thing also and what is that one thing okay so let me write down clearly that this is my third optimization or you can say third base case what is that base case sort all the mi values in what non-increasing order in what non-increasing order in what non-increasing order and what is the reason behind that right when we are going to just use a particular matchstick to a particular that is when we are going to include a particular matchstick that lets say a matchstick value five okay so let me write down a clearly okay so this is order and when we include some particular matchstick five and then we include some particular matrix again five and there are a lot of matchstick right okay so we have some sequence of matchstick like five six seven or some values of five and suppose there exists some another matchstick whose value is like 10 power 9 okay and these two conditions are like satisfied then only i'm going to talk about this third condition right so suppose we have some sequence of matchstick having the value length exactly very smaller like five six seven and there exists another matchstick whose length is like very big like 10 power nine and these two conditions are already satisfied okay then what is the best case to improve your run time right if you are not going to use this statement uh i guess you are fine you may get tle but uh for better case for improve your run time you need to sort the matchstick in non-increasing order non-increasing order non-increasing order okay so suppose we have some matchstick whose length is like very big and you need to build up a side whose value whose length exactly equal to the target then the best case scenario is to always pick up the maximum length of this matchstick first that is when you are going to include the maximum length of matchstick then the probability of getting your answer increases as fast as possible the recursive step becomes concise and concise means the number of recursion calls becomes very less if you use the this condition that is first process the higher value of matchstick length then we are going to move further to the smaller values suppose you are going to use the first smaller values then it will take a lot of time because the bigger values are coming at the last step of the recursive calls okay then the processing takes much time that is the recursive call stick much time so these are the three steps you are going to do okay this is basically a checking step this is also checking a step but this is like a good optimization step and if you are going to do this why you are going to do this for improving your runtime improve runtime okay now moving further to the recursion steps how we are going to build up the recursive things and what would be the sequence of quotes let's move further to understand this okay so we are now at the state where all these conditions are like satisfied that is first to checking condition last one also now moving further to the recursion initiative what i have done is like maintain uh four size vectors initially i have not maintained the four sides but i have used the variables but to like to make your code readable and concise i am going to use a four size vector and this is going to basically denote the sides of square like a vf sum square and this is the first side and this is second set this is the third side and this is the fourth side and the add is also going to denote the something this will store this all the sides like this first side what are the length of the sides that is the total current length of this side one and current length of this side to current length of the side three and the so on right okay and also we have some matchsticks right we have some and length size array and this is going to denote the size of the matchstick and note that this array is sorted in non-increasing order right so i'm in non-increasing order right so i'm in non-increasing order right so i'm also going to write this thing this is already sorted in non-increasing order now what i am going non-increasing order now what i am going non-increasing order now what i am going to do in recursion step all the recursive functions passing the parameters like passing the initial position of the matrix that is being operated right so suppose we have some sequence of matrix like five six okay that is sorted right now four three and two suppose i am just initially passing this one 5 then it will work upon this 5 and how it will start working upon like ok so this is 5 1 so what i am going to do is include this 5 into this that is 4 there are 4 sides right on a side 1 side two side three and side four okay so include this value of five into this first position of this arrow note that this is going to return the sides of square and then recurs for the next position like because if this 5 is satisfied over here and what is the checking condition that is whenever you start including one of these matchsticks that is let's say this position is like s of i and this is the s vector whose size is 4 you need to ensure one thing right whenever you want to include any matchstick of a particular length you need to check one condition s of y that is the current side length that it is holding plus the value that you are including into your current side and the value is 5 must be what less than equal to this target t and this is important and this is t is actually sum by 4 and we need to notice something that we want exactly the value of t for every side length right so you need to ensure that this condition holds otherwise you cannot proceed suppose this condition holds then what you are going to do since it is a recursive step you will increment your this pointer that is the pointer pointing at five to the next step four okay and when you are at this one again you are another in you are in another recursive function where you need to check whether including four to this five is satisfiable or not right so you want to check again now my current uh this is again a four size vector now in again another function what you are going to do include four to this position now initially it contains the value five plus you want to include four now and if this is less than t yes this should be included suppose this condition fails okay when this condition fails then the pointer and which point i am talking about this pointer like i have already tried to put this forward at this position okay so we cannot put this then i will try to put this 4 to this position okay when i am able to put this four to this position like this condition satisfies okay then i will move to the next position that is increment this position to this position okay then i will try to put three to back to this position if i can then i will move my this pointer to the next one otherwise if i cannot be able to put 3 to this position i will try to put my 3 to this position and if i can then i will increment this position to this next one otherwise then i will try to put my three back to this position and so on this is actually basically the recursion step whenever you are trying to put a matchstick to a particular side that is include that value to a particular side and if that happens it does not claims that you cannot put aside then you can just increment your current site's length value that it is holding and if it cannot put the side then you are you have to just check for the next side that you want to improve right so basically this is actually easy one writing the recursive thing easy but the main thing of this question is that how do you are going to optimize your code right you can do the recursive step even i can also do you can also do but checking these four condition although i have left one optimization that improves your runtime i am going to talk about that optimization while discussing the code okay so for now let's move further to the coding part and let's understand how the sequence of operation is going to happen and how i am going to write my code and efficient code okay so let's move further okay so you can see uh there are a lot of like tles three tls because i'm not able to initially figure it out the like correct solution with the optimization then i've got some accepted technique by uh this one is like i have got accepted by sorting the values mastic values in non-increasing values mastic values in non-increasing values mastic values in non-increasing order right you need to do that then i got accepted but the runtime is very bad then again some optimization then i've got this one then finally i've got the good code like of 36 ms okay and this is what the secret optimization dynamic programming optimization that i have to down okay so let me discuss this one directly right okay so i've also commented it for the readability of this code right okay so this thing this already happened i will also discuss it about for now let us move on to this actual main function make a square right so i will it will take a parameter of sticks right and first i will find out some uh that is sum of all matchsticks length and i am doing this without accumulate function of stl then i will sort in non-increasing order then i will sort in non-increasing order then i will sort in non-increasing order and the reason is it decreases the run time as well as reduces the chance of that is the chance of tla since bigger sticks are going to be processed at first this is going to be like really very important to improve your runtime as well as to reduce the chance of this tle condition sort sticks in non-increasing order and sort sticks in non-increasing order and sort sticks in non-increasing order and this sides is going to maintain the what is the current side length of every side there are four types of sides of the square and every length must be same and this is going to show what is the current state of the length of side that are being included to our answer okay you can see previously what i am what i have been doing here is like not maintaining the sides vector as just taking the parameter of side 1 side 2 side 3 and side 4 also you can also do like that but taking this one is like a good one for include improving your readability of the code right now i have to check the condition if sum is not a multiple of 4 or sticks length that is the given vector must be at least 4 and if it is not that is any of the condition holds to we are going to return false denoting that we cannot build a square of side four whose length is uh same now sum is now our target length and length that is the length of each side so i will divide it by four now check it out if any of the sticks has the length exactly is to be more than the target side length that we want to achieve then i'm going to return false also and this can be easily done by checking the first value of this array being sorted in non-increasing array being sorted in non-increasing array being sorted in non-increasing order already right so sticks of zero is greater than some strictly greater than some return false otherwise do the recursive step okay now that comes the main thing recursive step so i will check it out the base condition of this recursion that is every side is exactly equal and it is matching with the target value and what is the target note that the target is actually sum by four sum is the sum of the matchsticks length now this if this happens then return true otherwise return false okay now you note that this is the end condition that i mentioned in between these two uh these four conditions right so start iterating four times and check it out for a particular site if my current position of matchstick that is the current matchsticks can be included in sides of i if it can be included and how we are going to check that check whether on adding my current matchstick length increases the target or not uh not i'm not writing that increases the target it is like on adding my current matchstick to a current side that is holding my current sum of the sides that is been already included if on adding my current matchstick length to this one is has the new value exactly strictly greater than the target value we cannot move further that is this matchstick cannot be included into that side length okay that uh that side which is holding the sum right or this condition happens already happened okay so this is going to be like really important i'm going to discuss in a minute for now i will move further to this one okay or that is if my only including my current matchstick length to my current side that is holding the sum is strictly greater than the target new value or this condition holds true continue means that i am not going to use this matchstick to put into my current side sum otherwise in increment your sides of i by current matchstick length and records for the further subsequent matchsticks and if it comes to if it returns to this recursion you are going to also return to that yes there exists some valid square otherwise you need to decrement this sides of i also okay and if all the condition holds and we are not going to fit some return as true we are going to return as false right this is basically the recursion initiative now comes the main thing what is this already sorry already happened sides and i okay so this is like when you look over this dp optimization you can see i'm passing my current position i that is the current side number and the sides vector and what i'm checking is for all these sides which are strictly less than this my current position you can see i less than pose and if there exists some side who some side sum whose sum exactly matches with my current sum that is sides of i exactly method beside suppose i am going to return to that this condition is going to be true so i'm not going to move further okay so this is basically a condition that avoided that avoids the repetitive recursive calls and what is that repetitive recursive calls let us try to understand that suppose we have some 5 3 7 9 we have some certain state of sights that is the sum of the first some that is the side one is going to hold this some side two is going to hold this some side three is going to hold this sum and side four is going to hold the sum okay so i have done something wrong okay so i'm going to use again five over here five three five nine okay suppose my current matchstick length is six and i need to check it out if on adding six to any of these positions whether we can add this or not right so suppose i am trying to add this to first position that is first side 5 plus 3 then my new vector is 5 plus 3 5 and 9 right this is my current one and suppose if i'm arguing to third second position right now to three plus six and it is five and it is nine okay so you must be take care that i have done some mistake you have to do like five plus six okay five plus six three five nine five three plus six five that is i'm adding six to this first one then i'm trying to add this six to second one and then i'm trying to add this six to five one and so on okay so when you try to add six to this third position uh you need to take care for that one thing that is five three and when you add this to five plus six and then it comes over nine you can see that there is a state that i am going to that is i am going to call another recursive call for this condition and this recursive call is going to exactly match with this recursive call why you can see the there are two parameters same like five three and again five plus six five three again five plus six and then it is nine okay so it means that we are again calling the our recursion with the same value of parameters and it is not going to be useful and how it is not going to be useful uh suppose uh this step when you put six to this step and when you call a recursive uh that is when you recurse for the next of the position suppose this step on adding six to this system return false okay on adding six to this step it returns false then it is obvious that when you add six to this step it will also return first because the state of the parameters of the sites are really same so it is not going to be useful to move to this step right so this is the optimization so i'm going to check it out whether there exists some value which is already matching with my current value right now okay so this is what already happened function is going to check it out okay and you can see that how it improves the runtime from 1804 to 36 ms and it is wonderful right so the recursive step is this and already happened function is this which is actually the dp optimization okay so if you have any doubts i will recommend to mention in the comment section of the video so that we are aware about that you are getting these doubts and we will help you guys to move further with these doubts and to get it cleared okay so i will ask the viewers to like this video share this video and do subscribe to youtube channel for latest updates thank you for watching this video | Matchsticks to Square | matchsticks-to-square | You are given an integer array `matchsticks` where `matchsticks[i]` is the length of the `ith` matchstick. You want to use **all the matchsticks** to make one square. You **should not break** any stick, but you can link them up, and each matchstick must be used **exactly one time**.
Return `true` if you can make this square and `false` otherwise.
**Example 1:**
**Input:** matchsticks = \[1,1,2,2,2\]
**Output:** true
**Explanation:** You can form a square with length 2, one side of the square came two sticks with length 1.
**Example 2:**
**Input:** matchsticks = \[3,3,3,3,4\]
**Output:** false
**Explanation:** You cannot find a way to form a square with all the matchsticks.
**Constraints:**
* `1 <= matchsticks.length <= 15`
* `1 <= matchsticks[i] <= 108` | Treat the matchsticks as an array. Can we split the array into 4 equal halves? Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options! For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this. We don't really need to keep track of which matchsticks belong to a particular side during recursion. We just need to keep track of the length of each of the 4 sides. When all matchsticks have been used we simply need to see the length of all 4 sides. If they're equal, we have a square on our hands! | Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask | Medium | null |
378 | hello everyone aaron here and welcome back to leat code today we are doing the kth smallest element in assorted matrix problem so let's jump into the instructions given an n by n matrix where each of the rows and columns is sorted in ascending order return the kth smallest element in the matrix note that it is the kth smallest element in the sorted order not the k distinct element you must find a solution with a memory complexity better than n squared so n squared would be copying the whole matrix um so here 1 5 9 10 11 13 12 13 and 15 elements the matrix if we were to write them out in order looked like this so one two three four five six seven eight is this one we know something about this matrix so for example if we were to look in index eight one two three four five six seven eight that happens to be the same here but notice this 12 and 13 are in a different order so one thing we could do is flatten this matrix into a list sort the list and then get the eighth positional element that is going to use n squared memory and it's going to use um n log n time because that's the fastest way you can sort these things i guess you could argue you can do it with n time um with this uh sorry no that's going to be n squared log n uh because it's going to be n squared elements that you're sorting and that's the fastest way you can do that however we know that every row and column is already sorted in particular 159 are sorted 10 11 13 assorted and 12 13 15 assorted so we can take another view on this i think and that's that we're actually doing a merge sort now a merge is not going to be n squared log n it's just going to be n squared because i'm going to look at the 1 the 10 and the 12 but i don't care about the rest of these things and then look at the 5 the 10 and the 12 and the 9 the 10 the 12 because i know each row is implicitly in order i don't need to keep searching the whole row i just need to search the front thing maybe or the current element of each row that i'm looking at and then we're going to keep that count that up to k not all the way at the end because once we've found the kth element we're done then the question becomes can we do better well so one thing we can do to avoid using n-squared memory is we to avoid using n-squared memory is we to avoid using n-squared memory is we don't actually need to do the merge sort we just keep track of what we would do to do a merge sort and then just don't actually do the merge so that when our when we're going to fill in what would be the k element in the sorted array we just return that element we don't actually say where the k say we're at the second element and that's before k we don't actually put that one into the right position we just carry on over as if we had put it in the right position i'm wondering if there's a abounding we can do as well so because we know these are in order we don't need to start at the beginning so hang on if i just to exemplify what i'm trying to say here if i draw this out one actually uh let's do this one five 9 10 11 13 12 13 15. the earliest the eighth element could come would be one two three four five six seven eight it would have to be on this diagonal basically or well no it would be this diagonal or later if we had a whole lot of repeats um no actually we do know it's on that diagonal don't we somewhere on this diagonal is the element we're after so for example if i was after the fifth smallest element i know it's going to be somewhere along this diagonal because one two three four five is eleven it's that one there if instead we had one 10 20. uh 2 11 21 3 12 22 1 2 3 4 the fifth smallest element there is still that one um let's go with the fourth smallest element so in this original one uh zero one two three four it would be this one here and whereas over here will be this one so it's 10 in both cases by pure coincidence um but they're always on this diagonal so what that actually means is for k we can compute all the indices of diagonal that it would actually be on and then we just need to find the minimum on that uh do you need to find the minimum of the diagonal there's a 10 and a 5. hang on no it's the maximum on that diagonal isn't it no that's not true either how do i know when i'm looking at a diagonal which one so here obviously it doesn't matter i'm looking for the eighth smallest one here one two three four five six seven eight it's 21 not 12. ah because if we're looking for the sixth smallest element we know it's on this diagonal so i just need to work out what the no hang on 12 or 21. if i'm looking for the six so these are six and eight if i'm looking for six i want the smaller one i'm looking for eight i want the larger one on these ones here if i'm looking for the fourth smallest element there's a two and four oh hang on no because there's another example here isn't that one two four three five and three six twelve ten twenty one two three four i don't know it's on this diagonal because there it's up there all i know is this diagonal is the earliest frontier okay so waste a bit of time doing something wrong there anyway let's get the core going um let's do okay we'll count down from k index is equal to zero times len matrix and what i want to do is effectively y k is greater than one um in fact uh yeah while k is greater than one i want to do something and i want to return matrix uh that's what i've got i need to do we're trying to a deep index into the matrix ah no hang on uh i'm getting myself a little confused here so what i want to do is all the indices zero 1 for each of them and then what i want to do is i want to move these forward and in the end i'm going to be left with k is equal to 1 i'm looking at the right one and then what i want to do is i want to return minimum of matrix i j for i j enumerate indexes so zero gets indexed zero one gets into zero two gets indexed at zero the minimum of those is what i want now so while i'm in here i'm filling in that k position in my sort for merge sort um then i want what i want to do is i is the min let's do this again except it's going to be j i for i j in enumerate indexes but this time i want to make sure i'm just getting the index indexes i gets incremented by 1. so the logic here is i'm looking at the 1 the 10 the 12. the minimum of those is the 1 which is at position 0. so i want to increment that one forward so now looking at the 5 the 10 and the 12 and so on and so forth the fives are getting smaller so that gets incremented i'm a little bit nervous about this actually um because first off i need to make sure i'm looking at matrix i j um if n is land matrix j is less than and else infinity um the reason i'm doing this is basically if i'm gonna step off the end here ignore it basically it will never be the smallest thing it's gonna i'm gonna set it to infinity just i've stepped off the end um so stepping through this n gets set to three in this case i'm gonna have three zeros one for each row while k is greater than one k gets decremented so it starts at eight this is an asset to seven um then what i want to do is i is the minimum so i is the index of the rows where it's the smallest of the keyed value in each row 1 10 12. it's gonna give me zero because row zero the first row is the one that contains the smallest value so then it gets moved along so now my indexes indices is one zero then it's going to compare the 5 the 10 the 12. and it's going to see 5 is smallest it's going to go to 9 10 and 12. that's still going to be smaller so that gets pushed off the end effectively um if j float you know what let's let's just call it that this is going to be val j this one is going to be val i j i think that's how you do that in python um let's quickly run this i'm not super confident at the moment ooh seems to work let's use all the test cases nice um let's use this one again but no let's use one of our other more unusual ones one two four three six twelve five ten twenty asking for position 4 seems to work what happens if we ask for position seven so what's the complexity of this because down here there's some follow-up could down here there's some follow-up could down here there's some follow-up could you solve the problem in constant memory it's not quite constant memory because it needs these n indices floating around which is a bit of a pain could we solve it in order n time no it's still order n squared so at least it's not order n squared memory that's an improvement anyway let's submit this because it seems to be working fantastic it worked could we do better let me just think for a moment because this solution isn't terrible if i was to look at this i could look at it and kind of understand what it's doing i think there's something to be said about once i know roughly where it can be i can ravel in a specific way i think like once i know where the frontier is i've got quite a lot of information is that it is it's do i know it's somewhere on this front here i know it's a 5 3 or 2 or a 4 for example so it's not just the diagonals the whole frontier within the matrix i think i do know that actually so here it really is truly it's like this one here it really is truly this diagonal but out here it's not this diagonal it's this whole frontier or could it be here too no i think it has to be like this could it ever appear there no so i think there's something here and then i don't need to once i know it's on this frontier each of these could be the k-th element and once i know that one of these is the k-th element i work out what their min and max indices are now hang on if i know yeah if i know what their min and max indices are as in like put in sorted order these vary between like three and well if i'm going for k4 i don't really care what it goes up to but i know the minimum here could be three so then i'm just looking for position for another smallest is three one two three i'm looking to put these in order and then go up right no that's not right because it smallest is two isn't it one two see another one yeah there's something there i'm rambling we're done problem solved this is a valid solution for problem 378. i'm going to leave it there today i will see you next time bye you | Kth Smallest Element in a Sorted Matrix | kth-smallest-element-in-a-sorted-matrix | Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_.
Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element.
You must find a solution with a memory complexity better than `O(n2)`.
**Example 1:**
**Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8
**Output:** 13
**Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13
**Example 2:**
**Input:** matrix = \[\[-5\]\], k = 1
**Output:** -5
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**.
* `1 <= k <= n2`
**Follow up:**
* Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)?
* Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun. | null | Array,Binary Search,Sorting,Heap (Priority Queue),Matrix | Medium | 373,668,719,802 |
292 | today we're going to solve lead code 292 nim game so the question says that you are playing the following game with your friend initially there is a heap of stones on the table you and your friend will alternate taking turns and you take the first turn on each turn the person whose turn it is will remove one to three stones from the heap okay so you can either remove one stone from the heap two stones from the heap or three stones from the heap finally the one who removes the last stone is the winner of the game okay so what the question asks us to do is that given n which is the initial number of stones in the heap we should return true if we can win the game assuming that both you and your friend play optimally right and if we can't win the game then we should return false that means if our friend wins the game even though both we and the friend play optimally then we should return false okay so let's try to see how to solve this and gain some intuition about this so just by reading the question it isn't actually easy to figure out or like get a lot of intuition about what the solution should be right so how do we approach this question then a general practice in problem solving is to start small okay so let's take the smallest example possible that we can think of let's say that we have one stone in the heap okay so ah whoever has their chance okay so let's say initially there was one stone in the heap okay so whoever has the chance initially can just pick up this stone and win right so whoever has the chance will win when there is one stone in the heap right now we know that initially the first chance is supposed to be ours so if initially there is one um stone then we have the first chance and we can win right similarly if there are two stones we can pick both of these together and again win right and if there are three stones then we can pick all these three together and win right so that's well uh and good but what if there are four stones now we know that we can't pick all four of these and win right we have to uh pick either one or two or three okay so what happens when there are four stones like what are the different possibilities that can happen the first thing we can do is that we can either pick one stone right and if we pick one stone then our opponent gets the chance and he sees three stones on the table okay so now he can pick all three of these and our opponent or our friend can win right if similarly if we take two stones out of the heap our opponent will be left with two stones and it will be his chance now okay that means our opponent will be seeing this kind of a situation that he has two stones and it's his chance right now okay so again he can pick both of these and win right and finally the only other option we have is to choose all the three uh choose the three stones given in the heap right so in this situation our opponent will have his chance now okay and he'll see one stone lying on the a table right so he can pick that and win so in all the like no matter what i play if it's my chance when i have four uh stones on the heap okay then i'm going to lose okay so whoever has their chance when there are four stones on the heap will lose okay so that's a interesting thing that we saw now let's think about what happens if there are five stones okay so if there are five stones okay and let's say it's your chance again the first chance so what can you do you can pick one stone right and what will happen is that after you pick this one stone and remove it will be your opponent's chance right so he'll see four stones on the table now okay and we know that if there are four stones on the table whoever has their chance is going to lose right if they see four stones on the table and it's their chance to pick now they will lose so our opponent will end up losing no matter what he does right that means we will win if there are five stones just by simply removing one stone and leaving our opponent in a situation where anything he does will end up in him losing okay similarly if there are five stones we can take out two okay and leave our opponent in a losing situation again okay and if there are six stones we can take out three and leave our situation in and leave our opponent in a losing situation again right but what happens if there are eight okay what happens if there are eight stones on the table we can't get our opponent to a losing situation now okay because we can't remove all four of these stones right we can only remove one two or three we can't remove four right so if i remove one okay i'm going to leave my opponent in a winning situation right if i remove two i'm again going to leave my opponent in a situation where he can win if he plays optimally okay and if i remove three then again my opponent will be in a situation where he hits his chance and there are five uh stones on the heap so if he plays optimally he'll be able to win right so i see that when i get eight stones i'm again going to lose okay and we see a clear pattern emerging here that if there's one two or three i can win if i have the first chance if n is four then i'll definitely lose right then if n is anything between four uh and so if n is like five six or seven then again if i have the first chance i'll win right but if n is eight i'll lose again and this pattern keeps following okay so what we see is that for every f like for every kind of multiple of four okay we end up losing okay so if there are if the initial number of stones is four and it's uh and initially it's our chance because that's how it's given in the question then we'll lose if it's eight then we'll lose again okay if it's 12 we lose again okay but if it's any other number okay then we are going to win always so that's it that's all that this problem reduces to okay it was kind of like a riddle or like a brain teaser to figure this out figure this pattern out that initially if you have some number of stones that is a multiple of 4 okay then you are going to lose that means if n mod 4 is 0 where n is the initial number of stones on the thing then you can't possibly win no matter how you play right but in all the other cases like in all the other cases if n mod 4 is 1 or 2 or 3 you can win okay so this is all we have to code up now and coding up and coding this up should be fairly simple okay so let's go and implement that now okay so the code for this should be fairly simple right the only situation in which the person whose chance it is loses is if there are if the there is a multiple of four number of uh stones in the heap right so because it's our chance first then we'll only lose if n is a multiple of 4 right which means n mod 4 is 0 okay if n mod 4 is 0 then we lose so we should return false right and in every other case we can uh end up winning okay we have a strategy that lets us win so else we return true now that's it that's all that the code is so let's try to run this great so it works in on this sample case let's submit it now and great so this code obviously works it was a really short and simple code thank you for watching the video i hope it was clear the algorithm was clearly explained and this was just kind of like a fun brain teaser problem so hope you guys enjoyed it and keep practicing | Nim Game | nim-game | You are playing the following Nim Game with your friend:
* Initially, there is a heap of stones on the table.
* You and your friend will alternate taking turns, and **you go first**.
* On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
* The one who removes the last stone is the winner.
Given `n`, the number of stones in the heap, return `true` _if you can win the game assuming both you and your friend play optimally, otherwise return_ `false`.
**Example 1:**
**Input:** n = 4
**Output:** false
**Explanation:** These are the possible outcomes:
1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.
2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.
3. You remove 3 stones. Your friend removes the last stone. Your friend wins.
In all outcomes, your friend wins.
**Example 2:**
**Input:** n = 1
**Output:** true
**Example 3:**
**Input:** n = 2
**Output:** true
**Constraints:**
* `1 <= n <= 231 - 1` | If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner? | Math,Brainteaser,Game Theory | Easy | 294 |
399 | morning everyone how are you all I hope you are doing extremely good so today let's solve this problem evaluate division this is Elite code daily challenge problem so it is a medium level I think you can able to solve this uh try to keep some sort of Pomodoro Technique like 25 minutes you try the problem and after 25 minutes you are not getting the problem then come and see the related topics what are the topics they are following try to understand like which concept can I use then you keep pomodo technique for 25 minutes try to solve it if still you are not able to solve it then you can come here come over here and watch the video solution or you can go to the solutions and you can see like what are all the solutions existing this way you need to learn so let's solve this problem I think you have tried to solve it and after solving only you are coming and watching this video and try to watch till the end guys so that you can understand the problem easily and I will explain you like what are the intuitions we followed while solving this problem here you are given an array of variable pairs equation and array of real number values in here you give an equation A and B it states that a divided by B is equals to 2 because value of I represents the equation a by B A by B is equals to value of I suppose you consider this a by B the value is 2. and B by C we may see the value is 3 in this way here G has given and yes he says that we need to read and here again some queries we will see like with the inputs and then we can come to any conclusion and if there is the answer we need to return that answer if the answer is not present we to store minus 1 and we need to return it and each says that the input is always valid you may assume that evaluating the queries will not result in yourself he is stating that 0 by 0 won't exist 0 by 0 will not exist suppose a by B is 2 and a by B is 3 this is contradictory right so this is also notice so this type of contradictory scenarios are valid you need to see otherwise we will get confused so let's solve this let's understand with this example so yes when a baby is equals to 2 and B by C equals to three suppose you want to find a by C what you will do I will divide it a divided by B and B divided by C that's it right BB get BB will get canceled and we will be remained with a by C and suppose he has given d by a what is mean by b by just we need to 1 divided by 1 Upon A upon B so it will be 1 by 2 we need to just divide it dividend and the division should be interchanged and he has given a divided by e d e does not exist in this input so we can say there is no e so I will return minus one a by E what is a by it will be same so it will be 1. like you can cancel it I like this you can say that it is 1 and a by x that does not exist in the uh input equation so I will return minus one after I think you got like what are the inputs and what are all the scenarios so let's see how we will solve this problem uh you are going a and you are going to be your n1c suppose you watched up your a byc what I will do I will so I want to like I can store some I can come to conclusion what is the c or you can get a conclusion like what is B and we can get to a conclusion like what is C in that way we can solve and there is a another thing which I want to say that uh suppose you want a to c you can see this suppose a by b by C and C by D here is given a by B is X B upon C is y and C a bond is a upon B will be x b Upon A will be 1 by X here will be undershot right so uh a divided by B is equals to 2 then B divided by is 1 by 2. that is and let's understand this suppose e is given a upon d what we can do a upon B into B upon C into C upon D if we do this what it will happen BB will get cancel BB will get canceled c will see will get canceled we will remain with a bonding by this what we are understanding we are multiplying the 6 into this Y into Z to get the answer is equals to X into Y into set and suppose he has given d by a what you can see I will start with the T D upon c upon B and B Upon A now c will get canceled BB will get canceled we will remain with d Upon A what would be the answer D upon c will be 1 by Z into 1 by 5. into 1 by X I think you got the intuition like what exactly we are doing so we can say that we can consider the values as an graphs he has going strings and each string is a graph in that way we can solve this problem I will explain you like how exactly if there is a path uh if there is a suppose he has given a by e what you will do I will calculate a by B by C and C by D and e does not exist we'll return false and we will say that a to e there is no path if there is an O path we will return -1 -1 -1 I think you got the logic like what exactly the what is the math intuition this is a math intuition and let's see how we can implement this using we can solve it using DF phase as well as BFS but if you go with BFS there will be lot of code and it will be like little bit of confusion and Sim DFS is pretty straightforward let's see the code and I will explain like each and every part here I have taken map why you can see the constraint you can if you see the constraint carefully these are lowercase letters and AF length can be fine so what is saying is that I will give what he is saying is that I will give a b c d divided by e f g h i some said you can consider four five characters you can give and you can give some value like three by one uh if in the query if he has given a b c d and Z what it will happen if it takes as a string it will take lot of computations right every time the five characters need to be compared and it need to go this side every time that will happen to make our life simple and to make this problem optimized let's store A B C D and Z as one and E F G H I S two in this way like if there are we are getting new arrays suppose a by b by c by D will store a as 1 and B as 2 then we are getting first a then B then we are getting B and B already is two so not required then CS3 C is already stored then d s four first we will map it so I am taking the string and we are taking the integer and a is equals to we have the equation right this is the divisor this is a dividend and we are finding like if a does not exist we will keep the value of c and if a exists we are saying over here like suppose the B exists then it's not required right in that way we are comparing and we are keeping we are storing to make our lives simpler because if you deal with strings yeah you can solve it but it will be a bit complicated and then here then what we are doing we are double uh and we are storing because why we are storing now A to B huh for a we are storing B comma suppose the length is X x and we have to store for B Upon a and it will what it will be one by X because the path is reversed in this way you can see like you will see V by a i 1 by V by a and if a is equals to B if a is equals to b means what it makes a by a we need not to push into the array right if it is going a by a then directly we can say a by a is one so not required so to decrease the number of computations we are just continuing and we are pushing into the adjacency list I think most of you know about traditionalist if you don't know about adjacentialist go to geek for geeks and type like how the Matrix is stored it can be stored in different formats you can store in 2D array or adjacency list and unordered map you can store in many ways it is I prefer adjacent set because it's look good I like that yeah and we are taking Vector double and we are telling that it is an our answer and we are iterating each query A and B we are storing it A and B and if you can take this example is given a we are storing one B we are storing two see we are storing three he said that in this scenario for a it will be one very if there is an empty map will return zero if any one of this is zero and that output that queries input is not there in the equation input so you can say answer dot pushback minus one because the answer does not exist and there is definitely there is no path and then we are storing double is equals to C is equals to 1.0 and C is equals to 1.0 and C is equals to 1.0 and this is a path is like a DFS traveler uh DFS driver cells sorry and path is that so I used path and let's see I am sending a what a will be a will not be a string a will be like it's an integer B same it will be an integer via cam we are making very simpler by storing all the string into the integer so that our lives become simple and this minus 1 I think most of you saw this path like uh there is a graph one two three and there is four to five suppose if one to five there is a path there is no path we will return false one two three yes there is a path we will return to this straight forward version right I think most of you solve it in the same way it is very much similar to that little bit of changes let's see uh recursion is pretty straightforward guys first in the recursion way to think about the base condition what would be the base condition if this is our source a is our source B is our destination right a is our source B is our destination if source and destinations are equal then we are returning it pretty straightforward yes pretty straightforward we are returning true and we are saying that I have visited suppose you can take this example one I will say that okay if you are at node one I said I will say one is already visited and we will Boolean we will answer because we need to check like whether the path exists or not so we are making it as false if one of the paths existent it becomes true then we can say from that path the path is always exist let's see let's say I will explain you in very detailed and I think we all know this iteration r2i adhesive here a DOT first would be our next like suppose we are at one and one to two will be the a DOT first and the weight W1 would be I dot second huh right and if it is already visited then it doesn't make sense to privates again so wait to continue it and we are storing answer request to answer or path and if the answer is true if true then we are multiplying it and we are returning true if it is not coming into this array what we are returning we are directly returning the false I will explain you with simple example guys let's see one suppose you want the path from one to three what you will do one two three first I will start from the one then I will go to two then I will go to three you got the destination right three sorry six I'm extremely sorry 3 and you are checking review area returning true so what I will do I will return true from 2 I will calculate this weight suppose consider this weight as W1 sorry guys sorry W1 and this is W2 I will consider this W1 and from here also we are returning true and we are considering W2 as well and suppose let's say 1 to 4. one to four I will go to one to two and two to three and after three we have six yeah we have six we will go to six we'll go to after six we can't go to 4 right what six will return it will say 4 is not the right return false three will say 4 is uh e is written for I will return false written false return false by this we can say false has been written so the answer would be minus one so two to six you can consider first I will go to two to one what one will say there is no path so I will return false okay in the first iteration it is saying I am false and 2 can also go like this it will go to 3 as well two I'll say now I will go to 3 and then I will go to six yes I got the destination so I will return true from here I will return true and for him every true only we are multiplying you can see for every two only we are multiplying and we are returning the answer because we don't want to make like uh culture like there is a big thing one two three four to five to six and suppose you want a path from one to four you are going like this and we are returning we don't require this thing right five and six why we do why we want to iterate here it is written into then you are coming here and you are returning true that's it that's why we are directly returning the answer from here we don't require the another scenarios uh how much it will go down I am no I am not sure about that okay in that way we can solve this problem guys I think you got the intuition you got the understanding what would be the time complexity would be like order of uh for every query q how many queries are there Q into path how many times it will iterate the length of the graph we can say length of the graph so time complexity would be Q into order of n if n is the length of the graph I think you got the understanding guys what will be that space complexity would be the same order of some n order of n because we are storing the map and we are going additional list or it will be order of N I think you've got their intuition guys if you got the understanding please do like the video and please subscribe the channel and try to solve lead code every day because you can see my strict it's 140 so I hope you will continue solving this type of problems and see you tomorrow guys bye | Evaluate Division | evaluate-division | You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits. | Do you recognize this as a graph problem? | Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path | Medium | null |
172 | hi my name is Rish and I am a student of function of School of Technology and I'm in the second semester of my college and we are learning DSA through lead cot platform in Java language and practicing problems on lead Cod so I was going through the question 172 on lead code factorial trailing zero so maybe you maybe finding any difficulty or you want to cross check your answer or want to find a answer that will be in more precise manner so I have tried to solve this question my way so the difficulty level for this question is medium and the topics related in this question is maths mostly so from the outline of the question the heading of the question factorial trailing zeros if we want to break down this line this means we are we have been given an integer n and it's factorial we have to trace down all the associated zeros with them so this is the all requirement so while break down the outline of the question you get to know what you have to do in this question so trailing zeros means all the numbers associated with the factorial of that number or the total zeros associate in the last that are coming along with the factorial so we have to count them how many trailing zeros of that number so let's understand the description of the question so we have been given an integer n return the number of trailing zeros in N factorial so basically in this question we have been told that we have been given an integer n it can be any integer and we have to return the number of trailing zero in that n factorial so let's understand what factorial is so factorial of a number is let's say for example we have a integer five so to find the factorial we get from n minus one up to 1 so all the decrementing number all the numbers less than that up to one will be get multiplied and the product of all the numbers will be the factorial of that integer or the number you are finding for example we have been given in the question that n factorial is equal to n factori n * N - 1 into nus 2 so on up to factori n * N - 1 into nus 2 so on up to factori n * N - 1 into nus 2 so on up to 3 * 2 * 1 so this is the factorial we 3 * 2 * 1 so this is the factorial we 3 * 2 * 1 so this is the factorial we have to solve for this question so example has been given in this question that input n equal to 3 so we know the factorial of 3 is six and six has no zeros inside in them or no TR Z so output will be zero for example you can see example 2 Nal to 5 the output is 1 how the output here is five because it has one trailing zero and when we have to find factorial of 5 * 4 3 2 1 to find factorial of 5 * 4 3 2 1 to find factorial of 5 * 4 3 2 1 similarly like that and we get the factorial is 120 and 120 has one trailing zero so the output is one similarly for n equal to 0 it has zero trailing zeros so the output will be zero for input n equal to Z also you can mention or see the constants have been given for the question that n cannot be less than Z and cannot be greater than 10 the^ 4 so the constants also have 10 the^ 4 so the constants also have 10 the^ 4 so the constants also have been given that it cannot exceed 10^ 4 been given that it cannot exceed 10^ 4 been given that it cannot exceed 10^ 4 integer n so let's approach for this problem because a class has been already defined by the elite code and public method is being given by the leite code trailing zero integer n is the input here and uh within the curly braces we have to implement our solution so let's first initialize a variable count and initialize it with zero why we have initialized this variable to keep the count of trailing zeros when we will find them now let's uh approach for this problem how we going to break down and solve this problem to solve for this problem what we're going to do we will apply uh logic inside ourself at first how we will going to solve this problem so at first we're going to start with a Y Loop why we are going to use a y Loop because we keep checking for that number up to it won't get less than that zero so let's apply I'll explain the logic behind using the while loop also so I have used the while loop here while n greater equal to Z now this while loop will execute we know while loop executes when the condition is true so this will execute till the condition is true now uh let's Implement uh another approach so the approach that I've used here is n divided equal to 5 so basically the statement means n equal to n / 5 so we know that the factorial to n / 5 so we know that the factorial to n / 5 so we know that the factorial or trailing zeros can only occur when there are two and five inside the factorial um so but we can see for any integer to trace down number of two inside them is quite difficult to make our code efficient we can count the number of five coming in that number to count that five inside that number we will divide that n with five and we will store inside count so every time the code will Implement a solution um this will divide the N by five we will get the n and we will add it to the count variable which we have assigned now what we will do count plus equal to n by this statement what's going to happen any number for example five will come 5 greater equal to Z this will be true 5 ided by 5 = 5 ID 5 = 1 then we will get ided by 5 = 5 ID 5 = 1 then we will get ided by 5 = 5 ID 5 = 1 then we will get count plus equal to currently count is zero and count plus equal to what we have got here uh plus equal to n so n is currently one so count So my answer will be one here and at last we will return that count so this is the solution that I have implemented with because for this solution uh you basically checking the number of five inside total number of five in that uh number while finding the prime factorization you get to know there are several twos and fives to make our code efficient we have only used the five inside that and for that after that we have uh stored our uh total number of count of five inside the count variable and we have returned that now let's check for our code is working or not so all the test cases have been passed for our code and uh let's check whether it got submitted or not so our code has been accepted and it is taking it has beat 100% of the users is taking it has beat 100% of the users is taking it has beat 100% of the users with the Java and 0 Ms total time so the result process by lead code is being shown to you so this was all the solution for the question which we have implemented now let's talk about time and space complexity so the time complexity of this question will be we are iterating uh for all the five uh total number of five in that prime factorization of that integer so the time complexity will be Big O long Big O log n to the base five because it is executing for till total number of five divisions in them the space complexity is big one because we have only initialized a variable count here and it's taking a space complexity of one so that's all for this question have a great day thank you | Factorial Trailing Zeroes | factorial-trailing-zeroes | Given an integer `n`, return _the number of trailing zeroes in_ `n!`.
Note that `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`.
**Example 1:**
**Input:** n = 3
**Output:** 0
**Explanation:** 3! = 6, no trailing zero.
**Example 2:**
**Input:** n = 5
**Output:** 1
**Explanation:** 5! = 120, one trailing zero.
**Example 3:**
**Input:** n = 0
**Output:** 0
**Constraints:**
* `0 <= n <= 104`
**Follow up:** Could you write a solution that works in logarithmic time complexity? | null | Math | Medium | 233,809,2222 |
39 | hey everyone in this video let's take a look at question 39 combination sum on leak code this is part of our blind 75 list of questions so let's begin this question we are given an array of distinct integers candidates and a Target integer called Target we want to return a list of all unique combinations of candidates with the chosen number sums up to Target you may return this in any order and the same number might be used in candidates an unlimited amount of times two combinations are unique if the frequency of at least one of the chosen items is different and we don't need to worry about this one so before we get started in the question just the moment you see something like generate all types of or list all types of or any anything in which you have to do exhaustive search you want to think about recursion more specifically backtracking so we've done this in our permutations question we've done this in our subset question and the good thing about these types of questions is that a lot of the format is exactly the same and if you watch my subset question if you haven't go ahead and watch that one because I've kind of explained there like the generic format and like how we want to approach these types of questions we'll try my best to do it here as well but it that video is really helpful but basically we're just going to be following a simple idea just from that so before we get into any of that let's just actually go through the examples here to make sure that it makes sense to us foreign okay so here we want to form a target of seven and we have the following so it looks like we can reuse 2 to make four and then four plus three gives us seven we can also just use an element on its own to get seven so that's perfect now in the next set where we have two three and five we want to form eight so notice how we can just keep using the two to get eight we can do two three is reuse three and then we can do three and five and in this one it's pretty much impossible now important thing here is that all of the elements it looks like they are positive right so we don't have to worry about that okay so how might we go about approaching this as I mentioned whenever you see these lists all generated or exhaustive type question you want to think backtracking right and it kind of makes sense if you think about it I just don't want to say think backtracking but like it kind of makes sense if you think about it right because we might generate something like let's say we generate something like 22222 and you know we realize this doesn't work and then maybe we go back and then the next element is like a one and we realize this works so that's why like backtracking is should just become like intuitive in this type of question so if you like my subset of permutation the way I like to approach these types of questions is I'd like to have a result variable and then I like to do my recursive call here and then I return my result variable and the result variable basically is my result and my helper will populate resort with the potential answers which in this case are like the potential candidates okay so now let's go ahead and code our helper function and again I'm going to be using the same exact format that I have in subset so a subset permutation they often all use the same thing so what are a couple of the things we need right so we need access to the candidate and I'm just going to call this nums um don't want to spell out candidate so I'm just going to call it nums what else do we need well we need res we need Curve will be like our existing set of candidates that we're forming we'll need the index so we need to know like where we are in the list and that should pretty much be it okay perfect so what else do we want to do here so when I'm starting off this function right I'm going to be starting off at the current index so index number zero and now I really want to think about something I'm starting off at index number zero right in the subset case we always move towards the right index in the case for permutations we stayed on the uh we State we actually went back to the zeroid index and in this case what do we want to do well if you think about it really if we start on this index because we can reuse this item again and again it really makes sense if we actually just stay on the same index so when we are doing a recursive call we should just pass in the same index because we it's possible that we might be able to reuse this element again and again now you may Wonder well if we just keep passing at the same index how are we ever going to move forward in the loop now that's a good question but realize that we have access to the Target so if we are reusing the same index and we keep adding and we somehow go past the sum go past the target but then we know that you know we should recurse back and then at this point we will go to the next index so that's something to note here that we can actually just stay at the current index and if we ever go out of bounds or we overgo overboard at that moment we'll go to the next index so let's kind of start with that and we'll see how it can work from there so what we can do is we can do 4i and range we'll do index to length of nums right and so now one thing we need to do is we want to add this existing element again this is all part of the subset all part of like the way we do these types of questions we want to add this existing element to Cur we will do a recursion here we're passing nums res Cur and I will stay on the existing index then you'll finally pop it right now the question is here how do we know whether we are you know at a are out of bounds basically like how do we know if we have already passed the target so one thing we can maybe check is we want to check if before adding this nums at I if we were to add this nums at I are we able to basically get out of um get out of like the thing get out of uh out of bounds so one way we could do that is we could keep track of like a current Target variable right so um not a current Target but like total sum I guess so we can do like total sum here right and the one thing we would do is we would do if Auto sum Plus num said I if this is less than or sorry if this is less than or equal to what Target right then only we will consider this if it's greater then we have no reason to consider this because it's not going to lead us anywhere it's like if we're like 2 and then the last two actually took us like out of bounds then we don't need to consider this so we will keep track of this total sum here and so what that means is we actually need to update this total sum so we will do total sum plus what we will do total sum plus I'm set I so this will increment the total sums okay so that's perfect now we actually need to know where we add to the res variable where we add to this because as we're doing this recursion we will keep appending to curve but we haven't added to Res yet so we can actually just check that here we can do if total sum is equal to Target which means actually we need to pass in Target here as well if total sum is equal to Target then we add it to Res so we can do rest dot append sure remember we was append a copy and then we return because there's nothing more to do even if we like go into the loop we're just going to be over like out of bounds because we're going to keep adding on elements and that's pretty much all there is to this so we'll do res or nums res curves is empty index will always start off as zero total sub will be zero and Target will just pass in so let's take a look at this again let's first of all run it to see if it works or we run into any sort of bugs okay so it works let's go ahead and submit it awesome it works so again let's just take a look at what we did here so we can ignore this part but basically we are looping and we are looping we are first making sure that my total sum and the current item does not exceed Target if it doesn't then we'll add the target or we'll add the current num to our list of potential candidates and then we'll update our total sum and then we will check to see whether we are equivalent to our answer if we are then we will append it and then we'll simply return otherwise come back in any sort of way we come back either we go out of bounds or Maybe you know we return because like we found the Target and then we just come back and we pop and so that's this question as per time complexity I don't know I honestly don't know I think it's pretty hard to determine these ones um especially like backtracking questions so you can definitely look in the description um yeah but these ones are usually like they are really strange uh really strange like um time complexities like you can see like two to the target times K like what the hell right like anyways I hope this video was helpful | Combination Sum | combination-sum | Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.
The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.
**Example 1:**
**Input:** candidates = \[2,3,6,7\], target = 7
**Output:** \[\[2,2,3\],\[7\]\]
**Explanation:**
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
**Example 2:**
**Input:** candidates = \[2,3,5\], target = 8
**Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\]
**Example 3:**
**Input:** candidates = \[2\], target = 1
**Output:** \[\]
**Constraints:**
* `1 <= candidates.length <= 30`
* `2 <= candidates[i] <= 40`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 40` | null | Array,Backtracking | Medium | 17,40,77,216,254,377 |
1,704 | hello and welcome to another video in this video we're going to be working on determine if string halves are alike and in this one you're given a string of even length putl the string into two halves and let a be the first half and B be the second half two strings are alike if they have the same number of vals so they can be lower and uppercase and return true if they're likee otherwise return false so for the first one for book if you split it in half there is an o in each one so there's one V and one Val then for the second one it's text and book and in the left one there's one valve in the right one there's two vals so this is a relatively simp simple problem just checking if you know how to like check for vowels in a string and do it reasonably efficiently right so you should be able to do this uh in o n where you just look through your string ideally and also ideally you don't want to make like a copy of the string you want to just be able to Traverse it so uh pretty straightforward one let's just kind of walk through it and let's actually have an array with um in the to show this so let's just say we have a string of 10 characters and let's just say we have like a b c e b and let's say all vals or like something simple like a e so basically what you want to do is you first want to store your valves in a set you could just make like a string but it's more efficient to store them in a set and you could either store only lowercase valves or all of the valves and convert your strings to lowercase so in this case what I'm going to do is I'm just going to convert as I go I'm just going to convert each character to lowercase and then check if it's in my set but you could also store upper and lowercase characters in our set so we'll have a set of characters ABCDE or not ABCDE AE IO U lowercase and basically what we're going to do is we're just going to do a one pass here and the way to do a one pass is pretty straightforward you figure out what's the length of your string so in this case it is 10 divide it by two you get five and now you know your first string is going to go from zero to whatever this number is minus one so 5 - whatever this number is minus one so 5 - whatever this number is minus one so 5 - one is four so your first string is going to go from 0 to four and your next string is going to go from whatever this is to the length of the string minus one so 5 to 9 so you can just have an index I show this so we'll have an index I over here I will be zero and you can basically Loop through your string and you check two indices you check index I and then you check index I plus this like half thing right so plus half so in the beginning you will be at zero and five and you just check both of those and you have you just have two simple variables so you have a left and a right variable and you will just add appropriately if your character is a Val and it's in here you will just add appropriately so what's going to happen here is we have two vals so we have a Val on the left so we will add a Val to the left we have a Val on the right we'll add a Val to the right and we will move our pointer right so we'll just increment I in which case we will increment I and like I said we're going to be checking I and I plus this half so it's going to be I + 5 so this half so it's going to be I + 5 so this half so it's going to be I + 5 so then we check again Val there's no Val here there's a Val here so this will be two then we keep going so we have no Val in a Val so this will be three and you keep going basically what's going to happen is you're going to check these other two Val and at the end you will have two vals in the left and five vals in the right because the right section was going to go through all of this which is five valves and the left section is going to go all of this which is two valves then you just simply check is my count equal of both of them that way you just have a set of vals we're not like cutting the string in half you don't really want to cut the string in half because that's going to be extra space you want to just use correct index SC alternatively if this is a little confusing you can just Loop twice the first Loop will loop from like I said 0 to a half and then the second Loop will Loop through the rest store that in two different variables and compare those and that's pretty much it so we can code it up so we're going to get a half and this is guaranteed to be even length so we can just say like half equals length of s / two so we'll get some number it's of s / two so we'll get some number it's of s / two so we'll get some number it's always going to be um an integer because it's will always uh even then we're going to have our set of vals like I said you can either have all vals or lowercase so I'll just have only lowercase and you can give it a string so you can just say a e i o u here you could do this another way you could like do asky values or something but this is fine then you have a left and right so left equals Zer right equals zero and finally we can just Loop through our characters and do this so for I in range remember we're going to loop from zero to the half and we're going to check index I and index I plus half will be the right side and then the I will be the left side so we can say and we can even write this uh in more compact code but we'll just write it kind of a simple way so we'll say if si in vals so if it's a Val just increment left and if s i+ s i+ s i+ half in valves let's increment rate and I did forget one more thing remember these characters can be upper and lower case so we'll just convert here so I don't want to convert the string to lower case which is something you could do as well but you generally don't want to modify input so you could convert the whole string to lower case beforehand instead of doing this that will also be fine or like I said you could have all uppercase characters here and not have this lower operation either one's fine um yeah and then we just return is left equal to right and we can test that so let's take a look and there we go and all solutions are all kind of close you just run it a bunch of times like this isn't um it's not super important what your run time is as long as it's like somewhere in this range it's not very consistent I actually show my submissions here you can see that it's all over the place except for Java's faster but yeah python all over the place so yeah um so runtime here is just going to be oen because we are just looping through the string one time yeah because basically you're We're looping through half the string but then in each one we have uh two operat so it's going to be like half the string temps two pretty much and uh space and either way even if we were looping only through half the string that would still be open so space is going to be of one because we avoided uh putting we avoided like cutting the string in half you could there's like a billion ways you could do this problem honestly you can do a counter for the left and the right and any kind of like this is going to be over one or a counter of characters is also going to be of one because if it's only upper and lowercase characters there's only 56 no matter how long your string is it can be a billion so one other way is you could do a counter and then for every character for every Val you can just check like is the value the same that's like another way this is kind of straightforward or like I said you can break this down into two Loops one will check the left one will check the right but this is how you do both of them and one pass and yeah kind of a simple one so hopefully you like this one and if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching | Determine if String Halves Are Alike | special-positions-in-a-binary-matrix | You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters. | Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1. | Array,Matrix | Easy | null |
40 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem combination sum two we've already solved combination sum one and this is a pretty similar problem to the first one we're given a collection of candidates and these are always going to be positive numbers and we're given a positive target number that we want to sum up to and there could be multiple combinations from the candidates that can sum up to this target number so we want to find all unique combinations that sum up to the target also each number from candidates can only be used up to one time so it's not like it's unbounded right we don't have an infinite supply of each one and the solutions that cannot contain duplicates so this is what's actually going to make this problem a little bit tricky because take a look at the input right so we want to sum up to target a we can do that by taking a 1 and taking a 7 and that'll give us the sum 8. we can also instead of taking the first one we could take the 7 and then take the second one right that's a different combination but it's the same exact combination right so we cannot count it twice you can see in the output 1 7 only shows up once so we don't want to have any duplicates so that's what i'm really going to be focusing on because if we just want to get all possible combinations that's pretty easy right it's just going to be a decision tree right for each value such as 10 we could say okay include 10 or don't include 10 meaning we skip 10 right then next do the same thing for 1. include 1 or skip 1 over here include one or skip one right so we'd have one combination to n1 okay over here i was supposed to skip one so over here we'll take one over here we skip one so here we have a combination ten one just ten or just one or nothing right so we're looking for all combinations we can enumerate it like that but the problem we're going to notice if we do it like this is we're going to end up with duplicate combinations so let me try to explain how we can do it without duplicate combinations by the way no matter how we do it since we do actually have to create all the combinations the time complexity overall is going to be 2 to the power of n because that's how many combinations we can have for each value we can choose to include it or not include it n is going to be the size of the input candidates so let's take a look at this example input array and let's say we're trying to sum up to target 8. so let's just start back with that previous decision tree i was on so let's try it number by number and let's see why this doesn't work so we can choose to include 10 or choose not to include 10 right basically skip 10. now notice how already when we choose 10 we actually went over the target right so none of the paths in this left tree the decision tree are ever going to be equal to the target because all these numbers are positive we're always going to be greater than the value the target value a so this basically stops so we can choose not to continue down that way now from here we can choose to include one or skip one and then so then you know that takes care of one then next we get to two so from here we can choose to include two or skip two here include two uh where we you know didn't choose anything here or skip two where we will still have nothing over here and then basically keep doing that until we ever get to a target a sum where the target or the sum total is equal to the target uh so now we can do the same thing with seven include seven or skip seven uh similarly over here include seven or skip seven here we can also include seven but notice how if we do that then we get a sum of nine that was too big right so this decision this path is not going to lead to a solution here we also got to i think 10 so we cannot find the sum eight this though is going to be a possible solution one seven this so far is too small but basically now what i'm getting at you probably get the main idea here but what i'm getting at is this is not gonna work because this is going to lead to duplicates uh let me show you why so here we can include seven or skip seven and now so we're going to do the same thing with six right let me just skip six for now and just show you what happens with the one so we can include one or skip one but notice how this path over here is also seven one right and this path is also one seven so it's the same path right it's basically the same sum so we ended up with a duplicate how can we ignore duplicates well first of all let me explain the logic of how we're going to go about it and then i'm going to show you the actual algorithm so initially our problem is we want to sum to the target 8 right so this is what we're trying to look for so we can think of it in two different ways right one decision is going to be where we include a one value right for this sub problem eight because notice how we have multiple ones that's kind of where the problem comes from that's how we end up getting duplicates so one path well we will include ones and in another path we're not going to include any ones for the sum for the sub problem a right so by doing that by saying okay this left sub tree is definitely going to contain a one this right subtree is not going to contain any ones at all we can guarantee that both of these are going to lead to different combinations right i think that is kind of obvious this contains a one this will never contain a one so they're always going to be different combinations and similarly it's basically a recursive definition so next we'll get to the sub problem seven right we're now we're trying to sum up to seven over here because we already have a one so now we just wanna sum up to seven again what we're gonna say is okay left subtree could include a one and right subtree is never going to contain a one so the left subtree definitely has a one the right subtree never has a one so by definition you know this path is always going to be different than this path they're always going to lead to different uh combinations so that's kind of the main logic we're going to follow let me show you how we're actually going to implement that since we're going to be doing this recursively as i just kind of mentioned that it's a recursive definition one thing that's going to be easy for us to keep track is one we're gonna have a pointer i which is gonna tell us what position we're at so far and we can only choose elements that are equal to i or to the right of i and so you know what we're trying to do is say okay in one path we're including a one and later we're going to say the other path is basically we're not including any ones so it would be easy for us if we sorted the input array because if we sorted it this is kind of what it would look like it would look one so this is if we sorted the array so then if our pointer i is at this one we can say okay one path is including this one in which case you know the sub problem will become i plus one we're then looking at the remaining portion of the array if we decide not to include any ones at all our eye pointer is over here we're saying we're going to skip this one and this one we're skipping all of the ones we're basically saying we're going to shift i all the way to the point where we have reached a different element because now if our pointer i is over here we can choose from any of these values and we guarantee that none of these values are ever going to contain the value 1 because the array is sorted right so that's mainly the logic that we're going to follow it's still a brute force solution so the time complexity is going to be 2 to the power of n but let me just give you a quick walk through of how it's going to work so initially we have a choice we can choose one or we can skip one let's start with this tree right since we skipped one that means we skipped both of the ones right so now we're only going to be able to choose from these values so next we're at two we can choose two or skip two and since we're skipping two we only have a single two here so when we're shifting our i pointer we only have to shift it by one right now we have all of these values to choose from six seven ten so basically these two sub trees are going to be pretty much identical so we can either here choose six or skip six similarly over here choose six or skip six and so on and you can see that once we choose a 7 over here basically all of these are going to go over right these are going to be too big these are always going to be greater than 10 you can kind of see how that's going to work out with these candidates this is a possible solution 2 6 but over here we're going to end up and once we get to a solution 2 6 then we don't want to continue anymore because then we know if we add positive values we're always going to exceed the target value so we found one solution but over here if we choose the next value that's available to us seven we see that's actually going to go over to two plus seven is going to be nine that's going to be too big for the target so we're not going to continue here either continue on this left subtree so we included a one so now we have a choice of including another one or skipping all the ones to altogether right so if we include another one we'll get something like this another one and then we'll have choices we can choose a 2 or we can skip two and then if we include the next value it's going to be six which is going to end up being too great basically we exceeded the target when we went down this path so we don't continue and then over here we're so far at a sum of two we include the next value we skipped two on this path but we include the next value six so now we found another solution one plus six and if we chose the other decision if we choose seven we're going to end up going over so we're not going to continue down this path let me just save a little bit of space so next over here if we skipped the one we could have gotten a 2 and then we would have gotten a 6 7 or 10 and that also would have been too great right but we also could have skipped the two as well and if we skip the two we could have gotten a seven and this is also a another uh solution so we found three different solutions right so we found three different solutions one seven two six and 1 6. i think that's all three of the solutions and you can kind of see how doing it this way ended up eliminating the duplicates right we either chose a one in which case we could have chosen any of the elements or we skipped one and we skipped both of the ones and then we could have only chosen these so with that being said we can now actually dive into the code it's a little bit tricky but i'll guide you through it let's get into the code now and remember the first thing that we wanted to do is actually sort our input array candidates that's going to make it easy for us to eliminate the duplicates and we're going to be maintaining a result which is going to be basically the uh you know the combinations that we're returning and we're going to be doing this with backtracking it's recursive and we're basically just doing the brute force so we're gonna have three variables kerr is gonna be basically we're maintaining the current combination and another variable is gonna be i the index that we're at in our candidates array and lastly is going to be the current target that we're trying to sum up to because every time we add a candidate we're basically decreasing the target that we're trying to sum up to so if this target ends up becoming zero that means we've reached the base case we've found the solution in that case what can we do well we want to update our result right to the result we're going to append what the current combination is but we're going to make a copy of the current combination because this is kind of a variable that we're passing around we're going to still be updating this current value and when we append it we want to append a copy we don't want to append the original array itself because that's a reference we want to make a copy before we add it to the result another base case is going to be if the target is greater than zero or even if it's equal to zero either case we want to end up returning so basically if the target was equal to zero we would execute this statement and then after we would return if it wasn't equal to zero but it was greater or actually i should say less than zero that means we went negative then we want to return anyway so next we want to go through every single candidate in the input right we want to consider each one the first value and what are we going to do with this candidate well we're going to append it to the current combination right and this is basically the pre-work right and this is basically the pre-work right and this is basically the pre-work before we actually call the backtracking function once again so now we're going to be going recursive right we updated our current combination we're going to uh send the current into this function we're also going to say i plus 1 because we're saying that we can choose any of the remaining candidates and we're going to say the target is now going to be equal to itself minus this candidate that we just ended up choosing and after we finish that recursive call we want to do a little bit of cleanup so we want to basically remove the current candidate that we just ended up adding to the combination but don't forget remember what i was saying so if we chose a candidate such as one then on the next iteration of the loop we don't want to end up choosing that same candidate twice right we want to make a branch we want to say okay we can choose this candidate we already chose one decision where we ended up adding that candidate one the next time we want to skip one so how can we do that well we can say okay if this candidate is equal to the previous candidate that we just chose then we want to skip this iteration of the loop so then we have to maintain what that previous candidate was so over here we can say okay previous is now going to be the current candidate that we just chose so that we can use this val this variable in the next iteration of the loop but we still have to initialize this with something outside of the loop so the default value i'm just going to give it is negative one because none of the candidates are going to be negative one so this will never this if statement will never execute as being true on the first iteration which is what we want it to do and so that actually is the entire recursive uh function we're just you know brute forcing it there's just a little bit of logic you have to do a little bit of cleanup and basically this previous variable is what eliminates the duplicates for us so after that all we have to do is call the backtracking function passing in an empty array for the initial combination that makes sense starting at index zero that makes sense and the target value that we want to sum up to is the target value that we're given in the input that also makes sense once we're done with that we can just return the result that we updated and added all the combinations to from this line over here oops uh for some reason and so uh you know this candidate is the candidate of index i don't i always forget and it has an s at the end and down here i also called it candidate you can tell that i'm pretty sleepy right now but hopefully those are all the typos that i had oh and lastly when we're actually taking our index i uh we don't want to necessarily go through all the indices that's why we're passing in this i uh value in the input backtrack so actually instead of calling this i since we're actually using a different variable for i here i'm going to call this i position basically the starting position that we're starting at when we call the recursive function so from here instead of saying for i in range of the entire candidates we actually want to start at this starting position and then go to the end of candidates so that's going to be the actual solution sorry about all the bugs and typos but as you can see this solution actually does work and it is pretty efficient so i hope that this was helpful if it was please like and subscribe supports the channel a lot and i'll hopefully see you pretty soon thanks for watching | Combination Sum II | combination-sum-ii | Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.
Each number in `candidates` may only be used **once** in the combination.
**Note:** The solution set must not contain duplicate combinations.
**Example 1:**
**Input:** candidates = \[10,1,2,7,6,1,5\], target = 8
**Output:**
\[
\[1,1,6\],
\[1,2,5\],
\[1,7\],
\[2,6\]
\]
**Example 2:**
**Input:** candidates = \[2,5,2,1,2\], target = 5
**Output:**
\[
\[1,2,2\],
\[5\]
\]
**Constraints:**
* `1 <= candidates.length <= 100`
* `1 <= candidates[i] <= 50`
* `1 <= target <= 30` | null | Array,Backtracking | Medium | 39 |
349 | hi everyone welcome back to the channel Android all code daily challenge problem number 349 intersection of two arrays so it's a very simple problem to solve and this can be solved using multiple ways uh and you know we will look into the problem statement first then we'll check out the approach which we're going to use and towards the end we'll see the code as well so starting with the problem statement it says given two integer arrays nums one and nums true return an array of their inter intersection each element in the result must be unique and you may return the result in any order and they have given the examples over here so the correct of the question is like find the common elements from both the arrays find the intersection of both the arrays and all the elements will be unique and it can be in any order okay so to solve this question like uh it can be solved using multiple ways for example you can solve this question using a simple set intersection method so where you know you'll pass in your first set do intersection second set and this will be done or you can use ment sign between two sets to get the intersection as well but uh you know just uh to make sure U you know we know the other approach as well because in multiple cases uh interviewers expect us to uh write the solution from scratch without uh using any of the inbuilt method so what we will be doing uh we'll be using two dictionaries no sorry uh what I'll do I'll just simply use a single set and I'll convert this nums one array into a set so that we are just simply removing all the duplicate elements okay so my nums one becomes this one and two only okay now just simply iterate this uh array one uh nums one array for I in nums one okay and check if this I is in nums 2 or not this is nums 2 okay and if I in nums 2 then we can say okay this was a common element so we can add that into a result and the order you know anyways doesn't matter so there won't be an issue and at the end we'll just simply return the this result array which we are maintaining so this is one of the ways or you what you can do you can just simply use uh set of num one and set of num two or there is another method we will take set N1 do intersection okay intersection f with set N2 so these are the three methods which can be used there are multiple you know many other ways as well using sets only okay so yeah let's check out the code as well it will be a very simple code so uh as you can see uh what we are doing over here we have converted the list into a set and by doing so we have removed all the duplicate elements we have defined the empty array for the result and we're just simply iterating the values in nums one and checking if any of that is in nums two or not okay if the if we find the key in nums 2 we will just simply append that in the resultant array and towards end we just simply returning the resultant array so let's check out the test cases and the test cases got clear let's submit it for further evaluation now okay yeah so as you can see the solution got accepted and performed well uh but yeah so this is the solution guys thanks for watching out the video stay tuned for the uping ones don't forget to like the video and subscribe to the channel thank you | Intersection of Two Arrays | intersection-of-two-arrays | Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000` | null | Array,Hash Table,Two Pointers,Binary Search,Sorting | Easy | 350,1149,1392,2190,2282 |
1,910 | hi texas tim here back with you for more elite code grinding and uh let's see where we stand now i have done 420 of the easy and that actually is all the algorithm ones i'm pretty sure let's double check difficulty easy yep no available um easy ones that i have not started so we're working on medium and i like to sort them from easiest to hardest so let's get in there remove uh let's get in here number 1910 remove all occurrences of a substring all right well let's do this all right given two strings s and part perform the following operation on s until all occurrences of the substring part are removed okay so it's as we remove the substring part then possibly additional instances of the substring part might be created all right i think this is a case for string builder let me just refresh my memory and i like string builder for this because you can delete characters at certain places yeah indeed you can so let's try you can also remove the substring okay right okay i think i'm getting a sense i think we can move the string s into a string builder and then traverse the string from beginning to end and if we find a substring then we can delete it actually you know i think that'll work is there also an index up yeah of course there is all right so let's do a naive solution first i like to sometimes just get a solution out there that works might not be the most performant you know it's big o time complexity might not be that great but it gets something down and you get that momentum you know because you've it's correct i have a little acronym that i like to use to remind me of important things when i'm coding it's a c prism c p r i s m and those letters stand for correct performant readable idiomatic secure and maintainable and i try to think of those six values or objectives or goals while i'm coding and the first one is correct it's got to be correct if it's not correct then you know it doesn't matter how if you know how fast it runs or whatever if it's not correct then you're out of luck and a naive solution can be correct and you can you know iterate on it so let's do a naive approach and what that is let's see we're going to put it in we're going to do our string builder so string builder s b is new string builder okay and we're actually that's what we're going to return so boom we're like almost done we just got to put some stuff in the middle so while sb index uh let's see how i want to do this i want to know what the index is well index is greater than or equal to zero oh sb index of part so we're gonna do is have a while loop that just keeps checking to see if that substring part is in there and if it is we're gonna delete it with this delete start and end indices so delete index to index part link actually let's well we're doing a naive approach so i'm not gonna try to optimize it yet um you know that old coding quote about attributed to donald knuth that optimization is the root of all evil or something like that but well as you may know the quote is moral in the lines of premature optimization is the root of all evil so there's nothing wrong with optimizing but you don't want to do it too early partly because you can get sidetracked from making your algorithm correct if you're too focused on the other letters in my little acronym um for me that's probably the big one is i get distracted by worrying too much about details early on and i don't like to be distracted right so we're going to delete and then we have to update our index equals sb oh my gosh why did i do that index of part and then we'll return it so this is pretty naive this should work right let's see what is going oh my goodness i created my string builder but i didn't put anything in it oh my gosh okay let's submit it that's not bad that's actually incredible performance for now i mean i'm just using inbuilt methods you know string builder and it's delete method or doing all the heavy lifting so would this be the best approach to code in like a coding interview i don't know maybe i mean look at that performance if you're being hired for a java developer position why not show how well you can program in java certainly there's a way to approach this in a more lower level way and that's always something i think about um is you know do we want to do a deep dive into details of you know kind of rolling our own basic like rolling our own index of and rolling our own delete some i don't know maybe do both if you have time in the in an interview just do both let's look at these constraints and see if there's anything special to take note of i really i try to look at the constraints before i hit submit because sometimes there's a gotcha down there but i don't see a gotcha there so how could we improve performance i mean this is pretty high 99.94 pretty high 99.94 pretty high 99.94 that's pretty amazing but theoretically we every time we do an index of we have to uh look over the left part of the string again and so there's a lot of repetitive looking let's see if um so stringbuilder does offer a from index so what we could do is tell it not to go back all the way to the beginning but just to go back the length of the string part from the last point we started because that way you know if a new instance of part is created it's not going to be further back than the length of the that string part so let's try that so the first time we're going to start from zero but then after that we're gonna start uh from index and we've got to make sure we don't go below zero so we're gonna do math max 0 or index minus part.length so now part.length so now part.length so now we're giving it what would it be uh we're giving it a q we're given the index of a q to start just a little ways back let's see if this works it'd be nice to get zero milliseconds yeah well look at that isn't that nice to see we squeezed a little bit more performance out of there and it is i think it is very satisfying that you know theoretically you know that it should be faster because you're not going over as many parts of the string but it is nice to see the elite code judge proving that okay so let's put in time complexity and it is going to be o-n we're not and it is going to be o-n we're not and it is going to be o-n we're not going back over it too much and uh something fell on that closet i'll have to look at that later um so we're traversing s and we're going back potentially we could go back every time but in that case we would i think it would at most be 2n it's never going to be n squared okay space complexity um we're only getting smaller but we do well we do create a string builder that's the same length since we copy the input string into a string okay oh right let's submit it again like that and i think i'm gonna take out a naive approach but let's make a comment and actually we don't need to put it there although you know what i bet that internally oh my goodness yeah why don't we check let's see this and i think internally if we pass it index of with just a single argument it probably turns that into the index of with the starting index i'm almost positive but we can check let's see jdk 13 and i was there just the other day yeah here it is and we're looking for string builder this is of course the open jdk repository on github and there's string builder and we're looking for the index of okay uh return super index of okay string builder is a instance of probably what string buffer okay so let's hop over to string buffer let's check index of here synchronization um am i getting a little bit out of my depth all right let's go back to string builder what is it a super of or what is the super of it compatible no guarantee of synchronization isn't this fun going into the jdk source code to verify what is actually happening under the surface all right extends abstract string builder okay so let's go there okay now we're talking all right what's the index of here index of yeah see there it is exactly should i make this bigger i like to do let's do 125. all right so stringbuilder extends abstract string builder and if you pass index of to your abstract string builder it just turns it into index of with two param with two arguments including the second one zero so i don't know how much optimization it would be to pass at the zero anyway but i think i'm gonna not um because if we add the zero then whoever comes after like imagining this is part of a code base whoever comes later is going to say why did he why did the previous coder add a zero there and it's not going to be clear why you would do that so and the gains are probably so minimal that nobody would think somebody would do that so i'm going to not do that but down here we will say let's say give index of i'm going to um let's see what we're gonna do only start searching from how do i what should the comment be how about um don't research from the start of the string there you go maybe someone would ah even better no need to start from the very beginning of the string there we go and how about a little winky maybe that's not maybe that's silly okay submit there you go i think well look 0 milliseconds faster than 100 i think it's worth putting in the discussion let's do that why not fat see look some of these are not a hundred percent oh a recursive solution that's interesting and there could definitely be cases when that is valuable let's look at this basic implementation let's see what this person did um okay we've got some a boolean flag in play okay so far okay it looks kind of similar to what i was doing interesting oh so that's their index of and they do restart from the beginning each time so that's you know a naive approach well upload why not thanks for putting your voice in there person okay but i'm gonna post mine java zero s beats 100 very proud of that uses string builder um and index of with let's indicate with a from index there you go anybody who knows about index of and the second parameter from index is gonna know right what i'm talking about let's post this i'm really glad that went quickly sometimes these don't go very quickly let me take one last look at it before putting the ribbon on it delete you know i'm going to add an exclamation point there i wasn't going to do a winky but i'm going to oh it's over here there we go let me save there we go i do if i find that this same algorithm can sometimes hit a smaller memory footprint i do like to record that information here just for my own reference gives me a familiarity with what kind of memory usage different algorithms or different approaches might have okay all right well that completes this leak code 1910 remove all occurrences of a substring thanks for hanging out and with me while i do it and i'll see in the next one | Remove All Occurrences of a Substring | check-if-binary-string-has-at-most-one-segment-of-ones | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "daabcbaabcbc ", part = "abc "
**Output:** "dab "
**Explanation**: The following operations are done:
- s = "da**abc**baabcbc ", remove "abc " starting at index 2, so s = "dabaabcbc ".
- s = "daba**abc**bc ", remove "abc " starting at index 4, so s = "dababc ".
- s = "dab**abc** ", remove "abc " starting at index 3, so s = "dab ".
Now s has no occurrences of "abc ".
**Example 2:**
**Input:** s = "axxxxyyyyb ", part = "xy "
**Output:** "ab "
**Explanation**: The following operations are done:
- s = "axxx**xy**yyyb ", remove "xy " starting at index 4 so s = "axxxyyyb ".
- s = "axx**xy**yyb ", remove "xy " starting at index 3 so s = "axxyyb ".
- s = "ax**xy**yb ", remove "xy " starting at index 2 so s = "axyb ".
- s = "a**xy**b ", remove "xy " starting at index 1 so s = "ab ".
Now s has no occurrences of "xy ".
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= part.length <= 1000`
* `s` and `part` consists of lowercase English letters. | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. | String | Easy | 1999 |
1,337 | hi guys welcome to algorithms made easy in this video we will see the question k weakest rows in a matrix given a m cross n matrix of ones and zeros where one represents soldier and zero represent the civilians return the indexes of k weakest rows in the matrix ordered from weakest to strongest the row i is weaker than row j if the number of soldiers in row i is less than that in row j or if they have the same number of soldiers but i is less than j soldiers always stand in the front and that is always once may appear in first and then zeros would follow for example one we can see that this is a matrix given to us where this ones represent the soldiers that are standing here and these zeros are the civilians k given to us is three so we need to give three weakest rows if you count the soldiers in each of these rows you will get two and zero throw four in first row one in second row two in third row and five and fourth row after you rearrange them or sort them with the condition that are given to us the weakest to strongest order of this rose goes like 2 0 3 1 4 and as we need to give only 3 we give the first 3 and that's the output so in here we can see that one would get arranged in the start and then 0 and 3 both have same number of soldiers but since 0 is lesser than 3 we will take 0 and then we'll take 3 so it gives us 2 0 3 and then one is having 4 soldiers and then 4 so that's how we got this order so this particular question is mainly based on sorting it has nothing more than sorting involved in the question so it's an easy one let's go ahead and simply write the solution for this problem okay so the main thing that we need to do here is sorting so what we are going to take as a data structure is a priority queue that would hold integer array in which the 0th index would give me the number of soldier and the first index would give me the index of row so how do i need to sort this priority queue so i'll be taking a max hip wherein i'll be eliminating the max values and in here given a and b what we need to do first is first we need to sort based on a0 and b0 in descending order and if i am getting a 0 equals to b 0 then i need to sort according to my index which is a1 and b1 in descending order so this is how i want my priority queue to be sort that's the whole gist of this question right here so now let's go ahead and take a priority queue so this gives me the sorted priority queue so here this would give me sorting based on my soldiers and this would give me sorting based on my indexes in the descending order i have written here while my soldiers are not equal i want it on based on my soldiers and while my soldiers are equal i want them based on the indexes the next thing we need is a result array which would be of length k and now we need to find the soldiers in each row and put that number into our priority queue so for int i equal to 0 i less than so that's iterating simply iterating on the matrix so i have taken this loop wherein i am iterating over my matrix and i have written wherever i have one i'll do a soldiers plus and for that i need to take a soldier which will be zero and once i am done counting that i need to add it in my priority queue so this will added in my priority queue now after adding everything in the priority queue and getting everything sorted i need to remove the extra values from priority queue so while its size is greater than k i need to pull from priority queue and once i have all the elements that are there in the priority queue i need to fill my result array so while k is greater than 0 my result of k equal to p q dot pole the first index from that and at the end i'll just return my result so that's it let's run this code and i've made some mistakes okay so that gives a perfect result let's try to submit this and it got submitted so that's one of the way of solving this question the other method or other slide change over here that we can make is instead of looping over all the values we can binary search the number of ones that are there so i'll leave that binary search up to you and i would do something else for this question so can we get rid of this priority queue over here let's try to do so and so i'll instead of taking a priority queue i'll take an array of count and in this count i need to store something from which i can deduce the count of soldiers and also the row it is present into so instead of this line over here my count of i should store the number of soldiers plus my index would i be able to get the index over here from this value no i would need to do some kind of operation so that i can easily get my values so here i am taking this multiplied by thousand and here i'll do a mod of thousand which would give me my index instead of this i'll simply write arrays.sort arrays.sort arrays.sort for my count and that would count based on my soldiers and because i have added i it would also consider my ith position and now over here i need to write a for loop and my result of i would be count of i mod my mod by thousand so this would give me my result let's remove this let's try to run this and it's giving a perfect result let's submit this and it got submitted so the time complexity for this one would be o of m cross n because we have taken this loop for o of m gross n and my space complexity would be o of n so that's it for this video guys i hope you liked it and i'll see you in the next one till then keep learning keep coding | The K Weakest Rows in a Matrix | design-skiplist | You are given an `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row.
A row `i` is **weaker** than a row `j` if one of the following is true:
* The number of soldiers in row `i` is less than the number of soldiers in row `j`.
* Both rows have the same number of soldiers and `i < j`.
Return _the indices of the_ `k` _**weakest** rows in the matrix ordered from weakest to strongest_.
**Example 1:**
**Input:** mat =
\[\[1,1,0,0,0\],
\[1,1,1,1,0\],
\[1,0,0,0,0\],
\[1,1,0,0,0\],
\[1,1,1,1,1\]\],
k = 3
**Output:** \[2,0,3\]
**Explanation:**
The number of soldiers in each row is:
- Row 0: 2
- Row 1: 4
- Row 2: 1
- Row 3: 2
- Row 4: 5
The rows ordered from weakest to strongest are \[2,0,3,1,4\].
**Example 2:**
**Input:** mat =
\[\[1,0,0,0\],
\[1,1,1,1\],
\[1,0,0,0\],
\[1,0,0,0\]\],
k = 2
**Output:** \[0,2\]
**Explanation:**
The number of soldiers in each row is:
- Row 0: 1
- Row 1: 4
- Row 2: 1
- Row 3: 1
The rows ordered from weakest to strongest are \[0,2,3,1\].
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `2 <= n, m <= 100`
* `1 <= k <= m`
* `matrix[i][j]` is either 0 or 1. | null | Linked List,Design | Hard | 816,817,838 |
31 | Hello guys welcome to another interesting problem not only coding behavior after match for exploitation festival dates for meditation which basically rearrange from this number to lexicographic le next day termination of numbers in question are as per possible at Mussoorie arrange details below as possible order and replacement Been Placed and Used Only Constant Extra Memory 16 Tried to Take the Example of 123 456 Competition of But in All Possible Positive 123 Memory 132 Meghnad 032 S Way Can Observe Every Three Idiot Means MP3 Factorial is equal to six degrees of possible numbers. Of Mediation Center 2006 Issues Notification for the Road to Find the Next Possible Combinations of Water Discharge of December Answer is Yes OK Complexity and Video then subscribe to the Page if you liked The Rob Sending and 130 Greater Than One Man Force UK 3.5 Billion for this is the Force UK 3.5 Billion for this is the Force UK 3.5 Billion for this is the highest positive permission Response will Give for Annie Such Dar Date Detail in 1652 E Again Play List in E -E -E -E -E -E -E -E -Last Play List in E -E -E -E -E -E -E -E -Last Play List in E -E -E -E -E -E -E -E -Last 09 Year Possible Subscribe Problem Provision Problem Ho Spotted With Answer For This Point Collect Information For This K Skin Object Permission For This Case Will Be See From This When You Have Worm Tree Vanilla One Medium To You Love Fights How To Reach You To The Meaning Of This Is The Meaning Of This Point From infection to z patient for infection phone number call to the number to replaced with next number to point to two to this point to left mitthu tasty to ok with water based shampoo time will find in this runes there and after to Drops 2nd Number Greater Than What Is Possible Number Acid Phase subscribe The Channel subscribe Basically You Will Get 2ND Year 75221 subscribe to The Amazing The Beginning 2.5 Just Have Beginning 2.5 Just Have Beginning 2.5 Just Have Factory Salaries 20 Number in December 19 2012 Edward And You Will Be Able To Get This Will Arrange 521 Ascending Order Of But 17125 Boil To Reach Ajmaye Answer Sudhir Sharma First Flight Infection Point In This Episode Okay Android 2.1 Days With Water subscribe to Android 2.1 Days With Water subscribe to Android 2.1 Days With Water subscribe to the Page if you liked The Video then subscribe to subscribe Scam Will Still Be Not Completed Tours And Way Will Be Able To Get Rid Of Define Not Sweater Ladies First Time To Final Infection Point From 1000 Village This Point I Cold You I Am Dresses - - VN Am Dresses - - VN Am Dresses - - VN Rai Final Infection Points Words And Systems At Size - 134 Last Date Of The Systems At Size - 134 Last Date Of The Systems At Size - 134 Last Date Of The World Tour Finals of Elementary Middle He Is Greater Than Women Will Say Selection Points in Infection 208 Ki and Will Change It's My Infection Point and Infection Point Can Welcome Equal to Mr. Talented Designers and You Can Break Point Thursday at 10:00 PM The Best Possible Results For this pooja are not possible in this picture they will start on that your novels is dissolution infection point in what do you how to make sure you will love to declare and you clearly but will have to shoulder earth infection point - from bandh se is The Number Note I Have To point - from bandh se is The Number Note I Have To point - from bandh se is The Number Note I Have To Swap The Numbers That Know What The Contours Have Enough To Search The Number Which If This Form Number 16 For Inch J Equal To Inflection Point To Z Loosening To Z Plus Subscribe Number To Do Subscribe My Channel Subscribe Hit the subscribe button now to give the number to give benefit finally Bigg Boss back number 160 again in English I don't have to phase Samrat 2053 lighter final next gas number will be against the MLAs so how they find that he will have to take the difference Between systems for change - 200 of Android Between systems for change - 200 of Android Between systems for change - 200 of Android yet minimal right side effect also minimal in the differences minimum day and that is my number dial voice of co declared as minimum variables in an option will give in terminal is equal to inter max means 16 To the biggest possible restaurant and this website ok know what do you know the to make how to make a drawing algorithm to entertain is equal to two terms of vinous williams off kar do ki ramzoo ashraf inflection point - lineage ki ramzoo ashraf inflection point - lineage ki ramzoo ashraf inflection point - lineage of inflection point - one is equal to two Take of inflection point - one is equal to two Take of inflection point - one is equal to two Take amid the crowd gathers meaning are industry is the meaning of name starts with j plus points 121 phone number debt and rent pad set and i hope that this will work financial let's make sacrifice walking fan and in the morning at that time i think bira forgotten to gift Semiklan Hair Otherwise Shirdi And Hua Hai A Pedestal Time Don't Sleep Infection Point * A Pedestal Time Don't Sleep Infection Point * A Pedestal Time Don't Sleep Infection Point * Subsequent To Infection Points And Knowledge Given On Spelling Mistake Hairs Forgive Me For The Spelling Mistake That And I Hope You Should Define And Clean Working Fine Laser Sensitive Then This Time Swelling Accept Solution Thank You for Being Patient and Not Listening | Next Permutation | next-permutation | A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order.
* For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`.
The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
* For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`.
* Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`.
* While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement.
Given an array of integers `nums`, _find the next permutation of_ `nums`.
The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,3,2\]
**Example 2:**
**Input:** nums = \[3,2,1\]
**Output:** \[1,2,3\]
**Example 3:**
**Input:** nums = \[1,1,5\]
**Output:** \[1,5,1\]
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 100` | null | Array,Two Pointers | Medium | 46,47,60,267,1978 |
232 | so hello everyone so welcome to today's lead code daily question that is Implement you using stacks so the question is quite clear to us we have to implement the queue using stats so for that the hint given to us is that we can use two stack and uh for maintaining a queue so uh as you can see here the question will be given and there will be uh some functions given to us which we have to apply to it so the first function is my queue that is we have to initialize the data structure with the queue the license we have to initialize this tag we will be using to implement the queue then push of course we have to push the variable the integer given to us to the end of this end of the queue pop you have to uh remove the front element from the queue Peak we have to return the front element from the queue and empty we have to check whether the queue is empty or not so we will be doing it using two stacks so the basic approach which comes to into my mind while uh doing this is to use uh two step first of all and then what I will do is that I will whenever we uh we have been given like C I have to initialize this type two stacks over here so while pushing if I get up from if I get the call for pushing an integer so I will post that integer to the first step okay so when I get the uh call for pop or Peak so what I will do is I will transfer all the elements from the stat one to the stack two and then I will like you if you can see I have uh I have pushed all the elements to stack 2 from stack one till stack one is f not empty that is that this type 1 is empty and then I have taken that uh that stack to pop in one variable a and then again I have pushed all the elements of Stack to stack one and again then I have returned a so this was one of the approach and the second approach is quite uh space optimized because uh in this approach we use of n space complexity while in the second approach field which I will be explaining further we have used o of one space complexity so now let's move to the solution video so now let's first uh discuss the first solution so as you can see this is the function I've copied so according to this uh first uh this is the question which I have made by myself to just test this scenario so um let's uh do let's go on with the question so first my queue so far of course the two stacks will be initialized so now coming to the next part uh we have been given post two so uh post two so according to the uh solution uh I will post whatever whenever I will get a call for post I will post it into the first step so two will be first again three will be pushed over here okay so now push forward so push will be four will pushed over here now pop as I said in Pop I will uh transfer all the variables of Stack one to stack two then I will pop so um what I will do is I will move all the elements to uh stack two that is 4 will put that forward will equal to stack two and uh again this three and uh two will also go to stack two so um let me finish this so here I've pushed all the elements of from stack one to stack two and this is how our queue would look like just to understand it more better like uh we add at the end so four will be at the end so now we have to pop so as you can see power function is given over here so pop so ideally we have to pop two right so that for that only if you have pushed the element of Stack one to stack two so that we get two at the top so we pop it so we remove two for now okay so now what next step is that as you can see in the pop function over here I have again transferred all the events of Stack to stack one so this is a bit tedious so uh let me explain I will explain you a further better approach in the second part so for now let's move all the elements of Stack to stack one so uh I will shift it for a minute so I shifted only elements from stack to stack one so now again we get a pop so again uh well the same procedure will be taking place I will shift from stack one to stack two and also you can see the changes Q as 2 is removed for now so I will again do it so now we get a pop so again for the second pop we will remove three from it and also from the Q3 will be removed so again now we have to uh say 4 to the type one so we shift this 4 to this type one now we get a push function as you can see here we have a push file so push five so we will ideally it should be added at the end so here as per our push function I will push it to this stack one so uh it will be pushed over here now empty is basically I will check only like here if you see uh like once again just here yeah so here I have returned it if we have to return where the stack is empty or not since uh all no operations are mainly for with this type one so I've written if Step One is empty so return true else false uh also for a peak I have not explained you Peak but for Peak also similar things will go on like same we will transfer it to stack two then we dig and again we will move from statue to stack one so this is how the first solution goes on although it's a bit tedious but uh this is how we have done in it so now let's and it is also getting accepted so let me explain you the second approach now so now this is our second approach in second approach what we are done we have again used two stacks of course we've initialized it now for posting We will post only to stack one then if we get a pop or a p function so what we will do is we will transfer uh we will check if it is empty for transfer function what we do is that in transfer function we have made it so if stack 2 is empty then while stack 1 is empty we will push the element of Stack to stack one and again for the peak we will do the same thing we will call the transfer option and then uh then we will uh send this stack to the peak now you might think that this it is quite similar to the first approach but let us see in the solution video in the explanation how it is different so I've copied the entire solution over here as you can see uh I have this is the functions given to us and this is the transfer function at the end so now let's go to it so my Q will initialize the view now push two as per the uh as per the function written by us here so post 2 will push it to the stack one so okay let's suppose to use stack one again this will also go to the queue now push three and four then push four so I will post it to the stack one itself push three and push four okay so now next we get a pop so what for pop what we do is we return if empty now what if what is same fmt if empty is simply written if both this type not just the first type like in the first approach we will do we were doing if that one is everything so written true but here we are returning if both the uh stats are empty so we will return to so uh okay now we remove a transfer so what does transfer do over here so see if you see transfer so transfer function if stack 2 is empty yes stack 2 is empty so while stack one is not empty like while stacker is empty step D for Save the elements perform stack one to stack two okay so why is we will move all the elements from stack to the stack one so if we have moved all the elements from stack on to stack 2 now P not pop so we will return stack 2. as you can see over stack 2. uh let me suppose you completely so stack to the top here uh sending so we will remove this Two element from here and also from the queue for the understanding purpose and uh now we will not shift again from stack to stack one so this is the difference we will not shift again from stack to stack one we will let the elements be in stack to itself okay so now again we get a pop so again we will uh is empty is false so transfer now if stack 2 is empty no Step 2 is not empty currently so we will not again post the element from stack one to stack two since stack 2 is not empty so uh this will remain as it is now for uh now we will return next to the top that is the 3 will be returned over here so as you can see it is a bit optimized solution because we are not again and again transferring uh once the elements are in stack two we are getting the elements being stacked to itself so again from this over here also it will be removed three so again we will get a push five that is uh Push by we are here so push five will uh now we will move to here this element that is we will post to stack 1 as per our function return over here so uh five will be attached to the Queue at the end now we get a pop so as per the question again we have to uh remove the uh front element so that is 4 should be removed and uh so in power because transfer function so transfer function now stack 2 is not empty so again there may be no transfer happening so now start to so uh you have to return to return to return so again stack 2 will be that is 4 will be removed so as you can see this is reducing the complexity to much better so uh here also 4 will be removed and we will get a 5 over here only so now we get a peak function so again now P function uh we call the transfer function but now stack 2 is empty so now what we can do is we can transfer this five so we can transfer this by to stack 2 and then we will return the stack to that Peak so that is we will return this tag to that Peak so here 5 will be returned so 5 will be the answer to this speak with him empty now since it will pause because Tab 2 is not empty and we will be returning true only if stack one is stack 2 is empty so this is how it goes it is a much a better solution than the previous one so this solution also got accepted and it is a much better solution so uh in this video we have I have explained you through two approaches one was the name approach the second one was a bit a space optimized approach so I hope you liked the video and if you liked it so please do like and subscribe and thank you for being with me thank you | 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 |
337 | hello everyone welcome to my channel coding together my name is vikas oja today we will see another lead code problem that is House robber 3. it's a medium level question and it's a very popular question as you can see from the likes the let's read the problem statement the thief has found himself a new place for his thievery again there is only one entrance to this area called root besides the route each house has one and only one parent house after a tour the smart Thief realized that all houses in this place form a binary tree it will automatically contact the police if two directly linked houses were broken into the same night given the root of the binary tree return the maximum amount of money the thief can rob without altering the alerting the police so let's re let's take an example to better understand the question so suppose this is an example so all the houses form a binary tree if the thief robs the house with a value 3 that is highlighted by Orange and if the thief uh robs the directly corrected houses for example either of the two or three then there will be alerting to the police so the thief can rob either the house with value 3 and these two houses that is with value 3 and 1. right so the thieves can rob the houses three plus one that will be 7 or the thief can rob the houses two plus three that is five because three and the this three and this three are not connected directly three and one are not corrected directly but three and two and three are connected directly so to solve this problem we will first iterate the tree in a depth first search manner right uh DFS tree traversal so at each node starting from the leaf node while moving up so at each node we will return two values so we will return an array of size to X represents the maximum value or the maximum money a robber can rob from the nodes or the from the houses below this current house without alerting the police and Y represents the maximum money the robber can rob from the houses below this current house plus the current house the money he will get by robbing the current house right so the first value represents without the current house and the second value represents with the current house right similarly on the right hand side it we will return the same right now when we will uh go back up to the root node right the or the parent of these left and child nodes what will happen first we will calculate the maximum of whatever we are getting from the left child so we are returning X comma y to Z so at Z we will calculate the left or the maximum so suppose the maximum is X from X and Y similarly we will calculate the maximum whatever you are getting from the right so suppose the value is Y dash that is the maximum so at root Z or the parent root what we will do we will first to calculate the first value of the resultant array we will take the maximum left and the maximum right so and we will add them and the value and that value will be the uh first value of the resultant array so suppose the value is a and for the second value of the resultant array we will take the first value of the left and first value of the right so now that's very important why we are taking only the first value because if the robber robs this house the robber cannot Rob the left and the right side right so we cannot take Y and Y dash because Y and Y dash represent the maximum sum of the money that the robber obtained by robbing the houses below uh this node plus the current node right that we discussed right so y represents the money including this node and Y dash also includes the value of this node right or the money robber will get by robbing this house also so we cannot take Y and Y dash we have to take x and x dash because they represents the maximum value the robber obtained by not including this left and right side so as we are robbing the parent node we cannot take left and right so we will take X Plus x dash plus the current value of the node that is z so it will be X Plus X Z Plus z and b and from the root node we will return a comma B now let's see an example to better understand uh the approach that we talked about taken this example so we'll iterate uh in the DFS manner right so well we will go from start from the root node that is one we will go to 3 then we will on go on the left side but uh on the left side of three that is null so we'll return 0 comma 0. we will return an empty array of size 2. right with a default value 0 comma zero now we will go on the right so on the right we have again five so from 5 we will iterate left that is 9 from 9 the left child is null so we'll return 0. on the right again we have null so we'll return 0. now at nine what we have to do we have to again perform two operations first we have to calculate the maximum of left so from the left we are getting 0 comma zero so we have to take the maximum of zero comma zero that is zero on the right we are getting 0 comma zero so what is the maximum that is zero we will calculate the result is zero the first value of the resultant array that will be the max left that is 0 plus 0 that is 0 and now the second element of the resultant array will be the left zero the first element of the left that is zero and the first element of the right that is zero plus nine the current node right that will be 9 so we will return 0 comma I now at five we will go at right so again at right we have null so we will return 0 comma zero now again at 5 we will perform we will take the maximum of left so left is zero comma nine so maximum is nine on the right the value is 0 comma zero the maximum is zero and the first value of the resultant array will be 0 plus 9 that is 9 and for the second element of the resultant will be left 0 plus right zero so it's it will be 0 plus 5 that is the current node that will be 5 so the value returned from 5 will be 9 comma 5. now at 3 we will again return we will again do the same so at 3 we are getting 0 comma zero from the left so the maximum is 0 on the right we are getting nine comma 5 the value is nine the maximum value for the first element of the resultant array it will be Max left plus Max right that is 0 plus 9 that is nine the second element will be 0 plus 9 plus 3 that is twelve because left 0 is 0 right 0 is 9. so 9 plus 0 plus 3 the current node that is twelve so we will return 9 comma 12 from 1 now at 1 we will Traverse the right tree so we will go from one to six and then to 7 right till we reach the leaf node so 7 is the leaf node as it's the left child is null so we'll return 0 comma zero the right side is also return 0 comma zero at 7 we will again perform the same procedure we will calculate the left the max of left that is 0 Max of right that is zero resultant 0 that is Max Plus Max right that is zero and the second element will be left of 0 plus right of 0 plus 7 the current node that is will be seven so we'll return 0 comma seven now we will go on the right side of six that is set 4 so we'll four is the leaf node as from left side is null we'll return 0 comma zero right child digital will return 0 comma zero will again perform the same operation and will return 0 comma 4 from 4 and at 6 we will again do the same so first from for six we are getting 0 comma seven from the left and zero comma four from the right that and the maximum is seven and four respectively so the first element of the resultant array will be Max left plus Max side that is 11 and the second element will be left of 0 that is 0 plus 6 the current node that will be six so we'll return 11 comma six from six now at six at now at one we will again do the same so left we are getting nine comma twelve and for right we are getting 11 comma 6 the maximum will be Max left plus Max right for the first element that will be 12 plus 11 23 and for the second element that is left 0 plus right 0 plus 1 and finally we will take the maximum of 23 comma 21 that is 23 so finally we will return 23. so let's see the code part for it so I have coded this in Java language right so this is the class solution I have created a function that is introb which takes the root three node and I've also created a auxiliary method that is Rob sub that takes the root node and returns an array of integer of size 2. so we are first checking if the root is equal to null we are returning an empty default 0 comma 0 with size 2 right uh that will be our base condition now we are iterating the left child till we reach the leaf node and then the right side right usual DFS manner and each left and right child will return an array of size 2 so finally at an any Leaf node once we reach a leaf node we will create a resultant array and we will first uh the first element of the resultant array will be first we will calculate the maximum of left 0 comma left one right so the maximum of either of the two of the left side and maximum of either of the two from the right side and the second element of the resultant array will be the current node plus the left 0 plus right 0 as we talked about that the right 0 and right one will contain the value of the left and the child node also so we have to skip when we are you know robbing the current node so we have to skip the left child and the right side so we will only take the left 0 and write 0 that represents the maximum sum without the left child and the right child respectively and will result when and we will return the result and finally in the main method uh we will take result as an uh variable and we'll return the maximum of result 0 comma result 1. so let's try to run this solution so yeah test kit so let's talk about the time and space complexity so time complexity as we are iterating each element once right in a it's a DFS traversal so the time complexity will be bigger often in the worst case uh in the worst case where n is the number of elements and space complexity will be again n if the tree is q or left sided tree or right sided tree and where n is the number of elements so I hope you enjoyed watching this video so guys please uh share and subscribe if you have watched till here so it will give me motivation | House Robber III | house-robber-iii | The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`.
Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**.
Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_.
**Example 1:**
**Input:** root = \[3,2,3,null,3,null,1\]
**Output:** 7
**Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
**Example 2:**
**Input:** root = \[3,4,5,1,3,null,1\]
**Output:** 9
**Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 104` | null | Dynamic Programming,Tree,Depth-First Search,Binary Tree | Medium | 198,213 |
1,192 | all right i'm gonna explain how to do the critical connections in a network problem on leak code so i have an undirected graph here and first of all what is a critical connection so critical connection is just any edge part or movement will prevent some nodes from reaching each other so for example if i were to remove this edge here these nodes can no longer reach each other these nodes can't reach this node and vice versa therefore that is a critical edge let me put it back and this edge here to remove it same thing happens so these nodes can't reach these nodes and these nodes can't reach these nodes therefore that is a critical connection so let's put this back and this edge here if i were to remove it uh now prevents these nodes from reaching these nodes therefore that is also a critical connection so let me put that back now notice that these three edges that i remove so one two three uh these edges were not in the cycles of the graph so there's two cycles here there's one here and there's one here so these edges weren't in the cycles now why is that important because if you're in a cycle if you pick any node in a cycle there's at least two ways to get to all the other nodes in the cycle so for example let's look let's say these two nodes here these nodes are in a cycle right so these two here well if i to remove say this edge there's still an alternate path to get there because i'm in a cycle so uh therefore this edge is not a critical connection so all we want to do is we want to find the edges that are not in cycles so what we're going to do to find these is we're going to keep track of the depth we're going to kind of treat this like a tree and we're going to keep track of the depth that we are currently at and then we're going to return the minimum depth that we can reach uh when we're traversing this graph so we're gonna do a dfs or a depth first search let's just pick this node here and you could picture this like the root of a tree this would get a depth of zero okay now oh my whatever okay so this gets a depth of zero and then we're gonna go through our neighbors or our children whatever this is gonna get a depth of one and we're just gonna keep incrementing the step right as we encounter unvisited nodes so zero one just gets a two uh let's say we go in this direction here so we have two choices either this node or this node from the for dfs right let's just say we pick this node we're going to increase our depth again this is a 3. now notice that we ran into a visited node why do i know it's visited because it has a depth if it doesn't have a depth yet then we haven't visited it so what we're going to do is we're going to take the minimum depth from this node here so right now the minimum depth is just zero because that's the depth that it's holding and that's the only just let's just keep going so we're going to take the zero here and we're going to do the minimum we're going to do is we're going to pass back this depth that we encountered so this zero we're going to pass it back through the dfs recursion like so if you imagine our dfs is recursive calls like dfsdfsdfsdfs we're just gonna pass it back through the recursive calls okay so we're gonna take the zero and we're gonna do the minimum of zero and three and we're gonna pass back whatever so the minimum of zero and three is zero we're going to pass back to zero to this two and now what does this tell us here if we were able to find a depth or we're able to reach a depth that is less than or equal to my own depth then that means that edge is in a cycle because for example if we weren't in a cycle let's say we started zero then one this depth would just keep increasing but as soon as we have a cycle or we have a back edge to some node in the graph then we're going to run into a depth that is lower than us because we were increasing the depth this entire time and if we have a back edge to some node that we already visited that node must have a depth that is less than or equal to us okay let's get rid of this let's keep going with our example here so we ran into the zero we're going to pass back to zero we do the minimum of zero and three pass back to zero and here we still have to visit all the neighbors of two so we visited this guy but we didn't visit these right so we're gonna do is we're gonna uh add one to our depth so our depth here was two so this is gonna get a three this then we increase the depth again so we'll get a four and now we stop here right so we have no neighbors and now we're gonna pass back ourselves so we're gonna pass back four because we don't have any anything this we're gonna pass back the minimum depth that we can reach so the minimum depth that i can reach is myself in this case and we don't uh one thing to note is that we don't consider the guy that we just came from so whatever node we just came from which was this three we don't consider it so we only consider any other neighbors if they were here but not what we just came from but anyway we're going to pass back our depth here which is four and now because four is greater than three that means that this is a critical edge because if we were ju this means that we were only increasing in this direction therefore uh we never backtrack or we never had a back edge to some depth that was smaller than us therefore we're not in a cycle so because four is greater than three uh this edge is a critical connection okay and then we're gonna pass back the minimum of these two so between three and four three smaller so we pass back to three because three is greater than two here because the minimum depth that we could reach is greater than our current depth that means that this is also a critical connection now uh we pass back the minimum depth that we can reach so again we pass back the minimum depth we can reach here is zero we're going to pass back the zero to this one 0 is less than 1. therefore this is in a cycle and we pass back the minimum which is going to be 0 again and now because 0 is less than or equal to 0 that means that this is also in a cycle because again if uh if it wasn't in a cycle we would have received some depth that is greater than us because we were increasing our depth the entire time we should have gotten a one at least a one back from this um what we got is we basically got ourselves back which just actually tells us that this is the root of the cycle okay so anyway um that's not a part for this problem but anyway because it's less than equal this means that this is a uh this edge is in a cycle okay so now we're gonna go visit these neighbors this would get a depth of one right because we start at zero let's get the depth of one now this will get a depth of two and i'm just arbitrarily picking a path here so i could have gone this way it doesn't matter but so we go one then two then three and now i'm going to see this one here from this note here i'm going to see that i've already visited this i'm going to take the minimum depth that you can reach which is going to be the one and again we don't consider the node that we just came from right when i was here i don't consider the node that i came from so that's why the step stays at a one so we've one two three i see that i uh gave this a depth already i'm going to take the minimum depth that you can reach which is yourself and now so i have a one here then i'm going to pass the minimum depth that i can reach which is this one i'm gonna pass it back through the recursion then i'm gonna pass back the minimum depth here which would just be the one and now because this one is and also because these depths that i'm passing back are less than or equal to the depths in each node that means that these edges are in cycles this edge is in a cycle this edges and cycle this edges in a cycle because these minimum depths that i can reach are less than or equal to my cur to my own depth okay and again because one else number one this edge is in a cycle right and then we're gonna pass back this one to this zero and because one is greater than zero i'm sorry because one is greater than zero here because one is greater than my own depth that means that this edge is a critical uh connection okay so that covers the algorithm and i wish i had to code it so let's do that cool bye all right so let's code this out so uh they give us uh the list of connections here and because they actually tell us there's a connected graph right here in the constraints because um the number of connections is e greater or equal to n minus one which n is the number of nodes so if there's n minus one edges then that means it's a connected graph so for example let's say there was three nodes and there's two edges well that must mean it's connected right okay so uh what we're going to do is create an adjacency list so let's just create a map of integers to a list of integers so i'm just mapping the nodes they're neighbors uh jsoncliffs equals new hashmap and we're going to do our connections why is my spacing off okay so for every um connection in the connections and these connections just represent edges right so we're just going to uh insert the edges so compute if absent uh pass in connection dot get zero this is just the first node in the edge and it's key doesn't exist so if this key doesn't exist we're going to create an array list and insert it into the map and if it does exist it would just return the arraylist that we created in the previous iterations of the loop so then we just add in the other node in the edge or the connection so get one and because this is undirected we have to do because it's undirected we have to do the reverse of this um so we're just going to copy paste this and just flip it so one maps to zero okay so now oh so we have our urgency list now we need to uh let's create the thing that we're going to return and we'll just call this cc for uh critical connections so equals new arraylist and then that needs to be a semicolon and then return cc and we just need to do like a depth per search in between this right so let's see let's start with what so what do we need in this step for search so we need our we need to pass in the critical connection array list because we're going to add to it right so we're going to populate it we need to keep track of the previous node that we just came from we need to keep track of our the current node that we're at in the dfs we need to keep track of the depth of our current node and we need to keep track of you know let's actually just type this out as i'm saying it so let's call this find critical connections and so we're going to pass in the previous node from the beginning with negative 1 to represent there is no previous node and we're going to say let's just start from zero so this is our current node that we're going to start the dfs from and we could pick any node as long as it was less than n but you know why not just start at zero and we're guaranteed to have at least two nodes in this graph so i'm just passing on zero so anyway uh the then we need to pass in our depth so we're just gonna start at a depth of zero and then we need to pass in our adjacency list we need to keep track of the minimum depth that every node can reach so what i'm gonna do is i'm going to create an integer array so integer and there's a reason i'm using the object version of integer and not a primitive version so and i'll you'll see in a second but because i actually want to make use of the nulls um but integer array uh what do i want to call this min depth equals new integer pass in n so n is the number of nodes so every node has some minimum depth that they can reach okay and so we're gonna pass that in and am i missing anything oh pass in this critical connection that we're gonna populate and i think i feel like i'm missing something but if i am i'll figure it out later okay so let's just do private void we actually have to write out our dfs now so find critical connections so we're going to pass it in the previous note that we just came from pass in the current node pass in uh the depth pass in uh oh what this should be oh wait oh never mind so pass in the adjacency list so just copy paste this pass in what am i missing i'm in depth where is where are you passing this guy there's a lot of uh arguments okay and let's put some new line and then we're going to pass in the critical connections okay method signature complete all right so now what do we need to do let's uh populate our min depth so in the beginning we're going to say the min depth that we can reach is ourselves or is our as our own current depth so the min depth of this node is just equal to depth so the min what i'm just saying is the minimum depth that this node can reach it's just its own depth we're just going to initialize it to that in the beginning and then we just need to look through our neighbors so let's say for every neighbor in the adjacent list dot get node then we want to say okay if the pre is the thing that i just came from so if previous equals neighbor then just ignore it we're just going to do nothing just continue and if min depth of neighbor equals null so this is why i wanted to initialize it to an integer object array and not um just like the primitive ins so if it's null this means it's not visited this is an unvisited node here this neighbor is unvisited and we just want to call dfs on it or our dfs method on it so let's just pass in uh so no our current node is going to be the previous to this neighbor so neighbor will be the current node in this dfs call and then we're going to pass in depth plus one pass in the adjacency list pass it in depth pass in cc okay and now we can say if uh depth wait how do i want to do this if the minimum depth of our neighbor so this here this mendeth neighbor will get populated because we're dfs'ing on that neighbor first so it'll get populated uh it definitely get populated here but there's another way it can get uh changed but you'll see in a second so if the min depth of the neighbor if the minimum depth that this neighbor can reach is greater than my own depth that means it's a critical connection so we're going to do cc dot add and then just create a list out of the node and the neighbor because this edge here the edge between node and neighbor uh is a critical connection because it's not in a cycle because if it wasn't a cycle this would be less min depth of neighbor would be less than or equal to depth okay and last but not least we want to assign min depth of ourselves to the minimum of uh ourselves and our neighbor's min depth so in depth neighbor okay so all this is saying here is if mine if my neighbor could reach a certain minimum depth well that means i can also reach that minimum depth right so i'm assigning my own minimum depth to whatever minimum depth my neighbor could reach assuming that it's less than or equal to my own okay so let's run this make sure it works and i missed a bracket somewhere wait line five i always miss this bracket okay run code another one because i copied and pasted run code okay submit it's taking its time all right cool so uh it works and if the time complexity is going to be o v plus e because it's just a depth first search and um and the space will just be o v plus c because again i step for search but anyway uh we are done um if you like the video you can give it a thumbs up and yeah you can subscribe if you want cool bye | 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 |
39 | hi everyone today we are going to solve the readable question combination sum so you are given array of distinct integers candidates and integer Target return a list of unique combinations of candidates where the chosen number some to Target you may return the combination in any order the same number may be chosen from candidates an unlimited number of times two combinations are unique if the frequency of at least one of the chosen number is different the test case are generated such that the number of unique combinations that sum up to Target is less than 150 combinations for given input array let's see the example so you are given negative 2 3 6 7 for candidates and the target is seven output is 2 3 because uh total number of the combination should be a seven and also uh seven itself so total should be seven yeah that's why our output is two to three and seven okay so let me explain with this example so candidates are like two three six seven and the target is seven so I already wrote down the decision tree and uh every time we have two Choice um include current number or not include so why do we need a not include case so because um we need to uh remove the duplicate combination so let me explain with a like a concrete example now we are standing two and then we have four Choice uh um two and the other three and six are the seven so we can create like a 2-2 the seven so we can create like a 2-2 the seven so we can create like a 2-2 combination two three two six to seven and let's go down like a 2-2 bus and let's go down like a 2-2 bus and let's go down like a 2-2 bus and then again we have a full Choice other two three six seven and we can create that like a two three two six two to seven and then let's go down there like a two three um pass so now we are starting a two three uh combination and then actually we have a full Choice again it's like a other two three six and seven and then when I add a 2 to the like a 2 3 combination we can create like a two three two but look at this two to three so actually um they are duplicate because uh description Set uh two combinations are unique if the frequency of at least one of the chosen number is different but um we use a 2 and 1 3 and the two and the 1C actually exact same so that's why these two are duplicate so to prevented this situation so actually we need a um not include the case so let me go back to previous explanation so uh if we have not include option we can definitely create a unique combination so okay so let me go down from Top so now fast number is two so okay uh we go to uh we move down the include case so now we have two and then again um so we can choose the same number so um again we have two Choice um include the two or not include and let's go down the include case so now we have like a two so again uh we can um we have a two option that can include two will not include two so let's move down and then two to two combination and uh again we have two Choice um included two will not include and then let's go down two and then actually um this is a total eight so it's a over seven so in that case uh this bus is a long uh answer and then if not include and we have a two and then so in that case uh we don't add these two so other choice should be like a three or six or seven so out of three here but uh this is over seven so in this case um this bus is not correct pass and then same thing like not include three in this case so this is a includes three this is not include three so we still have negativity and then again next number is six so include six or not include six but this is like uh um 12 or more than 12 so I think this pass also definitely a long answer and then uh let's go back to here in the two and then not include the case so still we have like two so this bus are this bus is like included or not included so next number is three and then increase three or not include three so when we are the include three we created like two to three so which is a total of seven so this is a one of answer we found and then let's move down not include and we still have like a 2-2 combination and we still have like a 2-2 combination and we still have like a 2-2 combination and then um next number should be uh six so include six or not include six but if we include six that should be ten so that is a long answer over seven and then maybe we are the seven not include seven and then definitely uh this pass is also wrong answer so and then let's go back and then again I'll not include the case we moved on this bus and then so we have two Choice again uh include three one not include three and then um I'll move down into three and then if we next choices includes six one not and include six definitely this is over seven so that is a wrong answer and then uh yeah actually uh we do the same thing and then in the end this pass also um long answer and then um so another case is uh yeah we go down not include two in the case uh start from three so increase three or not include three so and in the end so this pass will be long answer and then finally um not include and then so yeah in this case we have two Choice include six or not include so and this pass also a long answer um and then we go down here we don't still have any candidate and then next uh include seven or not include seven and then actually uh this is a wonderful answer seven and then um there's no candidate anymore so yeah uh that's uh how this decision tree works and then we find a two to three and a seven so that's why we should return these two combination so that is a basic idea to solve this question um with that being said let's get into the code okay so let's write Circle first of all result variable um with empty array and then okay so we're done um let's say make combination so passing that like an index number and combination and a total number so let's create a inner function so this make combination and this is an index and a combat combination and the total current total number total equal Target in that case we need to the current combination to result variable so let's Dot append and uh combination and if we put column here we can like copy the current combination to result variable and then just return if not the case if total is greater than Target or index um greater or equal lengths of candidates in the case we just return if not the case first of all check the included case as I explained earlier so combination dot append um other current number so can be dates and the index then let's move down the include case so okay I copy this then um index um so we try to add same numbers or just pass the same index current index and the combination and uh total should be total plus and this one um current number then we can check the included case after that um no we have to check not include the case so that's why um we pop the current number then let's move down there like a distance 3 so do you remember so make combination in that case so we don't increase the current number so that's why we have to add next number so that's why index plus one and then a combination so this combination is not include the current number and then total also uh we don't add a current value to Total because this is not included current number and then just return three times result variable yeah I think that's it so let me submit it yeah looks good and the time complexity of this version should be a order of uh 2 to the power of T So T is a target number uh because potentially uh the distance height of decision tree should be a target number so that's why and every time we have two choice so that's why our 2 to the power of t so let me summarize step by step algorithm this is a step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm of combination sum step one initialize result variable Step 2 in inner function if current total of combination is equal to Target then other current combination to result variable and return if total is if the total is greater than Target or index is greater or equal to length of candidates then return if not the case are the current number two combination then move down to the next decision tree after that pop the current number from combination then move down to the next Edition tree yeah that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question | Combination Sum | combination-sum | Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.
The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.
**Example 1:**
**Input:** candidates = \[2,3,6,7\], target = 7
**Output:** \[\[2,2,3\],\[7\]\]
**Explanation:**
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
**Example 2:**
**Input:** candidates = \[2,3,5\], target = 8
**Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\]
**Example 3:**
**Input:** candidates = \[2\], target = 1
**Output:** \[\]
**Constraints:**
* `1 <= candidates.length <= 30`
* `2 <= candidates[i] <= 40`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 40` | null | Array,Backtracking | Medium | 17,40,77,216,254,377 |
1,712 | hey what's up guys this is zhong so 1712 ways to split array into three subarrays um so you're given like a array right consisting of i believe they're all positive yeah non-negative numbers positive yeah non-negative numbers positive yeah non-negative numbers and it asks you to split those arrays into three parts left middle and right and where the and the left middle right has to be an increasing sum and you need to find the total waste the total number of ways to form such a split and for example right we have nums one and obviously there's only one way of doing that and here we have like uh three ways basically we split one two and this and for example three here there's no way we can do it so that's why we do we split we return zero and the constraints is like this so it's ten to the power of five i mean to start with right so this one is a little bit tricky because you know i think a common solution is that we fix the uh the middle y the middle array here so let's see if there's an array here we have a middle here right we have a middle that's start and end by using like a prefix if we fix the try to enumerate all the possible uh locations for the middle array we can just get the left and the right by using a prefix sum and then we can get the final answer but the problem with this solution is that since we have like 10 to the power of 5 you know to iterate all the possible locations for the m we're gonna use we will need to use o of n square time which means it will tle so the way to solve this problem is that we're going to use a binary search so how do we use a binary search let's say we have like we have fixed the uh the left side so which means that we will be looping through the numbers one by one from left to right and the moment we have fixed the left let's see we have i here so this is i and here we have a left for example i is one this is i and we just need to use the binary search to find the uh the left boundaries for the middle one for the middle array and the right boundary for the middle array so which means enough for this example right let's say i is one and the left boundaries for the middle array is this is here so this is the left and the right boundaries for this one is the is what is the uh is here that's the right boundaries and in the end we just need to use the uh the right boundaries miners left boundaries plus one and to get the uh the total a good sub good split with this uh zero to i as the left array and now the problem comes down to how can we find the left and the right bound the left and right boundaries for the uh actually it's the ending boundaries and the left and right ending boundaries for the uh for the middle one because the middle one will always start from i plus one here and we just need to find the uh the bound the range for the ending point of the middle one then we can just use that to find the uh the possible good ways right good ways to split the nums so and the problem so now the question is what is the left boundaries so the left boundary is that you know we want to make this middle like array as small as possible so still the middle array needs to be greater than the left equal or greater than the left that's the uh that's the binary search for the left uh for the left boundary let's say if the left boundary is one in this case right if the left boundary is one and we just need to find the uh the smallest basically the shortest uh middle the shortest middle array whose sum is not smaller than one in this case it's one uh it's two here right that's why the uh the left boundaries for the uh for the middle array is gonna be the two here and how about the right boundaries so the right boundaries is that we want to find the longest middle array whose sum is smaller it's not greater than the right one right so that's the uh that's the right boundaries and to find the longest the subarray whose sum is not greater than the right one we're gonna use the remaining since we have the left and we have the total so the total miners left will become and we divided by two that's going to be the uh the maximum sum for the middle one that we can get because if we go over this one which means then that means that you know the uh the middle one will be greater than the right one and that will be a that won't be a good way that's why and so this is how we uh find the right boundaries for the uh for the middle range okay so i'll start coding and i'll explain a little bit more so basically we have like this uh nums here right and we're gonna use we're gonna calculate the pre-sum so for me i calculate the pre-sum so for me i calculate the pre-sum so for me i prefer using a dictionary so that i can handle this minus one case and then i just use this uh i num in the enumerate nums right so and we have a pre-sum nums right so and we have a pre-sum nums right so and we have a pre-sum i equals to pre sum i minus one plus num okay and then we have the uh the answer equals to zero so for i in the range of what and i in range of the uh and my minus two so remember so here we're looping through the left right loop left array that's why we start from 0 but we stop as n minus 2 because we need at least two numbers left for the middle and right and the left sum right so the left sum will be a pre-sum of i sum will be a pre-sum of i sum will be a pre-sum of i right and uh we're gonna have like a remain maybe okay let's do a remain because the three sum n minus one minus left right and we can we need to have like early termination here so which means that if the pre-sum the pre-sum the pre-sum n minus one is smaller it's smaller than the left uh times three then we can simply break here because it means that you know the left is already greater than one third out of the total so which means that you know we'll never find like a good split right at the uh if we keep increasing the left array that's why that's when we can simply break here otherwise right we have a left right and the right so left we're gonna have like a search left right we start from i plus one and the target is the left and then the right one is the search right and then we have a i plus one and then we have a remain divided by two right and then in the end we have answer dot n plus i minus sorry right minor's left and then plus one and then here we just return the answer dot or we also need a mod here i also define mode 10 to the power of 9 plus 7. so now let's implement this one here so the reason i do a i plus one is that you know the i is the ending point of the left array that's why to search the uh to search for the middle one i started from i plus one so search left i dot target right so i'm going to use a target here so left will be i and the right will be what would be m a minus 2. so why i do an n minus 2 is because we need at least one array left uh sorry one number left for the right array that's why we stop at n minus 2. so the first one is search left which means that we're searching the minimum value right so if you guys remember the template for searching the minimum value is that you know the uh so here we have a left plus uh right minor slapped and divided by two and if this thing is true so if this one is true right something is true and then we just try to shrink the right one otherwise we just shrink the uh we just increase the like the left one and then in the end we return the left that's the template first for searching the minimum values which is the which is why we're searching using the search left here and since the left is because so the reason we do our r equals to m is because you know we're trying to move the right boundaries to as uh to the left as possible so that we can get a minimum values because the because this r could be the our answer and since we're doing a left equals m plus one here we don't need to do a uh r minus l plus one here if we're doing the uh the search right which is going to be the maximum values uh which will be implemented later we need to do a r minus l plus one since we'll be doing like we're gonna assign m to the left now for this like helper for this uh conditions basically we're checking if the pre-sum m miners pre sum i minus one which where this one is greater still greater than the target right and then we just do this so the reason so currently this is the amp right we have m here sorry not this is the uh l minus one now this should be i minus one sorry because you know the uh the starting point is the it's i plus one here right and to calculate the uh the range sum for the middle one for this middle range from m to the i here we need to go back to i minus one because this is the i plus one and to get the range of this one we have to go back one more right so that's why we do i minus one here so and that's the uh that's how we calculate the left boundaries for the uh for the middle one and now for the right boundaries right also same thing we have at the range is the same right so left equals to i and r equals n minus two the only difference is that we're going to use the uh the template to calculate the maximum value the max in this case is going to be the max index right middle m uh r minus l divided by two right so basically we're trying to expand the uh the middle one as long as much as possible right when the uh if the pre-sum right of if the pre-sum right of if the pre-sum right of m minus same thing right minus pre-sum of i minus one okay oh i minus one when this one is actually either equal smaller than the target because here we're giving like a remaining divided by two right so that's going to be the maximum the middle one can get right so that's why when this one is it's true since we're trying to get the minimum the maximum values we're going to do a l equals to m right otherwise it's going to be the right equals to m minus 1. and since we're doing like l equals to m here if we need to do a plus one otherwise we'll end up with the infinite loop here and then we just need to return the either out or right doesn't really matter yeah i think that's it so if i run the code okay so the time and space complexity right so for the time complexity we have of n here and then we have of n plus binary search so the time complex is going to be o of n log n right and the space complexity is the uh it's o often since we're using like a dictionary we or you can use the list it doesn't really matter to store the prefix sum yeah i think that's it for this problem what can i say mean so for this problem i think the uh to come up with the prefix helper prefix it shouldn't be that hard the difficulty for this problem is that how can you effectively find the total number of the good ways to split given like a fixed left subarray right a naive approach is that given uh given the uh like a fixed left we have to try all the possible ending points for the right uh sorry for the middle one for the middle array and then we check if this if by looking at this by giving like this ending point for the middle one is if the if this middle one and the right one and they are all they are good split by comparing the thumb with the left middle and right and since the uh the presump right all the numbers they're all positive integers then we have like then this leads to a binary search to find the left and the right boundaries for the middle array then we can just use a log n time to find the uh the basically the valid middle range for our good splits yeah and after that it's just like a way to two templates to calculate both the minimum index and the maximum index and to calculate the minimum maximum index we need to use a different like target right because they are they have different meanings yep i think i'll just stop here and thank you so much for watching this video guys stay tuned see you guys soon bye | Ways to Split Array Into Three Subarrays | unique-orders-and-customers-per-month | A split of an integer array is **good** if:
* The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right.
* The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in `mid` is less than or equal to the sum of the elements in `right`.
Given `nums`, an array of **non-negative** integers, return _the number of **good** ways to split_ `nums`. As the number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[1,1,1\]
**Output:** 1
**Explanation:** The only good way to split nums is \[1\] \[1\] \[1\].
**Example 2:**
**Input:** nums = \[1,2,2,2,5,0\]
**Output:** 3
**Explanation:** There are three good ways of splitting nums:
\[1\] \[2\] \[2,2,5,0\]
\[1\] \[2,2\] \[2,5,0\]
\[1,2\] \[2,2\] \[5,0\]
**Example 3:**
**Input:** nums = \[3,2,1\]
**Output:** 0
**Explanation:** There is no good way to split nums.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 104` | null | Database | Easy | null |
399 | Jhaal Hello Hi Guys Welcome to Question Today's Question Is Your Devotion in This Question Also Aryan Equations in the format K Divider Par Pimpal Bhi Are Very Well Represented S Strings And K Is The Real Number Details Of Lord Floating Point Number Jeevan Sambhav Is Return Given answers in the answer did not exist return minus one t input always with met your mother carried you no division by others on for example and bse midcap 2002 android 2.3 questions and answers of b android 2.3 questions and answers of b android 2.3 questions and answers of b id m id porn a hind its in this manner definition answer A waste is the answer is not exist increase minus one so let's understand the approach of this question on a nine input brother given a question is that is abcd person mortgage help us to represent a different like subscribe Video not which exam abhi net Chalu ab it represents a village bhi representative adverbs equal to 2.0 and they will be adverbs equal to 2.0 and they will be adverbs equal to 2.0 and they will be divided such represents 3.0 that is 39 divided such represents 3.0 that is 39 divided such represents 3.0 that is 39 benefit chief to find ago Mercedes 500 can find wasi karni has to be done on the net by mez par bhi into middle east questions will be divided into three And Web 2.0 In Just 120 Days Next Question Is A Deadly Vacancy Date On Date Is Not Given Question Only To Do Subscribe My Channel Thank You See In The Middle Of Equations And We Will Give You Techniques In This Question In Every Question No Duty BCD Notes And See The Question Mode Of Karo Apne Didi Question Dentist Spending To Egg White Baby And Response For Youtube 8034 And Look On The Graph Like This Like Number To The Weight Of Two To Two Will Multiply Bill Passed From Multiple Values On Bill Passed From Multiple Values On Bill Passed From Multiple Values On Ajwain Use 2582 ciadv.msc So Answer In This Ajwain Use 2582 ciadv.msc So Answer In This Ajwain Use 2582 ciadv.msc So Answer In This Case Which Path From There Will Reach From First Always Be Benefit To C 234 Party Will Multiply 2328 Answer Will Come Out With Six Suno Let's Understand This With The Help Of Record First World You Will Make House Map in which relates to are not value and its corresponding and values and did not to which values and did not to which values and did not to which this kid after his lap and android app the scheme will be distinctive that and its billion factor of vector of prayer for spring corner double that and will not sweetness MP So The Also This Is Pantagraph Is The Earth Is This Is The Value A Factor Of Pair Vitamin A Star Value Converted Into Multiple Candy Crush To Multiple Notes In The Morning To Take All The Notes Into Consideration Between 828 Sudhir Kumar Yadav Actor And White Hair Spring Document Double Dentist That Between Value Of Electronic Also No Evidence Which A Great 282 B.Ed It From Thee To Biggest To Sudhir 282 B.Ed It From Thee To Biggest To Sudhir 282 B.Ed It From Thee To Biggest To Sudhir They Can Appear To The Destination And Disease But You Know Where To Front Is Graph What Will It Work E Will It Rain Today Equation Tractor Earning Ko 20 I Lashes In The Equations A Good Size I Plus Administrator And Questions Later Dated This Question On That Foreign Question Listen What Will Do The Equations Will Form The Node Of Every Units Prevented From Equations I0 In Which Equation of asbestos is difficult-2 acid key and difficult-2 acid key and difficult-2 acid key and vector will appear and service to the destination from the 1st key destinations has been switched off but this equation is one of commerce distance between and with this exact that Bigg Boss destination and distance Between the three values of distance Between the three values of distance Between the three values of iPad-2 So in these the iPad-2 So in these the iPad-2 So in these the value of that I bestows apps in this question B.Ed bestows apps in this question B.Ed bestows apps in this question B.Ed form not from A to B the problem is distance to but in the possibility when any one India answer also has to a view to find Answer of big software to form in this case view for directions of west from the to biggest to distance to but from 2725 video a transfer from tamil 182 member middle of noted that you know what you need additional director revenue collection now question on jai hind is Saliva Vikram Arabic Vikramaditya BMW Value Vikram Dash Mahin Se Destination From Noida A Distance Of Wallet Will Be In Voice Of Elevated 1.10 Divide By In Voice Of Elevated 1.10 Divide By In Voice Of Elevated 1.10 Divide By Values Of Life Values Of Life Values Of Life A Day From Distance From A Stupid Distance From 2ND Year To Find This Dialysis Machine 12231 Divide Value Sardar Positive Vibration Rashi Fifth Odi Of Bigg Boss Disprin SD Ki So After His Laughter For Graft Nobody Will Do A View To Solve Aapke Is Not Withdrawn Twitter After They Literature Courier Actor And He Will Declare Spring Chord Source The Prince Was With equal to a starting point What is this value2 The querist I Komal ji Road This starting point nou the destination Tutorial Idli Sandwich Tourist destination nor the distinctive destination Who is equal to queries that I to Madhavan Vishal A great source and destination nor Will U Will Perform Will Not Perform As A Billion Day To Find The Value Now F4 Difficult A Now Straight Road Will Take Another Unknown Map Fit They Visited There A 13 Comment And With Limits And Will Be Presented A That Boat Boating To Take Available Call Answer In Which Will Come Final Answer Pimps Minus One Big Boss If We Do Not Find Yourself Do Not Find Any Answers In This Case Probe Into A Story From The Two Leaders Cannot Be Possible Answer Swar Answer Will Remain In - Only And Sorry This Will Remain In - Only And Sorry This Will Remain In - Only And Sorry This related double qualities in decimal to every - 100 no any rate other way to take his stamp are able to answer the - 100 no any rate other way to take his stamp are able to answer the British to 8mp rear answer a key and wishes with one oh a noble qualities of this has been quite definition in which force will pass Snowden Destination Node's Deonar Dinner Whole Graph Maze MP The Bank Will Pass Visited There At This That Visited Dena Bill Pass A Answer Pimple Which Will Surly Be Admitted To The Final Answer That Is The What Is The Value From Her [ __ ] And Will Pass Time Prevail [ __ ] And Will Pass Time Prevail [ __ ] And Will Pass Time Prevail Which Will Be Reduced By Calculating Answer Sheet Eliminator Be Temperature Reviews Now Benefits and Answers Milk Available Which Will Be Disappointed Answer Vegetable Idli Pass That Reference Sovand Se Verses Completed Shreyans Available Will Give S D Will Give This Value Difficult Value Doob toe return back side 2222 a factor double answer tweet container answer morning straight versus over all differences with story answer shareef bante this is supposed final answer a in puncture fragrant differences over divine final answer and dinner final answer is in this that no after 10 b Vitamins and Final Answer Sudhi Code But Where to Writer Difficulty Function Listen Let's Look at How Pretty Function No Videos Function Avoid a Function at Its Content Subscription of MPS Customer and Width Graph Widep The Video then subscribe to the key and vegetables are in temperature which will Help in computing answer selection left side is function so let's celebrate cases when a form good source notice already been visited details of MP board account is will return from her dentist a senior a the first also move including doobie denge rules bittu hai but are they Not Already Has Been Visited This Place Will Do Not Operate And Will Return Simply Written E And Sunao Close This Episode And 985 Good Source Notice 112 Key Definition It Means That Wear Powder Answer Gave Powder Pat Suno And Answerable Will Be Updated To Stamp And Will Return From Fear Not Know What Is Equal To A Destination What Will Happen The Value Of Time Tour Final Answer Dance Available Will Get Updated With Answers In The Answer Will Get Updated With No David 21 That Nobody Will Perform Edifice For And To I Lately extend MP of this day will move tool child artists and use this thank you will patience function will not support his death does not first unite first destination remains same that every I pregnancy center graph remains same center visit here have already been Updated for this current thinking notes will pass and visit here's boat and answer base Baliye-5 acid this because it will only be boat and answer base Baliye-5 acid this because it will only be boat and answer base Baliye-5 acid this because it will only be updated in this case not temporary force 980 initially temporary force one now so initially temperature was burnt and but did not know Where Move Into Bishnoda Calling It A Person Does Not What Will Happen When You Should Not For Next BF Vikram Bhi And An Answer Till Now Will Be Do Hai So This So Day Next So 210 Not For Next Debit Amazing That First Day Test In this case being displaced Vikram also and temporary force will be multiplied method a good son second a temperature in multiply with you that distance between and be let this distance between and reduce to but time will be updated like this Sudesh Bhosale And Sacrifice Code Normal Return From Here A Ka Jutan Including Sudhi Difficult And Research Center Code When Vitamin From Here Answerable Business Answer Is Main Anil Son Person Answer From Here Not Change This Code For A Disco Do I Will Tell You Why Know At This Time Arvind Ko Dater's Gift Hair Returns But Was Not Forget To Gift Hair Returns But Was Not Forget To Gift Hair Returns But Was Not Forget To Check Weather This Has Not Yet Been Visited Not Sure To Check Id Would To Not Withdraw Note 3 And Declares Answer Key Of The Temple Situated In The Middle Of Knowledge 101 Basic Concept About One Thing That Is A Noisy Heads Giving Wrong Answer By Others On All Dear All Queries Or Correct But Still From Last Related To Giving Wrong Answer But That Also Beneficial Now Last Premise Divide Activex But They Can See Did Not Know What Is Not Present In The Question Civil Defense Nidra Devi Node Of Ne Maximum Per Graph With You Will Only Call Caller Difference Is Dare That Current No Data Sources Printing Office Office Office A Source Of Who Is This Is The Condition Critical Issues Notice Present Hindi Graph One Only When So at all had given this function he did not present when will not call the not quite difficult particular a query chocolate sandeep code a and listen dj gun tan se demonetization code a yesterday morning it's getting accepted aayog ne district's video thank you know | Evaluate Division | evaluate-division | You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits. | Do you recognize this as a graph problem? | Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path | Medium | null |
206 | hey everyone welcome back and let's write some more neat code today it's actually raining outside right now pretty hard so hopefully you can't hear it too well so today let's solve an easy question reverse a linked list and this question is actually like a sub problem that's needed in a lot of other questions like linked list related questions so it's definitely good to understand so just like the problem says we have a linked list we've got some nodes and we just want to take each of these links reverse them keep doing that with everything and then this is going to be the new head and then we're going to return that and they tell us that this can be done two ways iteratively meaning with just pointers and also recursively and i'll show you how to do it both ways so we can do this with two pointers because we want to reverse it so like from the perspective of this node instead of the next pointer pointing at three we want it to point at the previous node one so if we want to do this iteratively we can use two pointers like many problems now what are the two pointers going to be we can have initially a current pointer so we can initialize current to the first node which is our head and we can also maintain a previous pointer which initially is going to be set to null so for the first node 1 we're going to take the next pointer and reverse it so now the next pointer is going to be pointing at null so this is now going to be the last element in our new reversed linked list so now we can shift our pointers so we're going to take the previous pointer and then shift it to current and we're going to take the current pointer and shift it to the next node now since we broke this link we have to save this somewhere before we end up breaking this link and i'm going to show you how to do that in the code so now our current is 2 we want to take the next pointer and reverse it so the next is now going to be like this so it's going to point at previous so we can reverse the next pointer and set it to previous and once again we're going to shift our previous pointer to current and our current pointer is going to be shifted to next now we're finally at the last node we can once again update the next pointer of this current node and so now when we update our pointers previous will be here and current is going to be at null we've reached the end of our list now we want to return the head how do we return the head lucky for us the previous pointer is equal to the new head right so this is going to be our result just like in the drawing we can initialize our pointers first previous will initially be null current will start at the head and we want to keep going until we reach the end of the list so while current is not null we're going to reverse the pointers so we want current dot next to be set to previous and then we can shift our pointers right so we can update previous set it to cur and cur is going to be equal to current.next cur is going to be equal to current.next cur is going to be equal to current.next but notice how we set current.next but notice how we set current.next but notice how we set current.next to previous before so when we do this we actually are going to have a temporary variable called next which i will do at the first line when we start our loop so we can save that in next so then when we update current.next so then when we update current.next so then when we update current.next you know we still have that next pointer and lastly we return the result which we know is stored in previous when this loop stops executing so it works and this is actually the most optimal solution the time complexity is big o of n and the memory complexity is big o of 1 because we're just using pointers right no data structures or anything but if we want to do the recursive solution then the time complexity is also going to remain linear but the memory complexity is going to be linear as well so we're going to need extra memory so it's not the best solution but i'll still show you how to do it so usually the best way to think about recursive problems is to break it down into a sub problem right so if our initial head is one we start at one and this is our linked list right but let's say i want to do a recursive call instead of reversing the entire linked list i'm gonna reverse the remainder of the linked list so everything except this one so now i have a sub problem right now i only have two nodes to deal with but let's take it one step further this is now my new head right and i'm gonna break it down even more i'm gonna say reverse this portion reverse the sub problem reverse only one node so then if we try to break it down even more then we're going to get this is our sub list right but this is just null so we can't really reverse that's the base case so now we're at this we only have one node and we want to reverse it how do we do that well the next pointer is pointing at null instead of that we can take the next pointer and set it to previous not really because this is recursive and at least the way i'm gonna do it i'm gonna set i'm gonna keep the pointer pointing at null so we technically reversed this portion which is just this right it's just a link list of one so now we're going to pop back up out of our recursive call and now our job is to reverse these two nodes so since we're at 2 we can access three so what i'm gonna do is say okay the next pointer of this is actually gonna be set to me to is gonna be set to two where i'm at right now but my next pointer two's next pointer is gonna be set to null so notice that so far we have done our job we reversed a linked list of size two right this is going to be the new head and this is the tail this is the end of the list so we did our job of reversing it reversing these two nodes but we still have one more node so we're going to pop back up out of our recursive call okay so now we're finally at the last call so our sub problem is to reverse these three nodes and we can repeat the same thing we did over here we're gonna for one ins since one has access to two we're going to set two's next pointer over here instead of null we're going to set it to one and the next pointer of one is now going to be null because we've reached the end this is going to be the new end of our linked list so we've done our job we recursively took our linked list and reversed it the only problem is that we are doing this recursively so we have to in our code we're gonna have to maintain the last node as the new head so now let's code it up as with most recursive functions you want to do the base case first so if the head is null we can return null and i'm going to make a variable to maintain the new head which i'm going to initially set to head is the current node that we're at in our recursive call so if head dot next is not null if there's still a sub problem if we can keep uh reversing then we're gonna have our recursive call so reverse the list pass in head dot next and the return value of this we are going to have as the new head so if this returns something so we're going to set the result of that to new head and since head dot next is the next node of head we want to reverse that link so what we can do is get the double so head dot next is going to be set to head what this is doing is just reversing the link between the next node and head and lastly we can say head dot next is going to be equal to null so if head happens to be the first node in the list we're setting the next pointer to null and of course this function wants us to reverse the list and return the new head so we're gonna return the new head so i think so this works and i think it might be a little confusing the way i wrote it because we have head.next.next wrote it because we have head.next.next wrote it because we have head.next.next but if you want to understand it a little more i would try to like mentally run through a couple test cases for example if you were just given one node like if you were just given a linked list of this try to run through the code see what the code does see what the function returns see which like this statement would not ever execute if we were given a link list of size one this is not going to execute so just kind of like try that out see what happens if you had a linked list of size two like this and use pen and paper draw a picture and lastly the reason why the memory is linear is because if we were given a linked list of size two our recursive call is gonna be size two but i hope this was helpful please leave a like and subscribe thank you and thank you so much for watching and i'll hopefully see you pretty soon | Reverse Linked List | reverse-linked-list | Given the `head` of a singly linked list, reverse the list, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[5,4,3,2,1\]
**Example 2:**
**Input:** head = \[1,2\]
**Output:** \[2,1\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is the range `[0, 5000]`.
* `-5000 <= Node.val <= 5000`
**Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both? | null | Linked List,Recursion | Easy | 92,156,234,2196,2236 |
1,583 | hello this was uh this is the second question of the 206 with code uh contests it was a little bit hard for me to figure out how to do this uh in a satisfied manner and it started hard by just by uh the question itself okay i took some time to understand exactly what they are asking and i will try to explain in the easiest way possible so starting with what this questionary has um uh we have an n which is the number of people okay is the number of people preferences is uh is um so let me start again the goal of this question is to find an mp people that are paired okay people are paired and they might be uh unhappy and what defines if they are unhappy or not is uh how they are paired according to their preferences so if you see here the person zero as preferences first one second two third tree then the person one has these preferences like the highest is the lowest index so these are their preferences however they can be paired in a totally different way that can make them feel unhappy and what defines if a person is unhappy is if there is a better uh match in another couple okay and also uh dead person so unhappy people are cases where this person for instance this person would prefer to be with this one and also this one would prefer to be with this one this is these are the cases where we will find one and two unhappy people okay so this is the kind of work that we have to do we have to find the couples uh in which one or both of them uh would be better in another with another uh person so how i have tackled this problem how if i tackled this problem so i have broke the problem in three phases the first phase was to build a matrix okay the first step was to build a matrix with the preferences and the weight of each preference okay so if you see in here each uh each person has a given preference right and i will copy this so just one second this is a little bit small um yeah better like this so each person has its preferences and we can see here right uh we can see person zero person one person two person three okay so the first step that i did was to put um a value for each position for instance people zero person one person two person three uh if you go to the person one uh we and if we put the preferences like three this is tree this is reference true this is the preference one what i did was okay uh you can cannot be a match for yourself so i put minus one in here um actually i can put zero it was zero okay so you can never be a preference for yourself then uh the person one has the maximum preference so i put three in here the person two has the preference of two and the person tree as a perf preference of one and then i did the same for the other elements so three maximum preference i go to the position 3 and i score 3 then i go to the position 2 and i score i put the preference to then zero is preference one and this one is zero because you cannot be a preference for yourself so again tree we put maximum preference for one is the preference number two for zero preference number one and here is zero and again here one is maximum preference two and zero preference one and here zero so i hope okay i hope to have filled these matrix uh correctly but uh the gist of this is to go to a person index and put the corresponding preference this is the first step is a matrix so the next step is to create a graph okay we create a graph um with the pairs and uh the weight okay uh so um well a graph for a hash mark maybe is easier to think uh with an ash map so what i have done i have put then um i go through pairs and i put let's go for zero no wait a second so we received these list of pairs right this is the list of pairs that we received and we will transform these in a graph so we go to zero and it would be a weighted graph so zero and uh the pair is um one in the weight what is the weight we go to zero one is three the weight is three next we check one is with zero this is the person this is the match and this is the weight so okay we check then the person zero the person one we know that this couple his match is zero so let's see its weight we go to one we check zero the weight is one then we go to the next pair which is two and three we go to the our weight array we go to the two uh people number two we check the position number three which we check the weight in the weight is 3. now we do the other pair which is 3 and 2. what is the weight of this we go to 3 we check the position 2 and we check that it is weight of 2. so this is the second step perform these mapping these provide us direct access to weight and these providers access to pairs and weights so the third step is to validate okay we will validate if there is a case where the current uh friend the current uh person will ask for a situation where the current person uh is not doesn't have a maximum satisfaction the maximum preference um in another way i do it in there are two situations one situation is we have already our best preference and if we have our best preference like the case of two we are okay we are happy for sure uh the other thing that we will do is to check when we doesn't have the best preference we have to check if there is someone in our list of preferences that is unhappy okay so we have to for if we doesn't have the best match we have to see if there is someone in our preferences that is that would be happier if we were a match understand me so we will traverse this graph and we will check if um there is someone in our list of presences that would be happier with us and also us would be happier with them okay and when that condition applies we found one person unhappy okay so this is the first step this is the second step and the third step is to find uh some one that would be happier with me and i also would be appear okay so this is what we will do in the third step so let's see the code uh to see how this looks like i will jump for the solution and this is the solution okay so first we create the array with positions and weight um okay so this is our weight matrix that i have talked about in these four we will traverse the preferences and do the correct mappings okay for the indexes and the corresponding weights then um i create a graph okay is this second step the second step right here and um in this step uh well i just feel for each friend um for each uh person i put the mat each match and the weight and then uh for the final verification wait sorry for the final verification then for the final verification we will do what i have just told you we will traverse this graph and if the person is with the maximum happiness she could have we continue because that's an epic person if she's not happy what we will do is to go through our preferences and see if there is someone that we would be happier with okay we check in our current person if there is someone uh that would make us happier then the current person that we are had and then we would see if also we would make that person happier than the current person that she is with and if this condition applies we have found another unhappy person and uh that's it uh after this we we just return the number of unhappy people and that's basically how i have solved this problem and uh okay so i will show you how it goes i'm sorry i have to play a little bit with the size of the screen so okay so this was the final uh result okay guys | Count Unhappy Friends | paint-house-iii | You are given a list of `preferences` for `n` friends, where `n` is always **even**.
For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from `0` to `n-1`.
All the friends are divided into pairs. The pairings are given in a list `pairs`, where `pairs[i] = [xi, yi]` denotes `xi` is paired with `yi` and `yi` is paired with `xi`.
However, this pairing may cause some of the friends to be unhappy. A friend `x` is unhappy if `x` is paired with `y` and there exists a friend `u` who is paired with `v` but:
* `x` prefers `u` over `y`, and
* `u` prefers `x` over `v`.
Return _the number of unhappy friends_.
**Example 1:**
**Input:** n = 4, preferences = \[\[1, 2, 3\], \[3, 2, 0\], \[3, 1, 0\], \[1, 2, 0\]\], pairs = \[\[0, 1\], \[2, 3\]\]
**Output:** 2
**Explanation:**
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
**Example 2:**
**Input:** n = 2, preferences = \[\[1\], \[0\]\], pairs = \[\[1, 0\]\]
**Output:** 0
**Explanation:** Both friends 0 and 1 are happy.
**Example 3:**
**Input:** n = 4, preferences = \[\[1, 3, 2\], \[2, 3, 0\], \[1, 3, 0\], \[0, 2, 1\]\], pairs = \[\[1, 3\], \[0, 2\]\]
**Output:** 4
**Constraints:**
* `2 <= n <= 500`
* `n` is even.
* `preferences.length == n`
* `preferences[i].length == n - 1`
* `0 <= preferences[i][j] <= n - 1`
* `preferences[i]` does not contain `i`.
* All values in `preferences[i]` are unique.
* `pairs.length == n/2`
* `pairs[i].length == 2`
* `xi != yi`
* `0 <= xi, yi <= n - 1`
* Each person is contained in **exactly one** pair. | Use Dynamic programming. Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j. | Array,Dynamic Programming | Hard | null |
1,929 | hello everyone so in this video let us talk about a problem from lead code the problem name is concatenation of array so you're given that you are given an array as you can see nums uh in the input and you want to create an array answer of double the length of nums that is 2N and what you want to see is that you want to First nums of I is equal to number 5 for all the first n characters and numbers of I plus n is also numbers of 5 which means that you're just concatenating the same error two times so as you can see that in the input you have one to one now this is how about one two one which means the same array is just concatenated two times just added two times and you have to print that new array okay just doubling out the same array that's it that's the whole problem now how you can do that problem first you have an area let's say n you have to first create one more new array of length 2L okay then what you do you just iterate over this whole string so for the first n characters you will just put answer of I is equal to numbers of I so for the first Cate we just copy it out directly but for the next I plus n characters you will again copy them out but pretty much simple so what you can do is I'll just give you a very small example what you can see is that the array is 213 so you will just make an array of length six one two three four five six okay now what you will do is that for the first three positions you will directly put this but for the next three again you will put two what you can directly do is if this is the integral is 0 1 2 3 4 5 so what you can do is that when you are doing a follow for this particular half till the first n characters you can directly also add them in the next half as well okay which is I plus n okay so this is I ith point then this is I plus n because you have n box to the next because n variations you will filling out using this for Loop now I plus n okay is the again concatenation the new array that you want to concatenate that's it nothing much complicated here as well so what we have done is that we have created a new array of size 2N then just entered over this whole array till from 0 till n now you have to just iterate in the or fill in the new array that is this new Edge that you have made that is a okay now what you will do you will just iterate over the first n characters okay the first n numbers in the area numbers now a of I is equal to number five which will be able to fill the first and get us and a of I plus n is equal to lambs of I again okay these are the just two expressions which I have used here as well okay so this expression is used to fill the next n characters and this is used to fill the first and characters so that I will get two concatenations of the same array in the 2N array and that will just print out or return the total new array which has the same concatenation of the same editable okay that's it that's the overall logic and the good part for this problem as well it's a very simple problem if you still have a doubts you can mention in the comment box for this particular video I will see you in the next recording and bye | Concatenation of Array | maximum-value-at-a-given-index-in-a-bounded-array | Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**).
Specifically, `ans` is the **concatenation** of two `nums` arrays.
Return _the array_ `ans`.
**Example 1:**
**Input:** nums = \[1,2,1\]
**Output:** \[1,2,1,1,2,1\]
**Explanation:** The array ans is formed as follows:
- ans = \[nums\[0\],nums\[1\],nums\[2\],nums\[0\],nums\[1\],nums\[2\]\]
- ans = \[1,2,1,1,2,1\]
**Example 2:**
**Input:** nums = \[1,3,2,1\]
**Output:** \[1,3,2,1,1,3,2,1\]
**Explanation:** The array ans is formed as follows:
- ans = \[nums\[0\],nums\[1\],nums\[2\],nums\[3\],nums\[0\],nums\[1\],nums\[2\],nums\[3\]\]
- ans = \[1,3,2,1,1,3,2,1\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 1000`
* `1 <= nums[i] <= 1000` | What if the problem was instead determining if you could generate a valid array with nums[index] == target? To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum. n is too large to actually generate the array, so you can use the formula 1 + 2 + ... + n = n * (n+1) / 2 to quickly find the sum of nums[0...index] and nums[index...n-1]. Binary search for the target. If it is possible, then move the lower bound up. Otherwise, move the upper bound down. | Binary Search,Greedy | Medium | null |
28 | hello guys myself Amrita welcome back to our Channel techno Siege so this is our lead code Series in which we'll be solving lead code problems one by one I have already discussed some of the problems you can check that out as well so now let's move forward with today's problem so today's problem is question number 28 that is find the index of first occurrence in a string I have already discussed one of the approach for this problem and in this video we'll be discussing one more optimized approach for which time complexity will be o of n so now let's first understand the problem given two strings needle and Haystack return the index of first occurrence of needle in Haystack or minus one if needle is not part of haystack so you can see in the example we have been given two strings one is Haystack and another one is needle so we need to find the first occurrence of needle in Haystack if it exists otherwise we need to return minus one now let's understand stand how we are going to solve this problem so let's take the same example we have two strings one is Haystack which is sad but sad and we have one more string that is needle which is sad so we have to find this particular set in Haystack so we can see here that we have two side here we have to find the first occurrence and we need to return the index so first that starts from the index 0 so that means output would be 0 in this case so to find this we can use the inbuilt function of java that is index of let's first understand how this function works so index of is a inbuilt function in Java which Returns the first occurrence of character or string in another string for example if you have a string hello and you want to find the occurrence of character o in this particular string so the index is as 0 1 2 3 4 so if you want to find the occurrence of o in hello you can directly say let's say this is string s so we can say s dot index of character o so it will return 4 right so this is how index of function Works in this case if I say hey stack dot index of needle then it would return the first occurrence of needle in Haystack so in this case it is 0. and also one more important thing to note index of function if it doesn't find that particular character in the string then it would automatically return -1 and in this problem also we need to -1 and in this problem also we need to -1 and in this problem also we need to return minus 1 so we don't need to put any extra condition here we can just directly use this function if it finds the first occurrence then it will return the index otherwise it will return minus 1. now let's write the solution for it so this is our class that is find index of first occurrence in a string now let's write the method for it that would be public static since it is going to return index so it would be int s t r and it would expect two inputs that would be Haystack and another string that is needle right and then we just have to write our one liner code that would be return Haystack dot index of needle correct now let's go to our main function let's write the print statement let's call the function Str and the inputs that would be Haystack comma needle let's write our inputs as well string Haystack which is sad but sad and another string would be needle that is sad right so this is how we need to solve this problem let's run the program and see the output so we can see here the output is zero because sad exists at the zeroth index now let's test it with some negative input as well let's say we are finding dog which doesn't exist in the haystack so what should it return it should return minus one we can see here the output is minus one let's copy the code and we'll run it in lead code as well let's paste it and run it so you can see here it is accepted and runtime is 0 milliseconds so we can submit the code I hope you understood the solution if you have any questions any doubts please let me know in the comment section please don't forget to like share and subscribe our Channel thank you 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 |
242 | does this problem need another video yeah I think it does there's a lot of confusion around the performance especially the space complexity and I think we should clear that up this is leak code 242 valid anagram so given two strings s and t return true if T is an anagram of s and false otherwise an anagram is a word or phrase formed by rearranging the letters of a different word or phrase typically using all of the letters exactly once so this is silly they don't mean typically so I'm going to delete that so in plain English s and t have to have the same letters the same number of times the example they have is anagram and nagram and it's a little bit hard to see if they have the same Letters by just looking at them now so I'm wondering how can we make this comparison easier so you know what if we did a little bit of organization so I'll group the A's together in s and then I'll try to do the same thing in t so I'll pull out the A's and group them together and let's see what we get now we can examine each column in s and then try to match it against a column in t they all match and SE their anagrams and in this case we have a perfect match for every column but what other situations could occur we need to make sure we account for every possible situation well there could be a different number of A's like this and that would be fine because we'd compare the 3 A's and S against the 2 A's and T and we would see the mismatch but we could also have a case where there are no A's in one of the words so for example if we removed all of the A's from T that would still be fine because when we examine the a column and S we would compare it against nothing and we would notice the difference but what if we had the case where there are no A's in s then if we only iterate over these four columns we'll get matches for all of them but we won't even notice that there's this entire a column that we haven't accounted for so how do we address this missing column issue the obvious fix would be to just iterate over all the columns in s and all the columns in T and would work because yeah we wouldn't notice anything is wrong when iterating over s but when we go and iterate over T we will notice the issue but is there anything else we could do I'm noticing that in this case T has an extra column that isn't an S so we could just count the number of columns and compare four versus 5 and that would work but if I step back and think about what it really means for t to have an extra column in this specific example it means that t has letters that s doesn't and so we could also identify this issue by checking if s and t have the same string length and an added benefit is that we could do this check right at the beginning before we even organize the letters into columns but how can we represent this in code well in each column there are two key pieces of information the letter and a count so for this column you have a and you have three because we have three A's and in code we could represent these pairs with a map where the key is the letter and the value is the count let's turn this idea into code so I'll start by commenting this out and then we can use it as a guide for our function and right away we can check the lengths and if they don't match we return false then we initialize the two maps for s and t T and we build up the maps with letters and their counts we can go through them at the same time because we know they'll be exactly the same length if the e letter isn't in the map already We'll add it for the first time and if it's there we'll increment then for each column in SM map we'll try to match it against a column in t-map and if we can't we return false t-map and if we can't we return false t-map and if we can't we return false remember we don't have to worry about the missing column issue because we have the string length check up at the top and if we don't find any mismatches then we can return true at the end for our time complexity we iterate over both strings to build our two maps then we iterate over one of the maps this gives us o of S Plus T time and I think most people would be satisfied with this analysis but if you pay really close attention you'll notice something interesting at the very beginning we have this string length check and so we only create s map and tmap if s and t are the same length that means when we look at o of S Plus T if s and t are the same length then this would be the same as o of s+ s which simplifies to O of s as o of s+ s which simplifies to O of s as o of s+ s which simplifies to O of s so you could also Express the time complexity this way for space it's temped to say ofs plus t or ofs for the same reasons I just described that's because we're building two maps whose contents will depend on the two strings but this isn't quite right and it's frustrating that many videos about this problem make this mistake if we pay attention to the problem's constraints we see that the strings are guaranteed to contain only lowercase English letters this means that at most each map will have just 26 keys because there are only 26 lowercase English letters so our Maps would take o of one space because we have to look at every letter in the input we can't do better than o of s time and O of one space is as good as it gets to before we move on to an entirely different approach I want to talk about a popular Twist on this map strategy that does allow you to use one map instead of two but it's not as good as people think it is it's based on the Insight that two anagrams should perfectly cancel each other out for example if you have rat and tar the RS cancel each other out the A's cancel each other out and the t's do two and you're left with nothing let's see how this looks in code if the lengths are different there's no way they can be anagrams so we return false then we initialize one map for S this will be the only map we use and we build it up with letters and counts next we try to use the letters in t to cancel out the letters in s so for each letter in t if the letter is an S we subtract and if it's not there at all we can immediately return false then we check if everything has been cancelled and we'll know if all the values in SM map have been zeroed out so if we see a nonzero value we can return false and if we get to the very end that means everything was zeroed out so we return true it's true that this will use one map instead of two but remember that each map can only have up to 26 key value pairs so we're talking about 26 versus 52 at the most if you have two maps either way both will simplify to O of1 memory all the same but then people will say but what if you removed the constraint of only lowercase English letters and allowed the maps to have an unlimited number of keys well it still doesn't matter for bigon notation if you have one map you could have up to S Keys which would be ofs space and if you had two maps you could have up to two s Keys which would also simplify to ofs space so using one map is only slightly better and not in a way that matters for Big O notation all right we've talked a lot about map approaches but are there any other reasonable Solutions maybe there's something simpler our first approach took S&T and rearranged them in the same took S&T and rearranged them in the same took S&T and rearranged them in the same way using a map and then we checked to see if the rearrangements were the same so I'm wondering is there a different way we could do the rearranging and if I think about this for a little bit the idea of sorting comes to mind if I take s and t and sort them in the same way and get the same result then I know they must be anagrams let's turn this sorting idea into code if the lengths are different there's no way they can be anagrams so we return right away and then we want to sort S&T but in then we want to sort S&T but in then we want to sort S&T but in JavaScript there's no way to sort a string directly because they're immutable so we have to do a few things first we split both strings into arrays of letters and then we sort these new arrays instead and then we can join the sort arrays back into Strings finally we can check to see if they're the same okay so this approach definitely feels simpler which is good but what about the performance we have a bunch of linear operations so splitting strings into arrays converting the arrays back into Strings and then comparing them at the end but the most expensive part will be the sort which will take o of s log s time since the strings will be the same length so slightly slower than the previous o s time approaches now for space creating entirely new arrays takes o of S Plus t space sorting those arrays takes o of one space assuming Heap Sort joining the arrays back into new strings will take o of S Plus t space because we're creating two new strings and then comparing them at the end doesn't take any additional space so overall this takes o of s plus t space which can be simplified to O of s since s and t will be the same length this is a lot worse than the previous approaches which only took of one space a lot of people think this solution takes o one space but this isn't quite right and misses the full picture the main argument is that Heap Sort takes o one space but that's not true if you're dealing with immutable strings and all of the most popular interviews languages python JavaScript Java all have immutable strings that's why we had to copy the letters into new arrays which takes extra space and then we had to sort the arrays instead of the original strings so let's rephrase this shaky claim into something that's fully true this sorting approach takes o of one space but only if you're using a language that has mutable strings I'd be totally fine with this but no it's a much weaker claim than many people are making the second bad argument I've seen concedes that the Sorting approach might take o ofs space because of immutable strings but the argument is that the function definition could be changed to take arrays instead of strings in which case it would take o of one space in every language absolutely true but we have a very explicit function definition from leak code and we shouldn't argue a make Bel situation that doesn't exist imagine in a courtroom a defendant stands up and says yes I stole the car but what if I didn't so after all of this analysis which approach is better well it depends the Sorting approach is always slower and in most languages we'll use more space too so if you care about performance one of the map approaches will be your best shot if you care more about Simplicity and Clarity there's a good aru arent to go with the Sorting approach but you'll lose a little performance now if you go back to the beginning our line of reasoning started with examining anagram and nagam and asking how can we make this comparison easier then we organized the letters into columns where we only saw perfect matches so we asked what other situations could occur and so on which ultimately yielded two map strategies and a sorting approach what's most interesting thing about this problem though is how easy it is to get the space complexity wrong twice in two different directions it's really easy to end up in opposite land and that's exactly the Trap that a lot of people fall into if you're not careful you can mislead yourself into thinking sorting is the space efficient Choice when the opposite is true | Valid Anagram | valid-anagram | Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "anagram", t = "nagaram"
**Output:** true
**Example 2:**
**Input:** s = "rat", t = "car"
**Output:** false
**Constraints:**
* `1 <= s.length, t.length <= 5 * 104`
* `s` and `t` consist of lowercase English letters.
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case? | null | Hash Table,String,Sorting | Easy | 49,266,438 |
1,903 | hey everyone today we are going to solve decod problem number 1 1903 largest or number in a string so in this problem statement we are given a string num representing a very large integer and we have to return the largest value or integer as a string that is non empty substring of num or if we are not able to form that odd number we are going to return empty string so let's say for an example 41 2 6 0 1 if we have to return this is an string given to us and we have to return a subring of it which is OD and have the largest value so to make a string sub string largest we have to include more number of digits so we are going to start from right we will check whether one is OD or even one is OD because module of 1 by module of 2 is equal to 1 it means it is or if we if for any digit the model of 2 is equal to equal to0 that is OD that is even so one is odd if we include one in our substring so all of these substring are going to be OD and we have to capture the largest value so we are going to include all of the car all of these characters here 60 1 is also 2 6 0 1 is also OD 1 12601 is also OD and what is the largest value 412 601 this is the largest OD value or maybe largest OD substring let's take for an for another example 52 two is even so we cannot include two in our answer maybe we cannot take two as a rightmost digit in our answer let's check for five we can take as our answer because 5 mod 2 is equal to 1 let's take another example 4 2 02 it means 2 is even 0 is even 2 is even four is also even it means we cannot get any substring so in this in that case we are going to return empty substring we are also given that there is not tailing like leading zeros so nothing to worry about we are going to it like we are going to iterate from uh right till left extreme and we will capture for any OD desert so for that like uh we are going toate over given string from right to left whenever we get any OD value so let's say I equal to 3 I = 2 for I = to 2 we got any odd to 3 I = 2 for I = to 2 we got any odd to 3 I = 2 for I = to 2 we got any odd desert so in this way in this case we are going to take substring from starting to that index so 1 2 3 is going to be our largest OD value maybe largest or integer okay let's quickly code this here we have to get the largest substring which is OD from this given string which is num so let's first capture the length of this num do and now we will iterate from right to left int I equal to n - 1 I greater than left int I equal to n - 1 I greater than left int I equal to n - 1 I greater than equal to 0 i-- if we don't find any answer we are i-- if we don't find any answer we are i-- if we don't find any answer we are going to return empty string now we'll check for the character equal to num do character at I now we have to find the digit from that character CH minus 0 now we got the digit whether this digit is OD or even if it is odd that is mod with 2 is equal toal to 1 it means we found our answer and we can directly return num dot substring 0 to I + 1 because we num dot substring 0 to I + 1 because we num dot substring 0 to I + 1 because we have to include I that's why we have to pass I + 1 check for the sample test cases it is passed submitting the problem It Go submitted okay hope you understood the problem thank you guys | Largest Odd Number in String | design-most-recently-used-queue | You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** num = "52 "
**Output:** "5 "
**Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number.
**Example 2:**
**Input:** num = "4206 "
**Output:** " "
**Explanation:** There are no odd numbers in "4206 ".
**Example 3:**
**Input:** num = "35427 "
**Output:** "35427 "
**Explanation:** "35427 " is already an odd number.
**Constraints:**
* `1 <= num.length <= 105`
* `num` only consists of digits and does not contain any leading zeros. | You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end. | Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set | Medium | 146 |
307 | uh today we're gonna be working on lead code question number three zero seven uh range some query mutable uh given an integer array nums handle multiple queries of the following types so we're going to be update we're going to be updating uh the value of an element in nums and calculate the sum of the elements of nums between indices left and right in closer so we have done a very similar question not really similar very similar question but we have done a question where they were where things were immutable weren't changing and we didn't have to do any update and we were able to uh actually uh implement an algorithm where the sum range was of one as we were taking off and time in order to update them in order to initialize the array but this time uh we're gonna be making use of so let's read it first so basically it initializes the object with the integer array nums and the update updates the value of uh of in nums of index to be value and the sum range is just gonna return the sum of the element of nouns between the indices left and right and closer okay this is uh like a typical example or the perfect uh like use case of the segment renault and we're going to be using segment tree node and the reason for that is like that the segment tree node is allows us to be able to implement this sum range and update what both of them in log of n because it's going to be a tree node it's a little bit different we instead of like having the just the binary tree node left and right nodes we're gonna save uh the information about the sum of the uh all the nodes on the left side and all the nodes on the right side and then the start and the end these are the uh these are the few information we're going to keep in the segment no tree node okay uh we're gonna initialize we're going to define our uh segmentary node first so the segment tree node has in start and then it has a few nodes called segmentary node uh left and right and then we have the and the last thing we have is the sum okay the way the constructor is gonna work is the segment tree node takes two things which is the start and end n and then this start is gonna become equal to start just start and we'll become n okay and we're gonna set both left and right to none this dot left equals to null this dot right equals to null and we're going to set the sum equals to zero nice okay and also we are going to say that the root segment is also so that the root is accessible by all the functions so we're going to call it segmentary node root which we're going to initialize to okay nice so the first thing we're going to do is uh when we are initializing it in the nums uh num array we're gonna say that we're gonna change the route and the route is gonna be changed and we're gonna call a helper function build uh tree where basically we're going to be sending him the nums and the starting index and the ending index so the starting index is going to be 0 and the ending index is going to be the num start length minus 1. okay now we have to implement this uh function which returns a segment tree node it's called build tree it takes uh and nums it takes an index starting index and an ending index okay how we're gonna be building a tree is array by recurring right and there are two things here first of all there is a sanity check you can say that if the sanity check or like the base case to where the start becomes greater than end if that is the case we're just gonna return i will say it's kind of a base case now because start will become end a lot of bigger than end and we're gonna keep returning the nulls okay else if that is not the case right then first of all we want to create the uh we want to create the return segment tree node which is basically a new segment tree node it takes nums okay uh sorry because the segmentry node just needs a start and then so we created a new one but uh so we created a new one now we want to do two things one is that the start becomes equal to n if that is the case right we also look at that one so because the leaf nodes of this tree are always going to be individual elements where the value where the sum is actually equal to the value of that uh nums at that particular index so it's not going to be sum of two nodes it's just gonna be the that value so for that we're going to say that the return dot sum equals to nums and start this is going to be mostly the leaf nodes else if that is not the case we're gonna calculate the midpoint we are worried about the overflow so we're gonna say start plus n minus r divided by 2 just over the overflow okay now the return is gonna have a left node right uh for that we're going to call recursively called this uh build tree with the nums and with the start and it will end at mid similarly we're gonna call that we're gonna calculate the right node where it's gonna be beltry uh the nums and the mid plus one and then the n so we have the left and then on the right once we are will come out of this else right we can just return whether if or whether else we can just return the that node okay that should be it for the initialization now we're going to be implementing our update and some range functions updaters we're going to be using a helper function with a different uh like in the definition type of the root we're going to be calling the same update but this time the arguments are going to be root and then uh index and then the value so this function is going to be again returning a void update but it is it takes a segment tree node root and then the end position and then end value oops okay so now for this one yes we are trying to update it right so basically what if the where the root is uh the start and the end is exactly the same if the root dot star is equal to root dot n that means we just wanna say that the root dot sum is equal to the new value else again now we need to make we need to first of all we need to know are we going to the left side or to the right side for that we're going to calculate the middle point uh that is gonna be equal to root dot star plus root dot n minus root dot star divided by two okay so we found the midpoint now if the mid uh if the mid if that position like the index he is talking about is less than if that position is less than equal to mid let me just do this okay if that is equal to that then we're gonna uh up call this function root dot left because we're going to the left side and then the position and the value else we're gonna go to the right side update root dot right same position same value right and once we come out of there we're just gonna say that the root dot sum is basically equal to root dot left dot sum plus root dot right dot sum and that should do it a very similar approach is gonna be here for the sum range uh we are gonna be using a helper function uh the same name but different arguments some range that's called root left right and we're gonna huh we are going to but this time okay let's just call it because we are gonna returning the value uh that would be okay so we are returning an end here and some range segment three node root and left and right or let's just call it star and n okay so what we're going to do is first of all we want to check that if our if the root dot n is equal to n and the root dot start is equal to star if that is the case we're just gonna return the root dot sum that's what we're looking for right some from the starting and the start from the index start to the index n okay so the root dot sum if that is not the case again we either need to go to the right or to the left for that we're going to be calculating the midpoint which is going to be equal to uh root dot start plus root dot and root dot okay so we can clear to the midpoint if the end is less than equal to again the midpoint now we're going to say that the return some range is the root dot left and then the start and the end so the start and the end stays the same the only thing is that we are going to the left side of it again else so sorry we have we need to say that the else f is equal to start is less than equal to mid plus one now there is the case we're going to be we're gonna be going to the we're gonna going to the right side return some range root dot right and then the start and the end and lastly if that is not the case like if so if the end is less than equal to uh like if n is less than equal to mid we're going to the left side right if uh the start is greater than equal to uh mid plus one we are going to the right side but if we have like uh have so that was like we were out of range on one side that's why we just completely went to the other side but now the left side if we if that is not the case right then we have to actually explore both of them so all we have to do is to return some range root dot right and then mid plus one and then the end plus now we're gonna go to the left side to some range root dot left and then this time it's gonna be start and then go to the mid okay let's see how it does okay there is over here root does not rig htrig hd now it is just not working right now okay we gotta figure this out okay let's see all the conditions here so when we are initializing and then the build tree is gonna say that uh when the start is greater than and we are sending the null and the segment tree is one more time what was the error so yeah even before that even before we updated it through an error so let's just look at the build tree first so we are the condition is the start is equal to n and then we are returning the star and then this is good uh okay over here one thing which i noticed is like we are not updating that so the return dot left dot sum plus return dot right dot sum ah just like we did it over here one thing is that we missed that let's see how it does for the other test cases yep and it works | Range Sum Query - Mutable | range-sum-query-mutable | Given an integer array `nums`, handle multiple queries of the following types:
1. **Update** the value of an element in `nums`.
2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`.
Implement the `NumArray` class:
* `NumArray(int[] nums)` Initializes the object with the integer array `nums`.
* `void update(int index, int val)` **Updates** the value of `nums[index]` to be `val`.
* `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`).
**Example 1:**
**Input**
\[ "NumArray ", "sumRange ", "update ", "sumRange "\]
\[\[\[1, 3, 5\]\], \[0, 2\], \[1, 2\], \[0, 2\]\]
**Output**
\[null, 9, null, 8\]
**Explanation**
NumArray numArray = new NumArray(\[1, 3, 5\]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = \[1, 2, 5\]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-100 <= nums[i] <= 100`
* `0 <= index < nums.length`
* `-100 <= val <= 100`
* `0 <= left <= right < nums.length`
* At most `3 * 104` calls will be made to `update` and `sumRange`. | null | Array,Design,Binary Indexed Tree,Segment Tree | Medium | 303,308 |
937 | hi guys welcome to the channel if you are new to the channel please consider subscribing because we sold a lot of into the questions here and that can definitely help you with your interview so let's start with the question says do you have an array of logs each log is space delimited string of words for each lobe the first word in each loop is an alphanumeric identifier then either each word after the identifier will consist only of lowercase letters or only of digits we will call these two varieties of logs letter logs and days it looks it is guaranteed that each look has at least one word after its identifier so we need to reorder the logs so that all the letter lobes come before any daily floats and the letter looks are ordered lecture graphically ignoring the identifier means alphabetically and with the identifier in the case of types the digit logs should be put in their original order and we need to return the final order of the logs I have taken the example which was given in the question and I have marked all the letter loads with red and all the digit looks with a green and if I take two arrays and in the array one I'll keep all the digit logs and in the era two if I will keep all the letter logs after splitting the digit logs and the error logs our arrays will look like this so if you see it very clearly it was mentioned in the question that we need not to do anything with the digit lows but in the case of latter law we need to return the latter low in the lexicographical order so if we see it very clearly art come before on but there is a tie between art so it was clearly mentioned in the question whenever they will gonna be a tie we will go to consider the identifiers so in this way our answer will look like latter one art can because letter won't come before the letter three then letter three because once we are done with the type our Friday will based on the letter logs note on the identifier and at the last will come the letter - once we are last will come the letter - once we are last will come the letter - once we are done with the sorting of letter logs we will combine both letter low and digit log and we will written them in the form of a string let me repeat it what we're gonna do we will take two arrays in one we will store the letter logs and in the second we will store the digit low we will sort the letter low on the basis of lexicographical order and we will combine both letter low and that is it look and we will written it in the form of a string let us write the code for this let's make two mtra plus one and rest two to store our letter log chant is it looks for login Long's we will use plate and H digit to identify our digit logs so if log to split at index one is teach it we will want to append it to re s2 else we will append it to re s1 we will split now we will sort first on the basis of our identifies and we will use lambda for sorting and now we will sort our little dogs to convert the list back to the string we will you join and we will use extent to combine our es 1 and our es 2 at the end we will return our es 1 if we will gonna copy and paste this code on the lead code it will work you can find the code in the description below if you liked the video please give it a thumbs up thank you so much for watching the video please don't forget to subscribe | Reorder Data in Log Files | online-stock-span | You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**.
There are two types of logs:
* **Letter-logs**: All words (except the identifier) consist of lowercase English letters.
* **Digit-logs**: All words (except the identifier) consist of digits.
Reorder these logs so that:
1. The **letter-logs** come before all **digit-logs**.
2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
3. The **digit-logs** maintain their relative ordering.
Return _the final order of the logs_.
**Example 1:**
**Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\]
**Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\]
**Explanation:**
The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ".
The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ".
**Example 2:**
**Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\]
**Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\]
**Constraints:**
* `1 <= logs.length <= 100`
* `3 <= logs[i].length <= 100`
* All the tokens of `logs[i]` are separated by a **single** space.
* `logs[i]` is guaranteed to have an identifier and at least one word after the identifier. | null | Stack,Design,Monotonic Stack,Data Stream | Medium | 739 |
208 | in this video we're going to take a look at a data structure called tri so try is a data type of enary tree so unlike binary tree where each node can maximally have two nodes energy can have multiple children right so we used to try to store strains and each trinode represents a string so and each node in the tribe we can have multiple children right we can have multiple children nodes so the root node is always empty and that's why you can see here with this our try and the root note is here and is empty it basically stores the chosen nodes and we use try to basically have a various applications such as autocomplete right where user input is character and they have a bunch of options for user to also complete the string that they're typing and where we can check the spelling right to see if this character is correct uh based on the dictionary the current dictionary that we have and then in this case we can see here that we have a try and we can be able to use this tri-data and we can be able to use this tri-data and we can be able to use this tri-data structure to do that to store the string you can see we have a string which is bad and each node is a store as a character and if we were to find b.a.d and if we were to find b.a.d and if we were to find b.a.d in this case what we can do is we can start at the root note and we check to see if root has a children of b in this case we do then we're going to continue to see if b has a children of a because we have a strain that we want to search particularly right we want to search for bad so in this case b has a children child node of a so then we check to see if a has a children of d and in this case a has a children of d so we know that bad exists so we can return the string to have that as an option for user to auto complete it right so that would be a perfect data structure to use so there are many ways we can define try so one way is we can use an array because let's say we're only dealing with like lowercase letters or uppercase letters we can define the size of this theory right so let's say we're dealing with uppercase letters we can have in set to 26 so that basically every time we insert a character we can have the current characters minus the lowercase a right or if we're dealing with lowercase a then we can be able to insert the trinode onto the current knows the trinomials children right and notice that the root node is always empty so we're basically dealing with the trojan nodes we're not storing the current nodes value onto the current node we're basically storing its chosen nodes so the node that we want to insert let's say is b then in this case we can just uh basically find that position in the array and we see if it exists if it doesn't exist we insert it and then we're going to look for the nest character in this case a and we check to see if exists if it doesn't exist we insert it right for these children right so we continue to do that right so in this case that's one way and the other way we can do is we can use a table so to use a table it's going to be the time complexity is going to be a lot slower compared to using array but this we can use table or a hash table or hash map to save us a lot of space because we don't if we have a situation we don't know how many characters we're playing with or we don't know if we're only dealing with lowercase letters or uppercase letters or just all characters right so then we can use a hash map to do that and this hash map basically uh same thing we can have a character and we have a try note for each and every single character right so if we have only if the current the root note only has three children then we only need those three elements in the hash map right so we're not adding extra space compared to using array so there are basically um two methods for try right one is to insert the string and the other one is to look for the string right and there could be more than there could be other methods but those are the two main methods right so if we were to insert a string in to the try first we want to make sure we initialize the current root right so the root is empty it has the empty uh has array or uh or a table of children and basically we're going to do is we're going to um iterate each and every certain character that we want to insert so let's say we want to insert bab then we're going to do is we're going to see if current character right if the current root has a child node of c we want to see if this character is already a child node if it's not then we're just going to initialize it and then we're going to do just like how we did in dfs right we're going to get current is equal to current.child equal to current.child equal to current.child uh chosen at c so that we can move on to the next character and then we're going to see if the next character exists in the current dot chosen right so we're going to continue this process so at the end what we're going to do is we're going to iterate each and every single characters that we have in s again is the strain that we want to insert also try so once we iterate each and every zone characters in s we know that we insert the string onto uh into the tri data structure then we can do is basically current is the last character of the string right or represents the note that represents the string s so another method um that we going to talk about is search so let's say we want to search a string let's say we want to search bab so same thing we first initialize the current root and we basically check to see right we're going to iterate each and every single characters in string s and if current node right does not have a child node of c that means that this string doesn't exist so we can just return false or return fail right and then to continue to traverse down the path we can just get current as you could current.children as you could current.children as you could current.children as c because here all we're doing here is we try to traverse each and every single character to see that string exists so at the end if we were to be able to traverse the entire string we can just return true so what we're going to do now is we're going to do a legal problem called implementing try so prefix tree right so what we're going to do is we're going to design this data structure and it supports three methods right so in this case we are trying to complete the insert part where we can be able to take a string and it inserts it into the string into the tri and we also want to be able to support a method uh be able to search the string if it exists and notice it says that if the string were is in the try was inserted before and false otherwise so a word basically means that if let's say we have a uh a word right let's say we want to insert apple we want to make sure that we be able to after we insert it we want to make sure people search it and be able to see if this word exists if we return true if it exists return false if it doesn't right and we also have this starts with so with it takes the prefix and return true if the previous uhly inserted string word that has a prefix right return false otherwise so return false so we cannot find this prefix and you can see we have a couple examples and i think it's very important to know that um and basically let's say we are the first you can see we're basically initialized let's try we're trying to insert this apple right and we want to search the apple we in this case it exists right but the thing here the catch is that if we want to insert if we want to search for app in this case it will return false right this is the real answer is that we don't have this word but the thing is that if we were to use the data structure that we just saw right it's not going to work because what we need to do is we need to change something we need to make sure that string that we search in this case is actually a word right if it's not a word like for example if we have a tree like this right we know this is a this is p and this is l for example right so we have a p l or e or blah and so on right so in this case um if we were to search app then in this case we know this is equal to the first character this is equal to the second character and this equal to second character and it might just return true because we know that we just traverse all this all the characters that we have in string but the thing is that we want to make sure that when we insert the uh a word we want to make sure the last character is actually represents the word right we want we can we're going to have a property that represents a word so that if this is the last character in the string we want to make sure this is a this is actually a word if this is a word then when we search the string it will return true if this is not a word and this is the last character then in this case we're going to return false and i'm going to show you at the end and then in this case we also going to have a situation where we have to start with right we want to make sure we have a string that start with app we want to insert it and we can be able to search it right so in this case we're going to have that property is word which check to see if it is a word if it is uh if in this case it doesn't really matter just to see if it start with this string but for search want to make sure that if it has if the last character is a word if it is word we can return true if it's not we're going to return false so let's take a look at how we can implement this so to do this we're going to design a class called trinode and this tri node basically has two properties so we're gonna have hashmap and the key is gonna be the character right and we're also gonna have a uh a value which is gonna be a node so we're going to call it children which is equal to hashmap and we're also going to have a property called is word to check to see if the current trinode is a word by default it's going to be false so inside our solution class right try solution class we're going to have a private property called root and we're going to define that in deconstructor so we're going to have root initially is equal to new trinode so we're going to create an instance of this trinode and so far we have no children at all so we're going to do is we're going to insert node so to insert a node we're basically going to have a current node so we're going to have a try node current is equal to uh the root so what we're going to do is we're going to convert the string into a character array and basically the idea is we're going to iterate each and every single character in the word and then we're also going to traverse that in our current uh prefix tree right or our current try so we're going to say array is equal to word.2 character array and basically word.2 character array and basically word.2 character array and basically we're going to traverse each and every single character in the array so current character inside the array and for each character that we have in the array or basically check to see if the current node so if the current node dot children right that contains key if it contains this current character is equal to false if it doesn't contains this character then we want to make sure we uh create an instance of it we want to insert a node right so in this case what we're going to do is we're going to say currentnode.chosen is we're going to say currentnode.chosen is we're going to say currentnode.chosen dot put right so for a current character we're going to create a instance of the try node and then we're going to do is once we create the instance right it doesn't matter if it contains or doesn't contain after here after this if condition we're going to do is we're going to set the current node it's equal to current node dot children dot get current character right we're basically traversing its children right it's current characters knows children and at the end what we're going to do is once we ins successfully insert each generation character that we have in the word onto the try we're going to set the last character so the current node which is points the last character we're going to set it is word is equal to true okay and we're gonna do is we're gonna search right so for searching is same thing what we're gonna do is we're gonna have our tri node current node is equal root we're gonna iterate each and every single character and for each character that we iterate we check to see if the uh if the current node that children contains this current character if it doesn't then what we can do is we can just return false and at the end if we were to traverse each and every single characters that we have in the word then what we're going to do is we're going to return true if so if this current character is a word right if it's not we're just going to return false right so that's how we're going to search the string to see if there is a word in the tribe and then for search for star wars to see if it has a prefix right so what we're going to do is we're going to do the same thing but in this case we don't have to worry about if the current node is a word so like we can we don't have to worry about if the current is a word or not a word as long as that contains it as long as it contains this uh this prefix then it's true right so now let's try to run our code and you can see we have a boolean that's why okay so we have to add a boolean here and root is going to be a type tri node cannot find this symbol 41. okay so this is going to be a prefix right so because we're iterating all the characters that we have in the prefix okay so let's try with so now let's try to submit and you can see here we have our success so time complexity again is going to be big o of n where n is number of characters that we have that we want to insert or that we want to search | 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 |
106 | So hi gas, we came to this question, we started the series of tree, then inside it we came to construct binary tree on this question, from these order and post order driver, there is basically nothing in the question, what life do we have in the question? This is life that we have been given an order driver cell and we have been given a post order driver. Okay, and what we have to do is we have to construct a binary from it. Okay, so if we look at these orders in this tree, then this ordering What will be the driver cell? What happens in this order? First, what will come on the left, then print yourself, then what will come on the right, your own Okay, so what will come on the left, your left will come, seven will be okay and we will give in the tree of rights, we will give ourselves. We will print right, so first our left sub tree will be completely printed, then the right sub tree will be printed separately, then we ourselves will be printed, so what else will come next, our root note will come and before that our two prints will have been done which is Android, first of all we will get the root right. We will not be able to identify where it is because the root note is on the middle, there is power on the right part too, there is power on the left part too. Okay, so here we will not be able to see where our root note is. So we come to post order, what is the interesting thing inside the post order driver cell that on the left, the tree is printed, on the right sub tree is printed, then I is printed, which means in the post order, the root at the end is no different. Okay, so this is the point, so we have got the best one. Okay, we have come to know that at the end of ours, the root note is going to be printed, which we are getting to understand, so this is the part that we have donated first. What is our problem, we have to extract the root node, we have to extract its painter, okay now what will we do, we went inside this order traversal, we have identified that this is ours but now in the post order, we have to tell which one is separated from left to right. We don't know where is the right, but right now we can see that 9 of us are making all the tricks and 55 are making 720. Okay, but now we will see one more thing, now what will we understand, now we come inside these order journeys. How can we identify in the order driver cell, we must have got this root note, okay index of D mid basically D root note in D in order, so we know that there are so many, okay so this is what we have to identify. What is the third step for us? We have seen how much we have read on the left and right. Now we come to post order travels sale because what we saw in the first step is what we started with in the first step, that is post order. It was done through traversal only because its only other element is what is going to be ours, the root is going to be the nodal right, so now we will see basically now, if we know this much, let me explain a little what is there in these order driver cells. Basically, if you reference this, people, right now we are taking reference to three, right then three this note nine will be in your right sub tree and you have to see the other thing 15 17 20 whatever will be yours 15 17 is okay 157 and 20 that much element. If you find it, you will get the elements of the tree from the right. Okay, basically you have to mine from the post order ending to the post order ending, so many elements, okay, let's take a quick look sometime, okay D. Laptop after meaning which is D. Stuff basically after defining D. Range of D in order and post order driver is an important question because nothing has to be done because it is very easy if you see the painter, it is very easy in the order driver sale, I repeat to us again, these order drivers do our element which What happens is that what is printed in our else, we ourselves are printed, the root is printed, how many elements are there on the left and how many on the right. If we find the elements with the help of trick, then we write it again, then when we code, we maintain 2 points. We will start these orders, okay yes, okay, after this you will see it will become zero, so because we are starting the lifting inside the post order, then our return is to start forint i = in and one more thing here because its scope Here it is defined, so you make zero and break, we got our index, so what to do in return and first let's create it, everything is fine, we have to right inside the root, inside the right of the root, I plus one, what about us? It will be done. If we have to construct something, then our search is done within all of us, so what will be our order from I Plus One till where it is done till these and others. Okay, this is the post and basically what will be the number of elements. Which of yours are going to be inside this inside you because first inside the post order, left is printed, then right is printed, then I myself is printed and if this is my left sub tree, sorry, if this is the right sub tree, then this is the right sub tree. And what would be the index in 20 and I what would that be that would have been printed itself so what would that be right basically so here put post and minus one put its ion start what would be its post and what would be right sub trick elements - Will read to do mines one, why are you doing that stand, so do mines here, ok, it's done I have made three mines out of 1804, ok, so child, out of one, now I have to deliver one more mine to the no. I will do it only then I will reach here. Simple Click What is it? Here I will show you what are the steps. What are the steps? Pick the last element of the root note before the post order. What will that be yours? There will be root element, after that do research and after that first you have to find these order driver inside the cell because you have to number because you know post and dress up, you cannot construct tree, so for that you and we have given reference point post. You have taken the order from the driver. Okay, so for that you have to mine the number of elements in the right sub-tree of the inverter tower cell you have to mine the number of elements in the right sub-tree of the inverter tower cell that you have got on that element of the order's journey. Basically, you will read from the last element of the post order, which is the index of the root element, then you will get the elements of the right sub-trick and if get the elements of the right sub-trick and if get the elements of the right sub-trick and if you want to reach the root index A of the tree from the left, then you will have to do -1, which then you will have to do -1, which then you will have to do -1, which we have done here. But I have given a summary explanation, you will get the solution, okay, and it will be based on very AG questions, but what will you do inside it, okay, we will construct from it. | Construct Binary Tree from Inorder and Postorder Traversal | construct-binary-tree-from-inorder-and-postorder-traversal | Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** inorder = \[9,3,15,20,7\], postorder = \[9,15,7,20,3\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** inorder = \[-1\], postorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= inorder.length <= 3000`
* `postorder.length == inorder.length`
* `-3000 <= inorder[i], postorder[i] <= 3000`
* `inorder` and `postorder` consist of **unique** values.
* Each value of `postorder` also appears in `inorder`.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
* `postorder` is **guaranteed** to be the postorder traversal of the tree. | null | Array,Hash Table,Divide and Conquer,Tree,Binary Tree | Medium | 105 |
1,513 | Hello hello everybody welcome to my channel it's all the problem numbers of serving with only one show consisting of 400 number of birth all characters vansh or answer me to do the power plus 76 example2 90 can for subscription form example subscribe number 520 can form number one One one can we number 212 subscribe number of wave raw agent he then they can form with 2131 total cand Delhi one of the oldest there is not possible for total no subscribe form with that in the very year in software for doing so such is let's take Another Example Which I Like This I Net Se All Six One Share Bhi Have Spring Dushwar String Hai Na Ho Easy K Encounter The First Vansh How Many Serving Bihar 225 With String Of Link 17018 Flying Dress Left Side Is Length Serving Account Is Decided That Nowhere In The second one so what is the president is considered as one so how many serving this one can provide we subscribe now to the third one will provide candy Three plus one and so total dhavans contribution his first one in the 2nd 3rd and 4th and 5th and listen to play list 2 f become form with 6 family tree so let's take another example you have we roman we well as head as one will contribute In The Second One Plus 2 And Plus 3 Nov Encounters-01 Feb 08 2014 Plus 3 Nov Encounters-01 Feb 08 2014 Plus 3 Nov Encounters-01 Feb 08 2014 Subscribe Now Hair With Reddish Account Difficulty Which Were Initially The Pimples Don't Forget To Subscribe Dr Will Again Will Be The Result Will Result In A Plus Account And Answer Can Were So They Will Take Them With Jut And Power Plus 7 Subscribe Code For Code Know Which Hair Vinida Result Variable Sholay Tent Result Beach Zinc 1600 Account They River Which Is Came From 0 And Vinegar Mode Variable Which Is The Power So They Can Write 079 Vidron In More Loop Plus App That I Plus Know Who Will Check The Character Of Account It Is Equal To This Character Correct Servi Current You Is Equal To One Effective Way Simply Subscribe Plus One Adheen Result Will Result In Every Time They Get Back With Sudhir And Total Number of subscribe to check weather it's working so it's working for the one taste lab technician subscribe ka disrespect like delay no one saw the dishes 600 only 2 serving for this task force which can only for 100 200 why translate time and code the city has Accepted Election What is the Time Complexity and Space Complexity of Time Complexity Bears Running for Loop for all the characters like for full length of the stringer Swadesh Laut Se Strength of String in the Complexity of Observation and Space Complexities Subscribe Like please do subscribe my channel Like this thank you for watching | Number of Substrings With Only 1s | find-all-good-strings | Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** s = "0110111 "
**Output:** 9
**Explanation:** There are 9 substring in total with only 1's characters.
"1 " -> 5 times.
"11 " -> 3 times.
"111 " -> 1 time.
**Example 2:**
**Input:** s = "101 "
**Output:** 2
**Explanation:** Substring "1 " is shown 2 times in s.
**Example 3:**
**Input:** s = "111111 "
**Output:** 21
**Explanation:** Each substring contains only 1's characters.
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`. | Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size "pos" where the maximum common suffix with string "evil" has size "posEvil". When "equalToS1" is "true", the current valid string is equal to "S1" otherwise it is greater. In a similar way when equalToS2 is "true" the current valid string is equal to "S2" otherwise it is smaller. To update the maximum common suffix with string "evil" use KMP preprocessing. | String,Dynamic Programming,String Matching | Hard | null |
279 | hello everyone let's start today's lead code problem perfect squares we are given an integer n we will make a combination of perfect scare for example 149 and 16 are perfect squares but 3 and 11 are not the sum of the combination will be equal to n and we will return the list number of it for example we are given 12 the output would be 3 because sum of three-fourths is the wrist number three-fourths is the wrist number three-fourths is the wrist number not like this it will be for we can solve this problem using dynamic programming let me show you the bottom of way we're gonna find the app for an equal type first we need an array for sorting the final solution and intermediate sub Solutions this is curve elements and we need one additional element at index 0. we can use it to simplify the calculation for square numbers second we need to prepare secure numbers square root of 12 is around 3.46 and the flooring it is 3. 10 one two three the square numbers are 1 4 and 9. and we can use this element to zero to calculate the count for square number indices a bit later let's see it step by step at index 1 it's square numbers so index 1 minus square number one is zero we add 0 to 1 and update it as minimum value it is one and index 2 we have only one square number one until now so index 2 minus square number one is one so we add one to one and update it as minimum value is 2. we do the same thing at index 4 it's a square number so we have two square numbers less than this index we find out which one is smaller than the other and we find an updated it is one we do the same thing at index 9 it's a square number so we have three square numbers less than this index nine we find out which one is the smallest amount the others and updated it is one and we do the same thing foreign ly we found the least number of perfect square numbers there's some to Turf okay let's code it we Define a DP for dynamic programming and bottom of way it is n plus one number of infinities and we set the value of index 0 as 0 to simplify the block called logic we are preparing perfect square numbers from 1 to square root of n and we floor it using hint function we calculate the minimum number of perfect squares from 1 to n in order we check every square number we prepared before seeing if it is greater than I if so we don't check Roger square numbers anymore at this step I if not it means we can use the square number at this time DPI minus Square located value is the minimum number until I minus Square so we add count 1 to it and compare the other cases on the other square numbers we find out the minimum number and store it for I after all the iterations we return the last one of the DP array okay we made it this solutions time complexity is because of n square root of n because Outer Loop is iterating for n times and the inner loop is it rating for maximum square root of n times and it's a space complexity is because n because we used all DP array I hope you enjoyed this video and it was helpful I will see you soon bye | Perfect Squares | perfect-squares | Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.
**Example 1:**
**Input:** n = 12
**Output:** 3
**Explanation:** 12 = 4 + 4 + 4.
**Example 2:**
**Input:** n = 13
**Output:** 2
**Explanation:** 13 = 4 + 9.
**Constraints:**
* `1 <= n <= 104` | null | Math,Dynamic Programming,Breadth-First Search | Medium | 204,264 |
337 | hello everyone uh today we're gonna go over uh lead code problem 337 uh house robber three so basically what's going on in this problem is uh it's a bi it's a tree a binary tree problem um so i'm just going to go over the problem statement here uh so the thief has found himself a new place um like a neighborhood and he wants to maximize his gains in the robbery so essentially what's going on here is that a thief can only rob houses that are not connected to each other and that is because if he robs two houses that are then you know that the police will be called on him so he'll be busted so just to go over the first example right here um for the thief cannot rob three and two because those are adjacent or they're uh they're directly connected but he can rob two and three so you know we can go over the potential robberies that can be performed on this one again the first one that i said two and three so five and then the other option is three and one which is seven that's the winner the thief can also rob three and three for three and one any combination of these but they just can't be connected and now we can go over example two here and i'm gonna jump into the white boarding session for that one so this is example two um and you can see i have an alternating uh row of colors and i've actually expanded on example two here so what the thief can do is he can rob three and its grandchildren so three one three four one or this row of um houses and their grandchildren four five two five seven nine six five four and three so if you add up all the um uh the sums for each color um for this and this you get a sum of twelve and for the greens you get a sum of 50. so that's the clear winner here so yeah just to go over the solution here first and third rows the blues 12 and second and fourth rows the greens are 50. so that's the one the that's the group of houses that the robber would go for so now we're just going to jump into a kind of quote-unquote dumb solution a kind of quote-unquote dumb solution a kind of quote-unquote dumb solution so it works but it's extremely slow so what we have here is a solution where the nodes are essentially alternated the descendants are alternated so here we start at the root um let me change my colors here to green all right so here we start uh at the root first step um and we go and we iterate for the left node and we go over uh the grandchildren so we get the sum of the grandchildren's um so you get the sum for the left grandchildren and the sum for the right grandchildren and you add it all to value or val and you essentially find the max so there's the max of two groups of values the first of course is um the value of the root here plus the value val which you just found which was of the grandchildren and you add those up that's one group the second group is the other alternation which is the robbery values of left plus right so that's one group and when you find the max of those two you get the best choice so again for uh for the this tree right here um that would obviously be 50. so with the green group which is the winner um that would be this one right here because of course you're not doing the root you're doing um the second alternation so now we're going to go over a slightly more complex solution but this one is the most optimal so for this optimal solution we're going to use the first example tree uh so this one right here um so to go over this we're going to just run through the code and you can see i have a lot of notes written here so let's walk through it um so when we start out at the root you calculate the left array and this for this you have to make the recursive call for node two so this one um and you can see i have the notes written down for there let me zoom out a little bit so for two's uh left array that's going to be and i should rewrite this is going to be a array of size 2 with both values set as 0. and then the right array we're going to make the recursive call for node 3c and the notes are here for that so the left again this is going to be an array of size 2 with values 0 and same thing for the right yep and then you calculate the res array the result array so that is the math.max of left 0.1 so that is the math.max of left 0.1 so that is the math.max of left 0.1 which is 0 and then result index 1 is the value of that node plus left zero right zero so we have three and that so yeah this one is zero plus zero um index one is three plus zero which is three so now we go back to the uh the call for node two x um and here we have so we calculated our right array and that is 0 3 which is what we returned here so now we calculate the result array for node 2. so let's run through that again math.max so let's run through that again math.max so let's run through that again math.max of left 0 left 1 that's 0 plus 3 which is 3. and the result rate at index one is two plus zero again it's the value of that node plus left zero right 0 and those are both 0 so that you get 2 from that so that's what this is the result array that this operation or this function call returns so now we're back at our operation our initial function call at the root which is three a and you can see here we have uh array with values three comma two so that is done now we can go to the calculation for the right array and so again it's going to be something very similar to what we just did we can quickly go to the function calls again so the left value again is going to be 0 the right value we make a call for one y when y is zero for its left and right and of course we get uh result at zero is zero result at one is one because it's its own value is one so we return that here for the call at 3b and so let's calculate the result array for 3b at index 0 it's 0 plus 1 equals 1 because math.max loves 0 equals 1 because math.max loves 0 equals 1 because math.max loves 0 left one zero mathematics of right zero right one is one so zero plus one equals one and then the result array at index one is the that current node's value so three um and then left zero right zero which are both zero so three plus zero equals three so now we're back at the initial function call and the right array here is one comma three so now we have to calculate the main or sorry the last result call menu result calls um are not calls i'm sorry uh calculations um so at index 0 we do math.max of the values in the left we do math.max of the values in the left we do math.max of the values in the left array so that's going to be 3. and then math.max of the values in the right math.max of the values in the right math.max of the values in the right array which is again 3 three plus three is six and then for index one uh we are doing the roots value three plus left zero plus right zero so three plus one equals seven and of course the um the answer the correct answer is seven all right so now that we've run through the solution um and this is kind of why what i asked myself you know the first time i ran through this through the steps of the algorithm was what exactly is this result array and how do you actually end up getting this answer because when i did it the first time it wasn't really immediately clear to me what was going on so essentially um you know i'm going to go over what the first uh edit what index 0 means and then what index 1 means so i'm going to draw a little another tree here so we have x y and z all right so index 0 and index 1. so index what index zero means is you're not robbing the root okay so you're not robbing the root and you're going um you're basically focusing on the children of the root um so these two let me draw that better so these two um so you're not robbing the root and then it's basically the max output of let me move this of two things first let's focus on the left child max left child you either rob the left child or you don't rob the love child so you have two choices here any and you're basically finding out which one yields the highest results and same thing for the right child and rob left child um let me make these markings a little clearer so don't rob right child yeah sorry i forgot um my yeah i'm erasing the wrong things all right don't rob right child uh so this symbolizes z symbolizes y so this is what res1 is so you have two values here and if you don't rob the left child that could possibly lead higher results same thing for right child so if you find the max of both of these that could yield you the highest valued solution of course when you're not robbing the root or the current node that the function call is focusing on alright so res1 is kind of the flip flop of that so you are robbing the root and let me actually redraw the diagram to make it a little clearer x y z and then you're not focusing on the children at all and here's where i would you know go into like grandchildren territory i'm going to draw that to make it a little more clear here so you are robbing the root you add that to the sum of res one and okay so yeah you're adding the root and the i'm going to draw a little bubbles for these because these kind of symbolize function calls um and it is the output of not robbing the left child so it's really just the left child's grandchildren and same thing for the right okay so you're not robbing the children because of course that would violate one of the um one of the givens of the problem you can't you know these are related so you can't rob um ex's children directly um so these kind of just symbolized function calls and yeah it is this is the value of not robbing the left child but you can rob its direct descendant and this is uh not robbing the right child but you can rob its direct descendant and so on so conceptually that's what's going on here that's res0 that's res1 and when your operation goes all the way back to the root like we did right here um in that final operation uh what we found was that robbing the root plus the max values of the robberies of roots grandchildren three and one yielded the highest results versus doing this operation here which did not yet it yielded six um so that's that is the house robbery three problem um all right and thank you for watching | House Robber III | house-robber-iii | The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`.
Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**.
Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_.
**Example 1:**
**Input:** root = \[3,2,3,null,3,null,1\]
**Output:** 7
**Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
**Example 2:**
**Input:** root = \[3,4,5,1,3,null,1\]
**Output:** 9
**Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 104` | null | Dynamic Programming,Tree,Depth-First Search,Binary Tree | Medium | 198,213 |
48 | hello welcome to my channel i'm here to do my 100 lego challenge today we have question record 48 and rotate image so you're given an n time n 2d matrix representing an image rotate the image by 90 degree clockwise so you have to rotate the image in place which means you have to modify the input 2d array i mean to input 2d matrix directly do not allocate another memory and that's the problem and the example right here we see one two three four to nine and we just rotate this row become a column in here bro become a column in here row becoming column in here so it's at 90 degree and for this question here's another example we can use the pen in here to draw this out first now there's two steps to move from here to here that two-step to build this that two-step to build this that two-step to build this 90 degree rotation so first we can switch this row by switching left and right so now it's three here six nine two five eight and then one four seven so by switching the column you see this is the new order um in this new order you can anti-clock i mean you can anti-clock i mean you can anti-clock i mean anti-diagonal to switch 2 and 4 anti-diagonal to switch 2 and 4 anti-diagonal to switch 2 and 4 and become this order 3 and 7 become this order 6 and 8 reverse in this order and this diagonal line anti node light will not change because if it just changing to itself so after this two step and it turned to a 90 degree look so that's basically the idea of this question but i believe there's a multiple way to do this uh you can take a look at the discussion right here but now i introduced this way first since we cannot use extra memory then we just do everything in the original matrix and here's void then we don't need to return anything and we started with the mattress lane matrix because we need to use it let's make some pseudocode we will first flip we do the left and right flip and what it means is i equal to 0 i less than n j is equal to zero and now the tricky part j is less than metric lane which is i think they are the same so n time n so will be n divided by two so we can have pointer here and if this pointer switches to the last one if we move forward and then this will count backward so we only need one count counter in here one pointer in here until we go to the middle part you can see this example now we are pointing to five and we switch to length minus 0 minus 1. here increment by 1 they'll count backward incremented by 1 2. so they will switch this two row j is plus and we'll keep in terms equal to matrix i j and mac tricks i j equal to matrix same row and we'll have n's the length minus 1 minus i minus j sorry so i n minus 1 minus j will equal to temp so basically switching this and we look through the whole entire row column and then that will be it and this will first switch after this loop sorry upload this to double for loop and we turn to this state right here the rest day but now we have to do the second flip by and ty type good no four um this is another thing that we need to be careful so in this case we have three two one six five four nine eight seven in this case we only need to operate this three number you know you can flip this number and then find the opposite number which is here flip this number to the opposite number seven flip this number and eight and this number you don't need to operate and you shouldn't go more than that because if you go to 8 and flip it back to that opposite number then that means do nothing what we can do is just operate go through this corner right here let me draw this what we need to operate then so i is zero and we don't go more than that so i is less than uh n minus one ends right here and minus one is the one before that so you only need to loop that much row i plus and how many columns we need to do so we start with 0 and then j is less than n for sure minus 1 which is the last one and minus i okay so if this increment by one the boundary will reduce one by one based on this uh logic you can see the pattern right here so j is equal to this and j also plus so now we only look through this area what we can do is also having uh in tam equal to matrix i j matrix now we have to look at the opposite side uh you can see this 3 is corresponding with 7 which is uh n minus 1 minus j and let me copy this one i mine n minus 1 minus i will be equal to temp oh wait matrix equal to this and this thing to 10. so basically switching this two um two places the corresponding is n minus uh j at n minus 1 minus j and the column will be n minus 1 minus i so that's it for this rotation and after that it should be it because you don't need to return anything we first do this one we can have one we can run the code sometime we do this oh wait where is it so now you can see um if you want you check this code and it looks like this so this stage is here right here so we can double check if this code is right also you can replace this one to the beginning one and see double check if you're doing the right things because sometimes you might have some error between the upper code and lower code it's hard to debug um let's see 18 right here okay that's it submit it yeah that's it for this question uh if you have any question please comment below and i will see you in the next video bye | Rotate Image | rotate-image | You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000` | null | Array,Math,Matrix | Medium | 2015 |
76 | That fans, in this video, we friends, so I want to tell you the smallest submission of the first Singh in which I am the example of all the characters of Joshi. Everyone can see what is this question that we have, like the example we have is, the first one is string one and the second one is Rintu, we have to tell the smallest sub-section of this trick which has tell the smallest sub-section of this trick which has tell the smallest sub-section of this trick which has all its characters. The monitor should be broadcasted on someone else, how will we do it, we make it in frequency, * make it in frequency, * make it in frequency, * make caffeine limit, which gives us this in sequence. Will tell ka this is once bae is twice cb is twice and d once ok this reference became mother now we will make a mixing apps youth came to the beginning and is sitting here so we are going to start sucking a wire and Release and work, we learned something that we made a video named Match Account Ki Chai, within its most there are Account Match Account Ki Chai, within its most there are so many people in its most that we can get all the letters of it, so see, when I acquired it, then this dominance. So here Saxena is the most domineering person in the elite, so whatever is made of this, we have acquired it right but at this time the match account is closed, at this time suit one has become because DD1 has promised the work when the work is fatal. If we do then the match will increase, when the relation of Bina is that if Himanshu will not fall then it is okay and when we start discarding then the method will decrease when the match will reduce to 6, then there will be a neck, meaning all of you guys have done it well, we are fine, now the next one is closed. Acquired frequency b11 now even it is less than abtu that is right also acquired match point back to that this work is done 11111 subscribe our innocence in the lower village of these na songs take 12123 this restrictions are mash three loops of juice Let's do this now there will be a viral even in this match because it is here that now the straight cross is even C-1 and here C that now the straight cross is even C-1 and here C that now the straight cross is even C-1 and here C is twice then the match point of the first over will increase then it has gone to 84 B you this second one is also in cross 2 So all this is a superstition of ours that we have match points and 15, that the total we need in 6 practices is 122 and one is character, we need 5, they have done it right, it has happened once at one place, it has gone viral in friendship. This is one of them, it has arrived 1 day ago, it needs to be washed, two back ones are done, now this extra one has also arrived, also noticed that your frequency map will make you for B3, but only with this you will not have to match any more or you have not. Developed team yesterday there were two here so the theorem disease this fast this now see these were my two only why will it not increase the match or have done your strike for your business do this square request the seeds of the sequence like this during the Btu Also cut it a little, this will not spoil your mash. Okay, now this one has happened once, one will be two seconds, this should have been done, so in my big body, I have also done one more time, spread four advance, this is the fourth Vivek Roy. Only two are needed, they are beyond the wire, so there will be no more matches with them, we have also got married, so now we don't have only one, we don't need only one, second test draw, why won't the match be extended, work on 9th is also kept closed, now C has been acquired, Situ is done. This will have maximum effect because it is difficult and friendship was needed. Now if you share Toubro then you will increase MS Word. Okay, this is the time permit, so leave the question, your work has been done, this is the answer, all its characters are inside this servicing, how? Look na d twice we should give di four times vulture should it is twice it should have that extra whereas ec2 times it has merit twice so it has all its characters inside it but it may not even be in the shortest answer but God. Dhowan's answer is a possible answer, so we left a wire, left it, and the release will start, now let's test the relays to come here, first select the answer that brother is a possible answer D BBC were in, only then this Big heaving first selected here now increase it and delete it and even while releasing match account will decrease but not always now it is ready to release it will become de1 even after release it has become one no problem and you have added extra one Delete or remove the spectacle is fine, it will come out again soon, now this is a possible answer, this saliva is because Bishnoi is also fine, MS Word is developed, so this is the answer and this striker is also small, so we are submitting our I to you. BSEB will give, I want a person younger than me. Okay, now let us bring this here and disassemble it, this will be a thing of the past. Now you will think that this will be internal, when the last step is gone, why will it not be removed, why will it be buried under even two. Na then we have used it unnecessarily in 14 of Kama Bandar, the fourth one has also been released, the fourth one is useless, only the second one will be released, then there will be sorrow, now there is no sorrow, okay, then we are again, the currencies are there again in the form of relief and this is the answer. Have you seen, this is the perfect answer for this train whose frequency is written D 12381 SITU, there are directors of six tractors inside it, so if you have this, then by playing this Eid DC is made, then see are all the letters for it yes, its Hope there is 11, if there is at least one then there is friendship in it, wash one, if there is even one, then it means that while requesting you, till the time the answer is not received, now we are releasing it so that you can know about it. Younger brother, if you get answers, you increased this and released one, a big facility, you will become even from petu, you will become a27, but you will adopt the attitude of the match, you have released shoulders from a to, expressions seven, one, tell me, you will not like it, down, no feeling, form. If I have it again, then this is an even better answer. Well, CBI gave ginger paste is the answer. According to this, the actors are present and all the tests are also present. If there are extras, then this disease is the shortest in time so far among all of them. Have increased and released Echo Insan Ki Vandana Also removed this unit from this time Should n't I reach them only That yes this is fine So you pose again This is the last time Cigarette is the answer 2 This time our of dancers CBI comes in divine form, first of all they collect the answers, if Israel is removed, then they take it from Hello Yes, then they increase it and release it, now do n't send this useless message, I will sew it as soon as I sew it, give it to AP, need this work Ka 2 has been released, the work is serious, this point will go to five, it is okay that as soon as the match account becomes less than its length, stop deleting it because now I have not been successful in it and it has become Dayawanti Riya Jeevan Hai Bittu Cricket There is a thing for them but if there is someone for Situ then now you are not in balance now you will have to start returning it then it is very simple a virus till the time of scientific that * length then Hiddleston come correct the answer scientific that * length then Hiddleston come correct the answer scientific that * length then Hiddleston come correct the answer press Click on the match till one and a half, if the match gets spoiled, the match five is spoiled, we need 66, okay, now we have increased it, acquired it here, one has become 322, one developed, two a given, if we appropriate, then we will not have to come, increased, unites. It has happened here also this month will not do the business well, it became free but his two sons also keep doing it once, is of no use, has done F1, will not do match road, also took the question, 204 has become B4, so it is on him. There is no use of MS Word, you will not need it, wash your two gone between 2F2, second is the yagya of ours, it was necessary to improve the smartphone, if we took the third quarter of the knowledge of its development, whatever is to be noted, it cannot increase your matches, now that you have squared off. There is a sequence, you have done a sequel to this work, two wanted friendship, there has been love, okay then the maximum has increased to six, as if matches have happened, stop loving, now more work will start, then this answer gives your desired content but this If it is not small, then increased it even more and released it, even after rare time, how well will the mash reduce that the death of the fourth period should happen, increased it even more, released it Bittu, even this will not destroy the match point because it will happen We have also released the third one, we need two, friends, we have also increased the release, this has become two, how will you know, we will not have it, because now I want the third release, this is what you want, now you are going to suffer, okay, now time is speaking a word. In the middle of the procession, depending on the monsoon, they computerize the dance alarm and update its length smaller than this. Well, in any case, here Reddy also released b1, as if one did not play the role of his work, all are in two. There are three things, you have one, friends, you have listed it, so for the fifth and 2 minutes of the match, like I passed it, now you have to start memorizing this mixture, so you have increased this expense, it has become 310 China. Maximum does not read because you increase it once without any work. B increased its previous 22. B also needs another cross. So the match we increase the total to six or now we will set Edison but for this I will see for myself. Is Sabina here? Is it smaller than C? No, it was made smaller and bigger and deleted. Yes Bittu, it is done, will we spoil you by doing duty? No, without gearing the car, now released C. As you will do daily, your C1 is done, but if you consume it, your match point will go to 500. There will be a daily collection, if I pass then I will have to think about it again. One person has not made the match because this is not the same. You are going to the village of two from home. There will be no breakfast. If you are hesitant in securing it again then this. If there is no match between then Intact, what you are seeing that day is the net speed, so inside this train all its characters are buried, not cigarettes, inside it, think, inside this train, there is D twice, we need one buried three. This is a bar, it was wanted twice, this is four times, it was wanted only once we had two girls, this whole room is sealed, we want friendship, so this balance, Udayveer, we got it from gram flour at one place. That's fine, I'll get it done again for the first time. People will write a little first and then do it again after writing. It's fine if I didn't tell you. If you watch it, you will understand it. By the way, friends, Admiral is needed in 2 minutes because it is long. Salwar is strong, we will leave a little, it has been done in each address, now we will see, after the corner, if we sign again, then at the time of court, we will understand something and then after the court, we will fight here again, only then we should understand. Okay here you go to code that this editor I request that chick that we have to answer I declare a string answer is equal to mp spring last line is it return an answer that a in the middle na I It is special that I make the character versus the interior. I am the map to the setting. We made this. We saw a new house. Okay, and the point is i20 is done. We put a loop on the hybrid SIM slot length pin and removed the character * Don't Forget it, removed the character * Don't Forget it, removed the character * Don't Forget it, okay, now do a very beautiful job, I message you, if you want to increase the cancer, then I can teach you this, I will not get more difficult than this in front of the collectorate, this is the way to do it, otherwise it is already there. If you do it one by one, then I do this, good match, then close all the other ones that you have, now I want this trick will help in making the frequency of becoming, this relationship has also come and should also come in the beginning. G B is at minus one. Now till the time I do some Khatron by doing wild two, keep the work going. So first what do we have to do, one wire, till when, the wire does not come right, Tarnach Pandey, then what to do, release and correct answers. Okay, okay. If you do this then it will keep going viral, that's why there is no support, there is a string one daughter in law, while the limit is there and the match account is loot dude, otherwise this does not happen, this is it, let's make the character Liya and after that I will give you this daughter and Even after this, now we will do it one by one, now the scars are more disgusting that the gate and the default map are how many liters are my feet that if that loot is equal to two, after considering it has become equal, the scientist is also discharged from this, map to make. Those who are before this, have claimed a work as yours, if you have not subscribed to the other work, then who should increase this type of match, otherwise make it. Understand this, what has happened if after acquiring the character that you have acquired, I am my Buffalo or leave, it is equal, that guy has done well like write dry ginger, now it is ec2, you share the first one, it is gal, you square the second one, I should increase it, but when you become free by requiring, then it has been more than a week, it is useless. You have shared, do one thing, so I have written this now, Les Nikul to your skin, why the court became equal to my acquiring, he needs 32 and if you remember and give it, then you are posted before that, have noticed the work, okay, good. Release Next Answers Harishankar What is VJ in actresses Make this paste 10 medium should work A solution of reasonable price If a little will do then it is good Ok acid in Devdarshan I & Match account If good Ok acid in Devdarshan I & Match account If good Ok acid in Devdarshan I & Match account If you are from here then please try so what are you Will do and subscribe this Ghr to and subscribe this Ghr to and subscribe this Ghr to A Plus One Se A Achha Ok G Plus One Se Aaye Plus Book We Will Go That This Is The Question We Will Like Because JP Look Up This Why Will We Go Better Than Jackson Which Is Agreed Come to the initial point, I used to reach here, then you had heard this stuffed, so you want to get all this penis, then yes, here I am sitting on the forest, so you from here to here, I will give you the answer inside all the lions. It's fun, he cleans it, he does n't take up the project, he is famous for ecological, he has come up and down, it is necessary that when you see me speaking, he starts eating as if he was raising you, he has to ask questions to raise this chapter. And our J1 is behind, it has been released like the oil has not been released, where it has been ready, where the organizer has finished, Amrit has sat because the previous one has not been done, so we will cut all this from here. Will celebrate ok appointed by speak why took from z plus one you have any problem when why have taken from garlic that I but from gold took it because it was Italy is very less and why took in you I don't like and that But first of all look at the IS sound, you have to do one more than the regular smart end, it works from the top one that if you say two to four then it gives you two three letters, you used to say tujhe bhai, two three four gives the last character. I have to say more than that, it is a potential answer, but this potential answer will become an answer only when its length is shorter than the actual answer, so if the CM length is short, then the answer is called a different answer, but if it is one, then initially it is definitely liked. If you get the answer for the first time, either the length of the answer is zero or the answer has not been made available to you or the answer is a small child of the potential answer. Whatever it is, Radha, after that the job vacancy has been set, so it is as small as a protein from last year. So will you be able to update it? Okay, I have done it, now this answer has been corrected, rather I should say collect answer channel is Agni, have done some correcting of answers and releases, now I will release it, I will see my character, I will first increase this and then the character. See response dot love you are fine, you made this, you caught the character, this increased, you caught the tractor, now what will you do, now you have to do sun, chairs, frequency will decrease, this frequency - if it is there, then we will do the frequency, this frequency - if it is there, then we will do the frequency, this frequency - if it is there, then we will do the frequency, above this, it will have to be seen that if the frequency is already I In the forest, if its frequency is already consumed by getting the frequency of gate CS, then I will cover it with you, I will give you some not removed iron graphics in it, this is to reduce its frequency, you are wind, salute that I map not gate in front of conduct CS. CH - reduce it from institute, if CH - reduce it from institute, if CH - reduce it from institute, if its frequency is one, then remove it, then release is done, good divide will be on maximum, now let's see map one daughter default that tractor is forced map1 but frequency has reduced that I am to C That I am scared of my work's monkey, okay if your frequency has reduced then the meaning of your work is still the same, then this temple is made of me, it was more than the end, okay it has reduced, developed, stop on your work. Match account - I am okay 1628 Match account - I am okay 1628 Match account - I am okay 1628 When will we get it out, how will we get it out, then it has a simple step Boolean flag one equal to two fonts If we both close that above then we took it from the form Okay, so come to the first form also once If you go then start the flight mode that I have come in this group and you have also come in this form once in the release form, rather make this flat to go to and check what was told to the people outside here but the flag remains 115. End Plot 250 If you are not going to get special form then we will put it Ok so I think what is the national game Drawn into some hidden cam is running Used to submit Correct answer is coming Not coming Correct answer is coming to you Is giving you And Rana again with this was the correct answer Howrah West Okay, I will make some space, made this paste and do nothing else, come 163 food on an empty stomach, the first part is of no use because there are buses for the village. The pregnancy map which I have made here is made in frequency. Then your match is zero in the beginning. We decide which comes into the length. Markandeya Katju - Markandeya Katju - Markandeya Katju - Keep it on us. This also works. This potato is useful. This is the by-law firm. Let's take potato is useful. This is the by-law firm. Let's take potato is useful. This is the by-law firm. Let's take this cord in a viral service. Hello friends, gentlemen, I am fine, it is a very big coil, so it will remain ready, it is ready, okay and I will write down the frequency, then which beloved should I tell and Bittu C21 was here. Where we have just decided it means this is the name of love below as yes requested so here I am the frequency of my map1 so my device is done so life is done it came from these three and increased it came and increased it again Pimple has increased and stood up, now I have to do this, MS Word will increase, frequency is equal, meaning till when the work is coming, then match which one has increased and yours is closed, okay, MS Word has opened, went up by more, moved forward again, capture this. Have become or pimple pencil daily and two today is less near village manager and match Aquarius two will do are made of work then went up that came increased acquired a well and sequence equipped nickel problem is water is less work We have a match on the salary that we are able to see during the working day. Went up twice to request for work. Equatored the frequency. Life has become here, now it is on fire only here, otherwise it will not be mashed because the work is like a pillow. Seeing my acting below, Kahar went up let's increase C acquired seven frequency less nickel to hai I am you and I in you I am on Malik now I am completely work Comeback bar then increased I to four again went up go up Let's increase the frequency by making it and then acquire it. Then let's see whether we want to increase it or not. So we came and made it bigger. We made it and captured it. Increase the flare-up from Bittu's remains. The arrangement for like owls etc. is Increase the flare-up from Bittu's remains. The arrangement for like owls etc. is Increase the flare-up from Bittu's remains. The arrangement for like owls etc. is acquired. Friends, if there is another solution then we have passed the scooter. Went up, increased sexual frequency to three, increased to three and need curd even on the road in front, there is no work, then went up, acquired by increasing income, increased income to 12, then one broke, now think, we will not do news, now this is thick. If it is more than 231, then the inquiry for work is without work, there will be no romance, went up again, even after increasing the income, there is a verification, too, before e, oh brother, this is what is needed, too much is going on without any reason, the chiruri has started, Parmesan cheese, look. Did that they went to two cans which is more so why would I not be able to grow by that then went to the top by increasing the income and went to the sequel, here it got shrunk, then the sequence became e2, cigarette, it is equal, it is equally useful for both the things, this number will be 6 messages. The match has been no less than the ODI matches, meaning you have to cover all the hearing backs, what you have done is that it starts the work of absolutely revolting the good song 2012, if the duty forces does it, then all of it is inside it, like this and so on. By tightening everything that you have till this point, everything is there in it, so in my opinion the release will be fine, go back and sports goods from The George, only the report will be fine, from this the answers came to us, we got hold of this listing, we saw the links of the answers, hey. So tell them with your answer that the marks have become our means that it has become cancer, it is okay, it has become cancer but now we son Sharma will try, the scoundrels have increased it and will release the chapter, it has increased it, released B, decorated or David Dhawan's frequency has increased, now we have to think that the match point - subtract one, it has become now we have to think that the match point - subtract one, it has become now we have to think that the match point - subtract one, it has become equal, it has decreased, it means that we have done unnecessary things, we have worked, it would have increased, the second DJ had released more, so it has not decreased. If it is equal, then why won't I move away? I have wasted it. Come up again. Come up here. This time the answer is this and all the conductor content. This is the text for 211 and Bittu as well. C2C code is Jeevan and it is shorter than the previous answer. Also this is BLDC transporters update two back vy ok after doing this increase release released B itself got blasted internally now think match some such tears or 32 still more going on So it means some match morning, this pet monkey has been decided again, usually it is brown, now it is smaller than here, so update this that CBI Chief, I thought you are different, he is soft immediately, so I am not calling, release Will remain again but let's do it during the time. Okay, so now after clicking this and answer, increased it to 140, made it 827. This time also MS Word will not make any difference because right now, the monkey will open the door on its own. Okay, pay attention to the doors. If it was circulated then such a wife is BDC and this is a good answer, this is BA BSC and this is a good answer, then it was expanded and released Your Dear, it was removed, this time also there will be some difference in the match point because the time work is getting less in this. If you are looking for another good answer then we have set it as CBI which is the right answer. Everything is fine in it. D is once, three is two times, B is three times, and if there is once, then one is needed only then it is more. If it is like this, then everything is its center content. It is a very good answer. Okay, so we collected it from here, made it and released it as a series, this time we made a mistake by doing a series, this has become one, which became a medium like this, then we came to know that Please tell me what is to be released, here is my map filled from inside, I have two bars in you, so will you send the monkey of work, I have made it 15, so five out of six of these are closed, here are the bays, there are two, there is one bar in the seats. Okay, so now what we have to do is to stop from here and go back to the start, Solan Fennel, and so in this way, we will keep making and running the best battery trans. I hope you understand. Come let's meet next year. Thank you very much brother. | 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 |
1,496 | See, in this video we are going to do a question, the lesson of lead code, crossing, you will be given a string like this is a beautiful string, Jas and means North e4 East S force South, if blue comes then West is ok brother, it was very good, now this In currently starting, you are standing at zero comma 0, it is a very good thing and you will move accordingly, N means, go one unit North, then go 1 unit East, go 1 unit Ha, okay, you will move according to this string, it is very good for you. Return true if the text you are looking for is found. Okay, if you cross any of your old paths, then you have to return true, otherwise you return false. Take the string I, it is okay, take it, North is this. What will happen, will be the diameter and give it will be your south, okay brother, you are standing at 0 in the starting, you went to the north, okay brother, it is gone, there is no problem, then you went to the south, but not like this, let's take it first. Aneesh, now let's see, he is going south, so what is happening, nothing is happening brother, there is no intersection here, but there is some string A caste like from Se, take Maa, as if earlier example was NDS. N Gaya S Gaya, you see, the overlap is the same, so it is okay, if there is overlap in the second step, then how to calculate, now see, if you have tried but still nothing is happening, then only then it is good, then try bandaging the video. Do ok let's go 0 1 What is its code net here 0 That's right how much coordinator is here One comma one How much card net is here One comma zero Good thing Now see if there is any intersection then the coordinator function will repeat Like mother, take this is my string, now N A S A N, okay, yes ring, mother, so where did it go first, where did North go, where did East go, where did South go, where did it go, where did North go, where did it go? Blue, you are looking back here, the cardinality that would have come here once before has been repeated again, okay, so what will I do, not at every step, I will keep it in my time, okay and then when I Every step will be a pleasure, I will see if it is lying in my pocket, if it is lying then please return the true key, yes brother, the cycle has been made, if not one of ours, then return the water in the last, okay, now it does not make sense. We will store this story in the set, we will store it in the set, let's see how we will store it in the set, because is this zero comma one, if it has two values, then let's reduce it by one, see zero comma 1, this is today We will finish it with n string, right? If the matter has come from then yes, it is fine, it is a useless question, don't get worried, but give it to me, let me start, see, I am late in the set, so what will I keep in the set before quickly, let's put a loop in the string. Let's put a loop, text dot care, okay, what else will I do? Let's do one less. Let's define two variables. First, the Wells let's put the ladder L s if c equal west l se si equal south equal l se equal tu ok if you see it is in the north, going north ok up so give a big one ok if in the west It is going okay, that is, in this direction, it is going towards the left, wherever you are looking on the screen, it is going towards the left, that is, do X - - if it is going towards the south, it is - - if it is going towards the south, it is - - if it is going towards the south, it is going downwards. That is, we will do A - - If you are going towards this, going forward, - - If you are going towards this, going forward, - - If you are going towards this, going forward, going towards the right, that is, X + Okay, when we X + Okay, when we X + Okay, when we come down, the operation has been done, you will have placed one less. Okay, so what will we do here, we will see the coordinator C O, give the pulse, what is the coordinator, you will see here X + comma dot, write something here X + comma dot, write something You have already come here, first make the return true, otherwise you keep wandering, what difference does it make, okay keep putting set dot add c o, okay if the loop runs, what does it mean brother, there is no return. What does it mean in the loop, no cycle has been made, it is okay, if it has never been run, then burn the return that brother, no cycle has come, let's run it and see, the wrong answer has been given, let's reduce one thing, there is one thing missing here. Let us add one thing here in advance 0 Isn't it right, in the beginning, we also add that we were standing here earlier, it is okay, it is over because we have set up here, it will be unique. We will make strings here as long as it is | Path Crossing | lucky-numbers-in-a-matrix | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. | Array,Matrix | Easy | null |
101 | Hello, this is coding in a big way. Today, we will try to learn the lute chord. The problem we will look at today is the deep-sea trick article No. 101. problem we will look at today is the deep-sea trick article No. 101. problem we will look at today is the deep-sea trick article No. 101. So let's take a look at the problem. Yes, I will give you the deep-sea trick No. 101. There let's take a look at the problem. Yes, I will give you the deep-sea trick No. 101. There let's take a look at the problem. Yes, I will give you the deep-sea trick No. 101. There is a binary tree here, and this is what it is. Slide to determine whether or not this is a deep tree, which means symmetry. So, cut this to the middle. I think you can cut it right in the middle of the problem and determine whether it is symmetrical on the left and right. If you look at the example, number 1 is a mock root node, so it doesn't really matter. If you attach it to the bottom and start with the child node, both n eye nodes exist. The veils also have to be the same. Oh, then there is a lot of symmetry. Up to 2, this is the center. If you give it again, the number 3 at the end here should be the same as the number 3 at the end, and the number 4 on this side should be the same as 4. And now, in another way, this can be said to be symmetrical as a deep-sea trimmer overall. And this can be said to be symmetrical as a deep-sea trimmer overall. And this can be said to be symmetrical as a deep-sea trimmer overall. And then if you look at the next one, it should be 122. Well, then the empty one, the right one is also 3, the left one is blooming, and the right one is also 3. Then, cut the left and right here in the middle. Well, both nodes exist. There is an evil tree node, and the value is right. Then, now on the left. There is no child node. It doesn't matter if it doesn't exist. But the child on the right here shouldn't exist at the same time in a symmetrical position on Arbor Day. But there is 3 here. Then, if you draw, the left and right sides of are different. If you lose to a mob, of course there is no actor and it is a veil universe. Merchant Ian may be correct, but the existence of the node itself is also not correct. That's why we can say that this is not a nickname. Well, then it will be M's blood tax. Let's take a look at how to iterate. Here is a parent node called Japan. This is Belle. In order to refer to the tree node, I pointed it out as node 1. This time, they will see themselves together as 1. Go to the child node number 3 on the right. This time, they are trapped in number 4 on the left, number 5 on the right, and number 3 is 6 on the left. Let's look at number 7 on the right side. The water diagram on the left of number 4 is number 8, and the difference 2 node on the right side of number 7 is 9. Well, this is symmetrical. If you look at it is symmetrical. How do you know this and solve it? In fact, if you look at it in order, Now, compare numbers 2 and 3, 1 first, and then compare number 4 and secret number 7, which is at the end of article 9, number 5, and compare number 6, number 8, and secret number 9. It will be like this. Now, in order to do a data rate method, you basically need a data structure. Putting a tree node like this and now taking it out. But now, what is stack q? Well, both are possible, but we will now take a look at the stack. So then there is a stack here. Ugly stay. 1. There is an ugly stack, so I will arbitrarily place it here and compare it to this time with the left child node. I will pass it 3 times. I put 3 times, and then I will beat the one that pushed this guy and take it out. 2 like this. At the same time, I'm going to pop it and remove it. Then I'm going to pop it and then it will disappear like this. It disappears. Now I'm going to compare numbers 2, and 3. I'm saying that number 2 and 3 do not have two nodes, or both nodes exist, and they both say that nodes exist, and there are two We 'll check 3 things to see if the bells in the node are the same, 'll check 3 things to see if the bells in the node are the same, 'll check 3 things to see if the bells in the node are the same, so if all 3 pass and there's no problem, we'll put in our own number and start the next step of comparison. We've done 2 and 3. What we are going to do this time is that all children on the left will have to add greeting number 4 and have contact with someone for number 4. Since we are doing Papa Bee Bom twice at the same time, let them know how to compare it together and add it once. Compare with number 4 and the interpretation will be number 7. And this time, there are 5 times the right shoe. By comparing the 5 times, the muscles become obvious. 6 times, this is over here, and only then, when you go to the next house, you will have to pay for these two seats again. Then, the e stack will look like this. Well, this time, we will compare numbers 5 and 6, and if they are both absent or both, if they are both, we will check if the values are the same. If we say there is both absent or both, if they are both, we will check if the values are the same. If we say there is both absent or both, if they are both, we will check if the values are the same. If we say there is no problem, we will put in a child node. 5 This guy will make you a child. Yes, you, oo, the raft will become null each time you put more die. Write her, because you have to compare it with this wide guy on this side, and you have to compare this side with this wide guy. So, two. I told you about both of them by subtracting them. Why do you say that the two nodes do not exist? Then, both of them do not exist. This is also correct. Instead, if 2 nodes are small, if they are gathered anymore, will they be put on the stack? That is why there is a problem because they are 2 nodes small. There is no more child nodes, so I don't do 2c because they don't exist. And I removed these two again with a pop, but they don't exist anymore. Then there's no problem, but they say it becomes closer. Well, then 7. There is number 7 and number 4. We will compare number 7 and number 4 as papabo. We have to compare number 7 and number 4 and see if there are both. If both are present, there is no problem with a. If there is no problem with both. But it's not like both of them are missing, so you have to push it. The child node field is number 4, the left eye is also 8, and then you can put number 7, this year, etc., number 9. 4, the left eye is also 8, and then you can put number 7, this year, etc., number 9. 4, the left eye is also 8, and then you can put number 7, this year, etc., number 9. Then, once again, what is it? Is it 2 balls? 8 The volume is combined. After defeating the buffa, once again, either two do not exist or both exist. If both exist, these guys are checking houses with the same value. I did it. There is nothing. It's over. Well, now I have to push, but what? over. It's over. Well, now I have to push, but what? Now, it will actually go in widely. I did this, but the area on this side is 5 on this side, and something on this side starts on this side. Yes, I removed two of these, but there is no problem. But I don't put any more children. And the two less ones at the bottom are also like papa pa. There are no problems with both, but the stack is finished because it doesn't let go of the children. If the stack is pretty, it doesn't spin anymore and you just have to finish it. So far, there have been no problems. They are symmetrical, and then it returns. All you have to do is turn it on. Yes, now you understand. Then, let's solve it with code. Let's solve it with code. Well, first of all, we need to check the base 1, 2, and 3 options. So, if this is young and there is no root, then what? Then, return to rare. Nothing exists. So this is symmetrical. When I check the realism next time, I need stack 1. System Note 2 Stack will store the tree node. I used Newstek and declared it like this. So, after stack 2c, the root is now that. Since this rumor has passed, the route must actually exist. Hudu's left tack n Bush's route will be lighted. Let's do it and keep turning until the stack is like this. The sun is 4, but these two are on the left, and 6 is on the right, so I have to decide now. So, um, after the tree node board, I'll do the left site RFID Roger, and figure out the tree node light CIQ. I'll give it to you, and in the picture I did earlier, the left root, left node, and right note are now included. You have to go in and compare. Left side, me, you, and right side. Is it you? If you're 2 cups younger, there's no problem, but children are saved. I'm not going to do it. What's on this side? There's a part like this where you save the child. So there's no need to save the child. Then, if you don't save 12, you'll continue to go back and become a father. Then, if left side, then. There is a case where the left side goes over and then there is the raft piled up, so the left child exists but the right child does not exist. Then only one side exists. Then, of course, symmetry is not possible. On the contrary, only the right child node exists and the left child node exists. Now, the brides do not exist. If you look at this in a larger scope, if only one node exists between the 6 on the left of the symmetrical one and the 6 on the opposite side, which is symmetrical, then of course, in that case, there will be no symmetry anymore. Comparing the case is, um, the fts side is small, and then the right side is null, so it does this with There is no problem if both populations are first with 2 ducts. If the left side is younger or the right side is younger, the return pearl is said to be not this person, so the left side is 8 and then the raft side and um. If the light site feet are not the same, it becomes a return pulse. Then, I would have compared the three. Then, since these are all done, now Ste will help you with your nodes. Left child note on the left side. Like this guy. Who are you trying to compare to? Then it will become a light on the right side. Then, the next light self mode on the craft site will be like this. The secret guy will be a left child node on the right side. It will be like this. So this is it. This bus until 2. If you don't meet them, return um, so you see it's grown, and if you clean it up, yes, it becomes a return to ru. Um, let's turn it once. Yes, we wet it, and it came rotten. 2 So, the liquid passed. Then, we'll find out right away with the Liquor Shub method. Um, the Liquor 10 won method is first of all the code. Delete them. Well, I think the basic exception check is the same. If null, there is no root, and this is a deep tricard. It is a deep tricard. Now, we are going to create a structure that keeps calling itself in a similar way, so we need to use the method. I'll make one more. I'll make a return and check what's called a deep-sea method. I'll make one more. I'll make a return and check what's called a deep-sea method. I'll make one more. I'll make a return and check what's called a deep-sea tree. Let's compare it and tell it. It's the 4th day of the LF event that gathers the stone garden. That Cree Wood Lighting to sit. I 'll receive the value of the 2nd factor like this. 'll receive the value of the 2nd factor like this. 'll receive the value of the 2nd factor like this. Then, this guy. They will make the first call. Check this guy. Deep tree cacher will put the app boot node in the root and the light child node in the root. So, the final result value of this guy is l. That's why when checking, the metric is 2g. This is done by uploading 2 parts of the type. Then, it is the same here. I compared the three before. You can write it the same way. Well, you are better than the left side eye, and the right side mode is better for both of you. If you put it in return tour, it is all-purpose. Next, you it is all-purpose. Next, you it is all-purpose. Next, you can think of this as the base key, Pie Base Define. So, when you use Liker 15, it will be a condition to go out. Basically, you have to use it of course, and then lfd did. As I said before, this is young or else, it is a light site with the condition of x. What is one of these two? If you say that only one side is null, then of course only one side of Pearl 3 exists. Then, it won't be symmetrical. Then, if both of the benefits are passed, if you come to this point, it is . It means that both exist. come to this point, it is . It means that both exist. come to this point, it is . It means that both exist. Then, compare the foot on the left side and the moon on the right side. If these two things are not the same in the middle, especially the turn pulse, the return pulse will do a verse that does not seem like it, and then here. m 10 things passed, check cement ri, um, just like we did with the butyl side, we said that we should then compare the light side with the light side, and as we prepared to compare this again and continued riding, um, the spelling became a little loose. Why is it so bad, especially? Caterraft star 2 lights Then, select the light sci. You can write it like that. Why does it pass after the sun sets? I'll try running the rung code. The code is oh yes. I went to compile. If you look at it, yes. Oh, did I write light? It's wrong. Ferrite and side. I ran a search on the li trite site and once again, yes, it passed, and then it was accepted. So I tried to solve it in a way like this. Yes, then, with this, the 5-bit code free that is being done today is now Yes, then, with this, the 5-bit code free that is being done today is now Yes, then, with this, the 5-bit code free that is being done today is now complete. I 'll see you next time with a new problem. 'll see you next time with a new problem. 'll see you next time with a new problem. Yes. | Symmetric Tree | symmetric-tree | Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center).
**Example 1:**
**Input:** root = \[1,2,2,3,4,4,3\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,null,3,null,3\]
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Could you solve it both recursively and iteratively? | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | null |
103 | interviewers love grilling you on binary trees and you might be really surprised how many companies have asked this question so you are given a tree and of a level or a Troublesome they want you to Traverse this tree in a zigzag fashion what does that mean let's see what all of this is about Hello friends welcome back to my Channel first I will explain you the problem script bit and we will next we are gonna see what does a zigzag triple cell actually mean and then we will try to implement this solution using a method that we already know it is just a very small trick after that as usual we will also do a dry run of the code so that you can understand and raise your life how all of this actually works in action without further Ado let's get started first things first what do you actually mean by the problem statement in this problem you are given a binary tree and you have to do a zigzag level order travel fill so first of all what do the level of a traversal actually mean you know that when you're doing a level or traversal that means you are hydrating to the first level 4 then 8 and 15 then 23 and 42 and then 16 correct that means you are going level by level right and this is the level of the traversal but in this problem statement you have to Traverse this tree in a zigzag fashion so if you're not aware about it a zigzag pattern looks something like this correct so how do you implement this pattern while traversing on a tree you have to actually follow how The Vig rack pattern is working what do you do over here you go from left to right then right to left then left to right then right to left right so similarly in your tree as well you have to go left to right and then right to left then once again left to right and then once again right to left so you have to continue this until you reach the last level and to return your output you have to return all of these traverses in form of a list that is a list itself so the first level will just have the element 4 correct the next level it has the elements 8 and 15 right but you have to go right to left correct so the next level should look something like 15 comma 8. once again you arrive at the third level and this time you have to travel left to right so in your list you are gonna add 23 comma 42. and once again you're left with the last most level and you enter 16. so you see how we are doing a zigzag traversal of the tree similarly in a test case number two once again you have to Traverse this tree in a fix that pattern so you go from left to right then right to left and then once again left to right and you have to return your answers in form of different lists whichever entire lift in itself so for the first level you just have four for the second level you have 8 and 23 in that order and then for the last level once again you have 16 comma 15. now these two reverts they are complete lifts in itself right and that is how you have to Output the answer for this particular problem for now if you feel that you have understood the problem statement even better feel free to take a shot at it otherwise let us dive into the solution and try to find out what we already know you have this binary tree in front of you and you're asked to do a zigzag level or a traversal correct so as the name suggest it already has level order traversal in it right so if you're new to level Auto traverses I would highly recommend you to stop this video right over here and look at my video on level order trousers first because as an interviewer myself if I have to ask this question I would first ask the candidate about level order services and then as a follow-up question I will ask him okay follow-up question I will ask him okay follow-up question I will ask him okay now what do you do if you have to do it in a zigzag fashion you will understand why so doing a quick recap how does the level on its level actually work you have a queue in this queue you add all the elements one by one right you start off with the root element and that is four you look at four you pop it out and then look at the children of four you can see 8 and 15 are its children so you add 8 and then 15 Right Moving on you will look at the children of eight there are no children so you move ahead you pop 15 and then you look at the children of 15. you feed 23 and 42. so you're gonna add these elements to your queue as well right and this is how the level of traversal actually works once this is complete you will have all the elements like this now if you notice one important thing over here if you mark all the levels this is your first level this is your second level this is your third level and this is your fourth level right and in this traversal itself you can see that two of the levers are already traveled in the correct way right 4 is correct and 23 and 42 is correct right you only need to do a reverse traversal of the alternate levels right because you have to Traverse the second level in the right to left fashion and you have to Traverse the last level in the right to left fashion so in a way this solution is already 50 correct right all you need to do to make this solution completely correct is you just have to reverse these remaining levels so instead of traversing left to right if you had Traverse these elements in this fashion what did you do you arrive at the correct answer right you can see that these elements they have been traversed right to left correct so try to think what can you do about it you have to convert this to this form right and what is happening over here the last element 10 it should come at the first place right and similarly this last element 15 this should come at the first place right and you have to do this procedure for every alternate level the last element should come at the first position right so this tells you something last in first out yes that is the stack data structure so what we're going to do over here is for every alternate level we will take the help of a stack data structure so try to think like this when you are at the first most level do not do anything just Traverse this level in a regular fashion now as soon as you reach the second level instead of adding the elements 8 and 15 to your list add the elements 8 and 15 to a stack instead correct and now once you reach the end of the level just pop these elements and add it back to your resultant Rift right so this time you will first get fourth and then you are gonna get 15 and 8 because they get popped in this fashion right similarly once again just go on to the third level and you feed 23 and 42 which are already correct and then moving ahead once again you see 16 7 and 10. now instead of adding them to your revert lift add all of these elements to a stack first so I'm gonna add 16 then 7 and then 10 over here as soon as I reach the end of the level just pop out all of these elements and add them to your result lift so first 10 gets popped out then 7 gets popped out and then 16 gets popped out so if you notice 23 and 42 are correct and then you also get 10 7 and 16 in the desired order so what did we just do we took the help of the level order trivofill technique and then just did a small change to get it in a zigzag fashion and to achieve this what you can do is you can take the help of a flag variable just keep the flag to false for the first level as soon as we move to the next level just flip it to true if it is true you need to take the help of attack F1 if the level is over just flip the flag again it will be false again so do not add your elements to a stack the level completes once again flip your flag and then now you are gonna again add your elements to the stack instead as soon as your level completes just flip the stack and now ultimately you will have your elements in the reverse Direction So based upon this idea let us quickly do a drawing of the code and see how it works in action on the left side of your screen you have the actual code to implement the solution and on the right I have this binary tree in front of me where this root is passed in as an input parameter to the function zigzag level order oh and by the way this complete code and its test cases are also available in my GitHub profile you can find the link in the description below so moving on with a dry run what is the first thing that we do first of all we create a zigzag lift that will be a resultant output correct next we just do a little housekeeping that if the root is null just return an empty list right now moving on we create a queue now this queue is actually used for your level order traversal we will add the first element root in over here and then we are going to pop element one by one after that as you remember I keep a flank now this flag is false that means for the first level I just need to go left to right correct moving on this is the Crux of the loop and that is our while loop you have to run this Loop until your queue is completely empty right now you just have four in your queue right get the size of the queue next so this size this will actually tell you how many nodes do you have in a level and based upon that you can actually decide that okay now my level is over and I need to flip the flag for right now the size of the level is only one because you only have one node right and that is node four now moving on we create two more data structures first of all is the level and next is the stack you do not have to use both of them but you only have to use one of them based upon your flag value right for right now your flag is false so you run another for Loop and in this you will pop an element from your queue and then look at its children if the value of flag is false that means you do not have to use your stack right so I can simply write down 4 in my list correct now this level is over and it will add the elements 23 and 8 to my queue once this Loop ends you know that you have completed a level what does that mean it means that now you have to flip the flag I flip the flag to true so this time the value of my flag now changes to true correct I add this level to my resultant list and this will add 4 to my final lift over here this while loop will run again because the queue is still not empty you have more elements to iterate upon right this time check the size of the queue is 2 right and you can see that this is the actual size of the level we know that once you have popped two elements you are at the end of the level and check the value of the flag is true so what I'm gonna do is I will pop these elements one by one and I will add it to my stack instead so first of all I add 23 and then I pop this element and then I'm gonna add eight and I'm gonna pop this element but at the same time you also have to add 16 and 15 to your queue because when the loop will run again you still have some pending elements right for now this Loop is over and you get out of it that means the level has ended and you have to reverse your flag again so I reverse the value of flag and this time it is false again and now what do you do your stack is not empty so just take all of these elements of your stack and flip it as soon as you will flip it what do you get you will get 8 first and then you're gonna get 23. so you see what is happening over here right this Loop will run again and this time I will add 16 and 15 to my regular list and since the value of flag is false we do not use the stack and 16 and 15 will get added to my resultant output after all of this is done we simply return zigzag and this is your final list which contains lifts in itself the time complexity of this solution is order of n because you have to iterate over every node in the binary tree and the space complexity of this solution is also order of n because you need some extra space to store all of these elements in a stack and going at the very last level you could have to Traverse it in a reverse order and that is why you need that extra stack space I hope I was able to simplify this problem and its solution for you as per my final thoughts I just want to say that you might be wondering why there are so many different kinds of questions just based on tree traverses well that is because when an interviewer is asking you problems they do not want to hire candidates who have just mugged up some of the solutions and then trying to solve problems because if you just go by okay these are the three standard traverses pre-order post order in order traverses pre-order post order in order traverses pre-order post order in order and level order then you might be able to just remember these Solutions and offer them but if you're understanding how they work then no matter what question the interviewer asks you will be able to come with a solution and sometimes this can be achieved by a very minor tweak so just try to follow how your interviewer is asking you the question if this question is a follower question then there will be a very small tweak required in the original code and try not to change the code too much that will tell you how cognitive you think and how efficiently you are programming so while going through this video did you face any problems or are there any other sorts of tree traverses that you have found can you solve this problem with any other trick with just a minor change tell me everything in the comment section below and I would love to discuss all of them with you as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what problems do you want me to form next I do read all the comments and try to get back to you until then see ya | Binary Tree Zigzag Level Order Traversal | binary-tree-zigzag-level-order-traversal | Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[20,9\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100` | null | Tree,Breadth-First Search,Binary Tree | Medium | 102 |
21 | given two sorted linked lists how can you write a recursive program to merge these two sorted linked lists into one and return the new hat that's today's video let's get into it my name is Steve today we are going through a legal problem 21 merged two sorted lists and today we are going through the recursive solution if when we check out how the iterative solution should be written and how it works feel free to check out the video that we published from yesterday that one describes how the iterative solution works for today we'll focus on how the recursive solution is going to work as quickly go through in the problem description again we merge two sorted linked lists and retain as a new list the new list should be made by splicing together the notes of the first two lists so given this two linked list 1 2 4 and 1 3 4 the final new result after merging these two subtle next to certain linked lists becomes 1 2 3 4 how can we do this so suppose we are given these tuning list 1 2 3 5 now 2 4 6 so first were given access to these two handles l1 and l2 the first line of the matter is going to be more check whether l1 equals 2 now if l1 equals 2 now we just written out to you that's it and also if out u equals 2 now we're just written l1 either one of these two cases right well just written the other name to list these put these two conditions over there and also these two conditions are the base cases for the recursive call so for this recursive function we actually don't need to write a helper function we can just use the main function itself now what's next if neither one of these two Nicklin link to list had notes and now that means we can do comparison right then we can check whether the note point by l1 is greater or smaller than or equal to the node pointed ad by out you so what check if L 1 dot Val is smaller than L 2 dot well if L 1 is smaller than out to you next step what are we going to do is we'll move L 1 towards the right so this is the recursive for merge two lists don't worry if you feel confused or works that's true one by one so but well now let's just take a look at the code I put the code out here first so if L 1 is smaller than L 2 well what do is that will move L 1 towards the right next in the else case what's the else condition house condition is if L 1 dot Val is greater then L 2 dot Val oh you coat you how to tell them because here I put a the example here there are two equal nodes right so in this case 2 is going to go to the else branch this is the final actual code which is going to be accepted then let's analyze how the code is actually being executed so first for any recursive call the computer is going to allocate it a caustic in the computer then let's take a look how the call is going to flow first merge two lists here well just a pump this call into the call stack remember this is the L 1 and I'll tune these are the two notes note it in purple color now it comes in L 1 is not equal to now L 2 is not equal to now so it's not going to come into either one of these two branches what in work come to you is come to into here because L 1 is smaller than L 2 right 1 is small event 2 is going to come into this branch then it will come here merge two lists which is this call see now it's calling itself recursively before it caused this function itself it's using a different parameter it's using L went on next which is this value right which is this value let's see so by calling this we added another function call in on top of the cost ACK on top of this one right this is the second function call at this point this L 1 is this one noted in this colored no next where is this one is going to go in to get into l1 and l2 l1 is here and 1 l 2 is canoes both of them are known now so it's not going there so it's going into the else branch right because l1 equals to L 2 is in the else branch so now it's going to execute this recursive call game now what's going to happen L 2 is going to move towards the right let's see so L to move towards the right so LG moves towards the right is here so now this is the l1 and l2 you we're trying to get the pointer and that's correct that should be appended to out you done next and this out to you is this one we're trying to get the correct one here then we need to call this recursive function right so now we're at the beginning of the recursive call again this is the third one on top of the on the COS tank so we're coming none of them is now so and one is smaller now to a small mmm form right so it comes in here so then fourth recursive call is going to happen this is the fourth recursive call it's going to call this merge two lists then l1 is here now one is pointed and the node with value three it moves towards the right and then what are we going to you l1 is here l2 is here none of them is now so it comes here because L 1 3 is smaller than out to you fall so it comes here now recursive happens again let's see l1 moves towards the right l1 done next l1 moves towards right is its indicated by this dark red color so this is l1 at this point right so we see l1 and l2 5 & 4 so at this point five is l1 and l2 5 & 4 so at this point five is l1 and l2 5 & 4 so at this point five is greater than 4 so it's going to come here right so it's comparing five and fall again what do the recursive call add one more onto on top of the cost AK so it's moving out you this time towards the right so out U is here l1 and when is still pointing at the node with value five recursive call gain none of them is now continued L 1 is 5 m2 is 6 5 is smaller than 6 so one more recursive call this is the last one so you see here now we're at the base condition we're at the exit case right so now we reach the base condition so l1 is equal to now right so finally we got here and when it comes to now what are we going to do which is to pop everything on top of the cost AK off of the cost and that's what's going to happen because we find merge two this l1 here this is the dark green color pointed by this l1 this one is the base condition we're going to return ow - l2 is here this is the light green ow - l2 is here this is the light green ow - l2 is here this is the light green one like green ones here so the results of merge two lists is written l2 is here so we're written l2 2 L 1 dot txt this is what's gonna happen we're gonna return L to return here after we pop that off this l1 is gun and we assign l2 is here we sign l2 to l1 done next this is l1 done next so this link is cut off and the new link this L want our next is next pointer is pointing at the number the node with value 6 this is what it is doing right so then we return now we just continue that one is popped off of the claw stack well execute this one remember this one is l1 and l2 by this cutter by this dark red this l1 and light green is here that green seen so these two will compare which one is smaller the node with value 5 is monitor so we'll assign this one to you how to do next this is out until next we're trying to solve we're trying to find the node with the value that should be appended to out you'd our next how to do next is here next step is going to cut this link off and append it to the node with value 5 right that's what's going to happen then this node is popular off of the caustic we now have l1 and l2 you over here this is the one that will return next continue that one is popped off of the stack now we're trying to find between this l1 is here this L 2 is here we're trying to find the one which one is smaller this one's smaller our two is mana right so how to this monitor then which is to use alt you to append this out to you l1 done next this l1 is here it went down next so that this link used to be thrown from three to five is cut off now three the next is pointing to you the node with value 4 next that cost AK is popped off now we're at l1 and l2 is here l1 light green and else you this red color here which one is smaller 3 is smaller so we'll use this one which is the link here this link we used well assign l1 to be pointed by this and our next now this merge stylus is l1 and l2 so now these two colors l1 and l2 now here l1 and l2 which one is smaller l1 is modern so assign l1 to this out you indicate by this purple color this Alton's next so this one is cut off and then assign out to you this purple color is next pointer to this l1 right this one will just continue one more merge two lists this l1 and l2 u l1 is near l2 is here and what a sign is this out to you become L 1 dot next what's the final one we'll just pop that one off of the call stack the final one is return the result we're just going to merge l1 and out to you so which one is smaller l1 is moderate boom that's the final result I hope this walk through this step-by-step hope this walk through this step-by-step hope this walk through this step-by-step walkthrough of this example of merging two sorted linked lists will make sense how the recursive function actually work in computer programs after you write this recursive call okay and then let's talk about time compact the time complexity of this program is o M plus n m and n are the lengths of the two given linked list because we anyway we have to traverse through every single node of the given two linked lists so time complexity in studio Oh M plus N and space complexity this one is going to be Oh M plus n as well because we have a cost act remember here this cost back for this example it adds up it adds all of the value on top of the cost AK is going to use Oh M plus n extra space that's it now we can quickly put this recursive code into the year until a code the on line judge that's let it seen if so first the to base conditions if L 1 let's see if L 1 equals 2 now what is the return L to you and if L 2 equals 2 now which is written L 1 in all other cases which means neither l1 or l2 is now so what we'll do is go safely access to their values if L 1 dot Val is funner than L 2 dot Val what we'll do is that which means the node in the current linked list of 1 is smaller so we'll move l1 towards the right in that case this is the code let's see L 1 dot next and how to you doesn't need to move because L 2 is bigger and will return L 1 in Ellison else there are two branches one is two cases one is L 1 dot Val equals to how to novel the other is L 1 dot Val greater than L 2 dot well in that case we'll move L 2 twist the right marriage L 1 l 2 dot next then just written out to this is the code you can put the equal sign over here as well it doesn't hurt anything because the tune those are you know let's just hit submit and see all right also accepted that's the entire walkthrough of this recursive function if you have any comments questions just leave me in the comment section below and also don't forget to hit that like button let's do any help a lot and also please subscribe to my channel that's gonna help the channel to grow I really appreciate it and don't forget to hit the little bell notifications so that each time when I publish a new video you're not going to miss out on anything right now we're going through a link to list series of little problems to help people better prepare for the upcoming coding interviews and then after this we'll go through a tree series and then we'll go through combination of different data structures and algorithms so you want to hit subscribe button and tap the little bear notification I'll see you guys in the next one | Merge Two Sorted Lists | merge-two-sorted-lists | You are given the heads of two sorted linked lists `list1` and `list2`.
Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists.
Return _the head of the merged linked list_.
**Example 1:**
**Input:** list1 = \[1,2,4\], list2 = \[1,3,4\]
**Output:** \[1,1,2,3,4,4\]
**Example 2:**
**Input:** list1 = \[\], list2 = \[\]
**Output:** \[\]
**Example 3:**
**Input:** list1 = \[\], list2 = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in both lists is in the range `[0, 50]`.
* `-100 <= Node.val <= 100`
* Both `list1` and `list2` are sorted in **non-decreasing** order. | null | Linked List,Recursion | Easy | 23,88,148,244,1774,2071 |
179 | hey guys welcome back to my channel the tech coders and today we are going to solve problem number 179 that is 179 of read code largest number okay let's understand what question Isa saying to us so see question states that we given a list of non- negative integer nums and a list of non- negative integer nums and a list of non- negative integer nums and we supposed to arrange them in such a way that the resultant answer is maximum okay as I can see in my constraint that the length of this given input array can be up to 100 okay so that number will become really very large so that's why we are supposed to return a string instead of an integer okay now let's try to understand what exactly question is saying to us with an example so now see this is my second test case which was given in the question so we are supposed to arrange them in such a way that the resultant should be maximum resultant should be largest so after seeing this example I can say that the resultant answer will be 95 3 4 3 0 okay so this is my answer but now the major question is that how we can approach to get this as my answer okay so now you may be having one thing in your mind that as I'm supposed to return a string so let's do one thing that I'll take each of these elements in my string and after that I'll perform sorting okay let's try to go with that intution okay my string will be 3 0 3 4 5 9 now after sorting it will be like this 9 5 40 now you may say that this is greater than this okay but no that's not the case over here you can see that four is coming before three but in my given array four was coming after three it was 34 and over here it is 43 so this sequence can't be changed okay you may change the sequence of this individual element but this sequence can't be changed okay I'm saying that you have 20% right over here as they're going to 20% right over here as they're going to 20% right over here as they're going to perform sorting but that sorting is not going to be a traditional one again over here we are going to use the custom operator so now let's move further now see I'm going to perform sorting over here okay so now while sorting what we'll check let us suppose that this is my a and this is my B okay this is my a and this is my B so while sorting what I'll check if a + b is greater I'll check if a + b is greater I'll check if a + b is greater than b + a or not okay this has been than b + a or not okay this has been than b + a or not okay this has been converted into a string and what will be operation over here that is 330 is greater than 303 or not and if it is greater then we're going to return true that is you sort them now see over here I can see that 330 is greater than 303 what will be my resultant one it will be like this that is 3 will come first and after that it will be 30 now we'll come over here now you may say that this is my a and this is my B again we'll perform the same thing that is if 334 is greater than 343 or not okay now I can see that no this condition is false so what I'll do I'll Place 34 over here okay now I'll move further now my B will come over here okay again what we'll do this is my a and this is my B again we'll do the same thing that is a plus b that is 35 is greater than 53 or not okay this condition is false what I'll do I'll Place five over here now similarly my B will come over here this is a and this is B again we'll check the same thing 39 and 93 this is again false okay this is again false what I can say nine is going to come over here n is going to come over here now what I'll do I'll have my answer the string and over there I'll append each of this elements like this 9 5 3 4 3 okay now I can see that I'm having exact same answer which I was getting over here okay now let's see again okay so what we were doing we were taking two string at a time and over there we were checking if a plus b is greater than b plus a or not okay and if it is greater then we are putting B after my a and if it is false then I'm putting B before my a that is over here it was true so 30 came after this and if it was false then 34 5 and 9 okay you can see for each of these cases now you may be having a question that why a is not changing why a is constant over here if you want you can change this a over here also now see what will be my case it will be 3 4 whether it is greater than 3 43 0 so I know this condition is false and you can see that 34 is coming before 30 okay now you may be having query that why what if this will be my a and this is my B what will the situation over here that is 349 is greater than 934 or not okay so again this is false and I can see that 9 is coming before 34 okay so this was our approach now let's move to the coding part so initially we'll make a string answer which will be empty now what we are doing we were simply sorting it out so let's do that with a custom comparator okay so now I'll write a code for a custom comparator I'll get two values from there in a and b but now see what we doing at that time we are checking if a plus b is greater than b plus a or not okay so at that time we were considering this A and B as a string okay and now we are getting this as an integer so we'll come so we'll simply convert it okay we'll return if my string of a plus my string of B is greater than my string of B plus my string of a simple okay now I'm done with the Sorting part after this I'll each after this I'll add each of my elent into my answer simple I is equals to Z uh let's do this that is answer plus is equals to two string I okay you're done with this now we'll simply return this I'm saying that this is going to run for this cases but there will be a case where our code is going to stuck okay sorry it's a spelling mistake yeah it is running successfully now let's try to submit it so now see this was the case I was talking about okay now let's try to consider this one so now see this is my input so even after taking all the possible combinations and permutations over here my answer is going to be equal to zero okay so now see but I can see that my answer is returning two zeros over here so now I'm going to write a case for this that is if the first element of answer is equals to Z then simply return Z or else my original answer okay so now this will run so yes now we can see that our code had been successfully submitted okay so this was the solution guys I hope you understood all the logic and the concepts over here and if you're having any doubt then just feel free to comment over there we'll definitely help you to come out of it okay so like our video subscribe our Channel and share this with your friends who are participating in all this code fores and Lead code rounds and all okay so thank you for watching and have a good day | Largest Number | largest-number | Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
**Example 1:**
**Input:** nums = \[10,2\]
**Output:** "210 "
**Example 2:**
**Input:** nums = \[3,30,34,5,9\]
**Output:** "9534330 "
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 109` | null | String,Greedy,Sorting | Medium | 2284 |
172 | so this is factorial trailing zeroes lead code one seven two and the question is given an integer and returned the number of trailing zeroes in n factorial so in an example like say we have three factorial which is three times two times one and that gives us six and in this case we have no trailing zero and we would return zero in the case of four we execute four factorial which is four times three times two times one equals so 24 also no trailing zero and in the case of five we execute five factorial which is 5 times 4 times 3 times 2 times 1 which would be equal to 120 and in this case we would return 1 because we have a trailing zero here so the most intuitive way would be to attempt to somehow compute the factorial and then I count the trailing zeros true so like wow loop or something but that would be a bit slow for the purposes of discretion like leet code would not accept that because it's too slow so a better way that we could approach this is to really think about what creates a trailing so um why does five-factor you have a so um why does five-factor you have a so um why does five-factor you have a trailing zero we need to understand that to have a trailing zero we need to somehow create to somehow have a number that we multiply by ten so in the case of five factorial it's equal to 5 times 4 times 3 times 2 times 1 which can also be seen as 5 times 2 times 3 times 4 times 1 and if you notice here 5 times 2 is equal to 10 so good replace this with a tan and this is why we have a trailing zero here and in the case of 4 factorial 3 factorial be tones and the reason why it starts of 5 factorial is because the factors of 10 are 5 and so these are only two numbers that end creates and when multiplied together and 5 factorial just happens to have both of them so since 5 factorial has those numbers 6 factorial 7 factorial and greater numbers would also um contain 5 and so and would similarly have trailing zeros so now that we understand that we need to multiply a given number by 10 so have trailing zeros how do we count them we could count as zeros by used by using a little trick real year where we essentially divide whatever number given so we are given and over N and if we divide n by five then we would have the UM the number of times that like five goes into N and for every five so let's say the number of times five goes into and for every five there is a pre-existent pre-existent pre-existent so because five is greater than so um so we could use this to kind of count um okay so we have this number of five and since 5 is greater than like so for every 5 gm what exists whose trailing behind which when multiplied equals ten but this doesn't take into account the case of like the squares and cubes of five like 25 is equals 5 x 5 and me if we were to just return n over 5 its wouldn't say you can account the other five being made so we also need to so divide n by 25 through account for it for the extra 5 being made and similarly we would need to divide and by 125 the dependent on the number so for number is less than 125 we would end up getting an over 125 to be equal to 0 when rounded down and that's exactly what we would need so how do we approach this we could approach this by let's say the function name is trailing zeros and we taken an integer and we return an integer with the number of trailing zeros we could go if n is less than five that's a base case return zero then we could go and count equal to zero then we could create an integer Nam echoed 5 and the use of Nam is to divide and at every point in our upcoming loop Wow so all n is greater than or equal to norm we could go counts plus equal to and over now so this essentially finds out the facts is like we are I explained where we go n over five and we keep track of those factors and we would also want to go n over 25 and so forth to the value of n is greater than our arm device or I guess so in this case 25 and we could go norm x equal to 5 and we could return counts so we keep multiplying known by five so here we could get the square cube fourth power fifth power of files and onto n surpasses this we would be fine and over now I'm here automatically gets the floor using C++ wishes what I gets the floor using C++ wishes what I gets the floor using C++ wishes what I write N and so yeah this is the factorial trailing zeroes lead code one seven to use and C++ seven to use and C++ seven to use and C++ thank you like and subscribe | Factorial Trailing Zeroes | factorial-trailing-zeroes | Given an integer `n`, return _the number of trailing zeroes in_ `n!`.
Note that `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`.
**Example 1:**
**Input:** n = 3
**Output:** 0
**Explanation:** 3! = 6, no trailing zero.
**Example 2:**
**Input:** n = 5
**Output:** 1
**Explanation:** 5! = 120, one trailing zero.
**Example 3:**
**Input:** n = 0
**Output:** 0
**Constraints:**
* `0 <= n <= 104`
**Follow up:** Could you write a solution that works in logarithmic time complexity? | null | Math | Medium | 233,809,2222 |
392 | hi everyone welcome to my channel today is a day 9 of Joomla coding challenge and the problem is subsequence so let's see the problem statement given a string as I'm a string T check if s is the subsequence of T a subsequence of a string is a new string which is formed from the original string by deleting some character or none of the characters without disturbing the relative position of the remaining characters let's for example we have a string AC e is a subsequence of a string ABCDE how if we delete B and E and the relative order of AC in original string is same and it is matching so it is a subsequence while if we have a EC which is not because is if we delete B and D but the relative order of E and C is reverse in our string so how can we solve this problem so let me explain the algorithm here what I can do I will take a pointer to pointers I will solve this problem but with the two pointer help so here so we will take a two pointer one point that I is for s and J is for T then what we can do we will check the characters like if character of s of I if s dot carrot of I is equals to P dot carrot of I J this means we have to increment both the pointers like ie plus and J plus and if we don't get this not equal other it so this if this is not equal just like as dot care at I is not equal to as P dot care at J in that case we just increment that pointer J plus not the I plus because we have to find all the character in E string as in the correct string P in the same relative order so this is what the algorithm let me walk through the given example 1 so here is the example 1 we have string as t ABC n this is the example one and let me start like ie initially 0 and J is also initially 0 so we will check better as of G character 0 is 0 so yes we have equals to be equal sway in SN P so in that case our ie will be become 1 and J will also become 1 and the second call what we can do we will compare the second character of for string s and T so we have B is not equal to H so in that case we just increment J so I is again the same one and the J is 2 now we reach you on the 1/2 now we will compare be with if V is 1/2 now we will compare be with if V is 1/2 now we will compare be with if V is equal to V yes V is equal to e in that case we will increment both the pointer I as well as J so they will become 3 now we will compare the character in s at to index 2 which is C is equal to character in T at index 4 is G which is not equal so we just increment J naught I so I is again 2 and J will be incremented by 1 if we come for again we will compare C's equals not equal to D in that case also we just increment J will become 5 so here we have C equals to C so this will be why you become 3 and J will become 6 so now we reach at the end of the string so once we reach at the end of the string of either as or t4s case we will just compare whether s index is equal to the a short length if we reach the end of the string as in that case we found the subsequence of s in t so we have to result is equal to true otherwise if we don't get as if this is not if I not equal as or length in that case we didn't found all the character of s in T so this will be written false so the result will be false here so let's start the implement so let's first start the iterative approach so the idea was very simple so we need two integer which will be a pointer like I is equal to 0 and integer is equal to 0 and then we will use the while loop so while I is less than as dot length and J is less than T dot length if s dot care at I is equals to P dot care act J then we have to increment both the pointers so here I plus and in Al's case we have to only increment J plus 4 so J will increment in both cases here so just this is the condition so in the end we just simply return if I is equal to as dot length or not so this is our code it--it aversion so let's compile the it--it aversion so let's compile the it--it aversion so let's compile the code so code is compiled and we are getting expected answer let's try some custom asked is like instead of VB hey vary and he is not in the second T string so we should get false let's try this so we are getting expected let's submit our additive solution and see whether it is accepted or not so it is accepted this is very simple solution I take the based on two pointers so the time complexity of this solution is simple often we just scanning that and even size of any the size of any max of SMT and this is we are using just constant and the space complexity is constant so that's I take solution so let me explain why to implement recursive solution as well so this while loop can be converted into the recursive solution so I'm removing this code for now this one and I will show so I will show you how can we implement the same code in the recursive solution esta so in the course a we will call a recursive method is subsequence recursive which is also a similar definition and we will pass the string as empty and the index is zero and G zero and we here we will implement this method let me copy this section and here append the index is basically pointer for both n ty n integer and we will compare if I is equal to s dot length this is the our base condition length then we will just return true if P if J is reached T dot length in that case we didn't found subsequence so we have to return false so this is our base case and otherwise we have to return if s dot care at I is equals to P dot care at J then we have to return increment we bought the pointer so let me take this call here and we will increment about the pointer by 1 I plus 1 and J plus 1 otherwise if both character are not equal then we just increment the J pointer P pointer basically so J plus 1 so this is our because of implementation let's compile the our code and see whether it is bus running or not so it is getting compiled and we are getting expected answer let's submit our recursive code so the recursive solution is going on and it is accepted so this is a recursive implementation of the same algorithm so if you see we have another problem here like follow-up of the same problem so like follow-up of the same problem so like follow-up of the same problem so let me read this follow of the statement if there are lots of incoming s say s 1 s 2 s K where K is greater than equal to 1 we and you want to check one by one to see if T has the subsequence in the scenario how would you change your code so if we see our current approach the current approach of let me revert this one and get the item code again back so this is the height relative solution what we did we just scanning all the character of T and s and this so the time complexity of this twin for one is string s is open but if we get many string and we have to compare let me write down the steps here so for follow-up so this is for follow-up so follow-up so this is for follow-up so follow-up so this is for follow-up so for follow-up we are getting too many for follow-up we are getting too many for follow-up we are getting too many like s 1 s 2 and so on we are getting tails of K and we're case where K is very big this is 1 million so let's say s has average length so average length of s is let's say L and length of T is T and length and the number of for string number of all as is K so if we compare over all the string based on this approach so our algorithm will go off of K of n we have to compare and the size multiplied by the size of as the size of s is and so this is what the complexity of our if we go with our up to pointer approach but what we can do for improving this like we know that E is fixed here so T is fixed so we can do some pre-processing so pre-processing on P pre-processing so pre-processing on P pre-processing so pre-processing on P pre-processing on T and then is like we pre-processing on T and then is like we pre-processing on T and then is like we will form some kind of look up so that we can easily check the character like particular character of s is there so for pre-processing we will is there so for pre-processing we will is there so for pre-processing we will fill the characters of T in character comma list of index all the integer in the integer so all the we will do the mapping of characters based on their index so this will be the mapping of so character of T and the indexes in the T string so once we process this in the map then for searching as what we can do we will just simply check for the each character we have to check we will use the binary search to find out whether the it is exist that character in the string the first we will check if character map dot contains the character or not Pinsky for the current character of s dot carrot is so kept a tight so this is let's say I is a loop for the character and is a length so by using this we will do binary search for the S character in P using for index once we got that index of that character we will update that character index let's say this is called previous and next so for next character for next ex character we will look such until after 3 plus 1 so this will be research all the characters of s in P so for making video sort I already noted down the court I will show you the code and also share that code in description so here is the code so if I can explain you this is what I explained you we will use the map and do the pre-processing here based on the pre-processing here based on the pre-processing here based on the characters of T and the index in the T so this is a pre-processing part here so this is a pre-processing part here so this is a pre-processing part here so we will iterate on each characters of T and fill in the map if it is already exist we will append the list otherwise you will add the new list and add that index of that character so this is a pre-processing part and now this another pre-processing part and now this another pre-processing part and now this another part we have to search this - like whether we have to search this - like whether we have to search this - like whether the S is exist in T or not so for that we will use the previous starting with management index and iterate through all the characters of s so this is what and we will check if particular if any character not found is not found straight forward we will return true false here because we didn't found or some particular character of a sim T so this is the condition for that another case is if we found the character then we will look for the index at which index that character exists varies on our previous so we will do the binary search by passing previous so the character should be after the previous index so we will go through is and we will pass the list in the winery hana so this is the binary search implementation easy so here we will check if our middle character index is less than index then we will update the start to the mid plus one and if our character mid index is on the left side then we will reduce the end of mid minus one and in the once the while loop is exit okay then we will check if he start is reached to the end of the size of the list death means we do found the any character which is on before the Lindex after the index so in that case we will return the minus one otherwise we will return that index value of that found character in te string so once we got this previous we will check if we found the minus 1 that means we didn't found any more which we are looking for we will return the pulse here if we found otherwise we will update the previous for the next character and do this until this loop is exited once if this loop is again successfully we will return the true here so this is a simple implementation so the time complexity of this solution let me explain is the time complexity of this solution like if we go with the old approach that I am going to elect lkn so the time comes he of this solution will be of L is the size L is the string length as of length and K is the total number of this thing and here is a log of M because we are searching is character so that's it if you have any concern please say post the comment I will respond and like the video and subscribe my channel for future videos thank you | Is Subsequence | is-subsequence | Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_.
A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not).
**Example 1:**
**Input:** s = "abc", t = "ahbgdc"
**Output:** true
**Example 2:**
**Input:** s = "axc", t = "ahbgdc"
**Output:** false
**Constraints:**
* `0 <= s.length <= 100`
* `0 <= t.length <= 104`
* `s` and `t` consist only of lowercase English letters.
**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code? | null | Two Pointers,String,Dynamic Programming | Easy | 808,1051 |
1,001 | hi so welcome to this problem number 1001 greedy rumination it's a lead code hard problem but uh it's like i would not put this in the hard category it's medium level problem it requires a few insights but it is not as usually a harder you know such a hard problem like we do in the generally in this playlist so the question is uh you know that you are given a grade of size n cross m and itself the grid of the grid has a lamp that is initially turned off right so you have these n square lamps all of them are arranged in this n cross n grid and each of these grid has all the lamp the lamps are turned off right you also give an array of lamp positions lamps where lamps i roi indicates that the lamp lambda grid row i this i throw it column is turned on when a lamp is turned on it illuminates itself so basically you are given these uh this array and you know each of the array contains this to the tuple and row column so in that row that column the lamp is lit right now when the lamp is turned on there is this other condition also what is the other condition when you turn the lamp on it illuminates its cell and all other cells in the same row same column or diagonal right so if i let's say if this is the grid and i turn like this lamp a lamp here up all the lamps which are here all the lands which are here up down and also sideways right all of the lamps would be lit because i lit this lamp up right so this is the catch this is the interesting part that you when you have a lamp which is on it illuminates all the other rows in the same like all the lamps in the same row column or diagonal right so this is the setup you are given many of these uh you know this array lamp each of them your indicates which lamp is on so it itself is eliminated and all the column row both of the diagonals are illuminated now the question is that you are given this query array right where queries of i is also a row comma so i'm actually this is a query array in which there are different queries it's requiring the grid and a query is like row comma column and for the ith query you we need to determine whether the you know the lamp at row i column i is illuminated or not right not just that what it says is that after answering the ith query you need to turn off the lamp at grid row column uh you know that role which you carried if it was on and uh basically it's a digest and lamps are also on if they exist so basically every cell would have you know one two three four and then five six seven eight like eight neighbors every cell will have so all of the eight neighbors you have to turn off right so if the uh if the lamp is on right if the lamp is off then you don't need to do anything right so what are we doing for every query we are first saying telling whether these like lamp is on or off at that position and if the lamp is all on at that position you switch off the lamp and you switch off all the lamps which are in the it like the 8 vicinity lamps adjacent to that lamp should be one if the lamp of the ith query was illuminated and zero if the lamp was not right so this is more like a sequential problem so first query it does not only query the grid but it also affects the grid so it changes what is on and off in the grid and the next query the it affects it effectively so on and so forth so it's more like a dynamic uh you know querying problem so where you know if this was a bunch of queries what we could have done is we could have really you know made some arrays stored the states of the update and then you know just sequentially queried everything but this is not about sequentially you have to store everything in such a way that while you are querying you are going to upgrade it so that the next query would be possible right so that is the like the tricky part that is the challenging part uh here so let us see if see a few examples right so this is the first example let's zoom in a bit to see yeah so uh you know in the first example this is the configuration of the grid and there is this is the configuration of the grid and so we'll see what the input is given the input is like input is this n input has n is equal to 5 so it's a 5 cross 5 grid so it's a 25 uh you know bulb grid and at least this range in this way so the on lamps are 0 comma 0 and 4 comma 4. so now you see 0 comma 0 is the lamp with so on so when you say 0 is on it switches of all of its rows and all like all of its columns and all of its rows and also all of its like right yes so this is switch on and this is which one and then this is so this is when you look at the first one zero comma zero now also four comma four is also added so what is the four comma four so this is zero comma zero this is one comma one this is two comma two three comma three this is four comma four so four comma four this lamp will illuminate this row this column and the diagonal now because of this these things are already illuminated so we just keep them on right so that is not a change so the uh queries would be uh you know one so uh okay so when we do like one what will happen is that this is so we want to switch this off so this is off and so the answer vector is one because the at this position at one uh this lamp was already on and then we switch off this one you switch off this one both these are already switched and you switch off this one now one comma zero right so we're looking at the first row and the uh basically we're looking at the first row and we're looking at the second column so we're talking about this lamp now this lamp was actually switched off because of the last query so we don't need to do anything we just return a zero because this is switched off right so you see in the first query it was something else and then it updated the second query and we were able to return right so same happens so this is just gives you this example that you know in this rectangle it is this is the same thing that's right so you know we have to start programming with this situation in our hands right so uh the interesting part sorry i did not want to print anything yeah so i do not want to print anything uh the it's i just placed that by mistake now let's look at this problem now the interesting part is that we need to have a proper data structure which we would use to do the updating right so the key observation we have is we have to store the positions of the lamps such that they are easy to update now if we let's say if we made a set or made a vector of vectors and just stored the lamp positions individually so like for every uh you know lamp which is on we just go iterate through the rows columns and the line numbers will be stored them manually in the array what the biggest problem that would have happened would be that you know if you wanted to do the update the updates and the queries would not be efficient right because the query might be efficient you would say whether the grid is on or off but if you wanted to update it if there would be a long procedure where we actually you know iterate through the entire vector of vectors we see there are a few conditions satisfied we determine what is around and uh do it so also this is another added challenge that we need to find out uh to find a way to iterate through the diagonals right because uh you know x and y coordinates is easy but how do you actually iterate through the diagonal so all of these are actually questions one can ask and one could pose so the natural way of thinking would be that rather than uh you know storing this as individually in a vector of vectors the position of the lamps like what you could actually do is you could just store the x position and y position and query accordingly right so the key idea is to uh store just the x position is like the row and uh y position which is the column position and then query from there now how do you do that so for that i so x position y positions are enough for querying whether they're in the same column or in the same row but how do you even look at the problem of the diagonals so could you represent the diagonals with this x and y the answer actually turns out to be that yes you could actually you know do that let's go on a whiteboard and see how you could actually you know accomplish that so um we i just like erase the screen so i assume we have this square grid of uh certain size for example it's four cross four right it's four cross four and uh it's a little bit abnormal but just forgive me for that yeah so this is this four cross four grid and what we have here is uh let's write the let's write the individual coordinates of these things so this is zero comma zero this would be uh you know one comma zero depending upon you know row or like the first one was like row right so this is a column so this is one comma zero depending on whatever you want to do the observation still holds it's two comma zero this is three comma zero right uh this is zero comma one this is 0 comma 2 this is 0 comma 3 right and so on and so forth this is 1 comma 1 this is 2 comma 2 this is 3 comma 3 um this is one comma two this is one comma three this is two comma one this is two comma three this is three comma one three comma two now like in this setup let us uh you know figure out how do you query like let's say a certain so for example you have this uh you know this lamp is on so you save zero and you save one now when you save zero and when you say one what happens is that any of the uh you know any on any of these which will have the x coordinate as zero they would be lit right so you don't need to figure out then you don't need to store all of these values individually if you just stored this 0 which means that if this is on anything with the left side as 0 anything with the row value as 0 is already on so you just need to store this zero engine check for it the second thing is anything this entire column will at this entire row would be so anything with the position one in the right side which is the you know column position rotation whatever in the right side position these things would be uh these things already so we just have to see we have to store the x value we have to show the y value and for any incoming uh query check if we just check the x and the y values and if you've seen things before then i feel we are done right that is what we have done with the rows and columns but the question is what about the diagonals so now diagonals are of two types so diagonals which go from here to here and the diagonals which go from here to here right now the diagonals which uh you know go from this side to this side they are called the primary diagonals right they are called the primary diagonals and these are called the secondary diagonals you know which comes from this side if you throw a pattern in the primary diagonals this entire thing becomes very easy so take any primary diagonal let's say we take this diagram this primary diagonal here right so what is two plus zero it's two what is one plus one it's two what is zero plus it's two so the x plus y value in the primary diagonal would remain the same take any primary diagram take this one three plus one is four two plus two is four 1 plus 3 is 4. so the x well like the x plus y value in the primary diagonal remains the same now take any secondary diagonal for example let's say this one this big secondary diagonal wait let me use a different color to say this is let's say we're looking at this big secondary diagonal now in this big secondary diagram the diagonal what we do is we just subtract the values what is 0 minus 0 and 0. what is 1 minus 1 it's 0 2 minus 2 it's 0 3 minus 3 is 0. so the secondary diagonal would preserve x minus y right so if you want to check the row what you need to check the first value if you want to check the column you take the second value if you want to check the primary diagonal you check the first value plus the second will get the x plus y if you want to check the secondary angle you check x minus y you could like verify it with any one let's say this one 0 minus 2 is minus 2 1 minus 3 is minus 2 take any of them and lower it will work for an n cross and grid and it is actually not that hard to show you could actually use a piece of pen and paper and just see once we have done this i think the problem is now extremely simple right let's do this uh together now so we have this vector of int uh let's call it answer right and it's currently it's where you know you'd return the values now vector of interest answers now if for if any case if n is equal to 0 what we do is we just return this empty list because there is no you know bulbs to check if this is not the case then we have interesting things we what we do is we would want to store the x values and the y values uh as unordered maps right on our map anode and map of int comma and write the two values x and y are like and in comment let's call this x then there is this unordered map of why right it's just uh we also need to have a another map for the primary diagonals to check the x plus y so we have another map of intent of let's say p lag right and we have an unordered map for the secondary diag cool easy we also need to have a set a simple set which would uh store uh for example it will store which values there are so the well the like for example the if you this was row comma one so you actually also need to store the input queries so that we can then remove them from the set so row like the lamps where are all the lamps so to see where all the input lamps are right what you do is just you do pair of indent so it's just a set of pair of int and uh that's it we call it let's say s that's a good name for a set why is this not being indented properly because if this if there is an indentation problem in lead code always remember that you might have done some text here so that's a good hint to take from lead code right so set pair parent s this is good now what we want to do is we want to iterate through this lamp vectors so for uh uh you know auto lamp in lamps what we need to do is like it would be a 2d like it would be a two element array now you just say x of lambda of lamp of zero so the first value of that you just say plus because i've seen like the unordered maps x and y will store how many times have i seen uh this x to be like this x in my input array so uh you know you'd see where this is used in the future but it is like if i have completed all the instances of x when x was supposed to be you know plus then where x was supposed to be there then i mean that this entire row is empty or that element is empty so we will have a look at that in the subsequent programming so for the white lamp we have seen why for the for you know once we also need to see where we have seen the primary diagonal so we do the b diag and predict is of course lamp of 0 plus lamp of 1 and we would want to do plus we want to increment that and the secondary diagonal is nothing but the same thing with a minus right with a minus uh we would also want to uh secondary diagonal you also want to insert uh the values in the uh the lamp values in the s you know set so you just do s dot insert uh have the curly bracket rotation lamp of zero comma lamp of one right done so you when you do this what happens is that this entire loop will run and it will increment this x on map y map diagonal maps for a diagonal secondary triangle and it will increment so that every time we see an x and y every time we see a point which is illuminated we know where like you know what the others illuminate just by storing the instances in them so now this is done now for auto query queue in this queries what we would want to do is we would want to let's have some real estate what we would want to do is we would want to do q of 0 q of one so if you want to first see whether uh these things are in you know whether this queue is actually matching in the lamp so how do you do that you just do uh if for example uh let's say if we just want to check whether this q 0 q of 1 which i like the x's and y's do they belong to any of these uh yes so for that what you do is uh you just do if check if x of q of 0 of course if this is greater than 0 or like if any of the condition holds if it's in the row of this one if it's in the column of this one right uh is greater than zero if it's in the diagonal of uh this one p tag of uh q of zero plus q of one if it's in the diagonal of something it's greater than 0 or if it's in the secondary diagonal of something of a q of 0 minus q of 1 if it's in the secondary diagonal then we can say that uh if any of this is true what we do is we know now we now know that this uh variable is now like now this lamp is actually in the rain so the lamp is on so if you know the lamp is on we just do answer.pushback answer.pushback answer.pushback one because finally what we need to do is we need to return this unsurveilled we not only do that we now have to go iteratively and in this data structure proper manner we also have to remove the elements which are around right so how would we do that so what we would do is like for let's say into j is equal to minus 1 from j is equal to minus 1 to j greater than equal to 1 j plus so from j minus 1 0 1 uh also do the same with k so it's like that position one less one more right for uh if k is equal to minus 1 uh k greater than equal to 1 k plus this is also v like you know for this variable in minus 1 0 1 but stuff slightly fancier and more convenient doing it is here so okay in this case what you would want to do is we'd want to have this variable called uh all of these variables this variable called q so the q x value of the q so what is this x value of the queue it's like the q of 0 plus its neighbor so it's j the x this side and this side right so in q of y is nothing but q of 1 right the y value of k plus k so it's like the for is like the vertical neighbors right iterating through all the vertical levels now in for all of these if what we need to do is if you need to check if qx is greater than equal to 0 right if qx is greater than equal to zero and if qx is smaller than n because that is the size of the grid and if qy right is greater than equal to zero and if qi is smaller than n and what else do we need to check uh do we need to check the primary diagonals and all i don't think so because this is like checking whether like whether it's valid or not and if we see that uh it's like this q x q y they are also like illuminated like in the original illumination grid right so yeah so and uh if they are in uh the initial lamp place because to check the whether they are in anywhere in the surrounding you already put them in the if condition and if they're in the initial uh you know this list so s dot count is uh count of what count of q x comma q i is greater than zero that is already like it's and so it will be a binary variable by itself and if this is the case then what we would want to do is you would want to do s dot it is of uh qx qy right this variable and then uh we want to increment whether like we want to delete them right so we're going to decrement these x's and y's so that next time it checks in a proper way checks it checks in a proper way so i decrement x of qx by minus i'd want to decrement a q y because like i'm like switching off this lamp minus uh we'll also want to switch off the primary if the primary diagonals so like we're not switching all the primary diagonals we're actually checking if they are switched off we're gonna like just delete them so that they don't come in the next check right qx plus qy we just do minus yeah we do s diagonal you just do q x minus q i and you just do uh minus here so this all of this will actually take care of the fact that um the for the next time the eight around it would be subtracted right and uh if we so this is why we are doing plus we are just not noting down you know whether we have just seen it once and then it's on for all we're also doing plus was we're actually counting every instance of where there is also a common thing so even if one of the common it gets in because of the second one which is being lit all others are being lit right that is the actual key part and that is why we are incrementing everybody one by one right in all of them so that's it we are done with that if this is the case then you know push back answer one if this is not the case for example if this is not the case then you just do an else block and just say that uh answer dot push back zero because it means that this condition is not satisfied it means that the lamp is off and if the lamp is off we don't need to do anything now and once that is the case we just have to return answer let's do that let's just return all right so this is i think the bracket for the function we finally once we do we have done this we finally return the answer right the answer vector yes so let's run this code and see what happens accepted let's submit this code let's see whether you've made a silly mistake or not absolutely successful not silly mistake absolutely successful uh the statistics don't matter but it's reasonably fast so this is how you approach this relatively not so challenging but relatively insightful problem uh this is one of its kind there can be other like problems which are these rows and columns based but this is how you solve a problem with illumination and querying where there is updating also required while doing queen right thank you see you in the next video | Grid Illumination | n-repeated-element-in-size-2n-array | There is a 2D `grid` of size `n x n` where each cell of this grid has a lamp that is initially **turned off**.
You are given a 2D array of lamp positions `lamps`, where `lamps[i] = [rowi, coli]` indicates that the lamp at `grid[rowi][coli]` is **turned on**. Even if the same lamp is listed more than once, it is turned on.
When a lamp is turned on, it **illuminates its cell** and **all other cells** in the same **row, column, or diagonal**.
You are also given another 2D array `queries`, where `queries[j] = [rowj, colj]`. For the `jth` query, determine whether `grid[rowj][colj]` is illuminated or not. After answering the `jth` query, **turn off** the lamp at `grid[rowj][colj]` and its **8 adjacent lamps** if they exist. A lamp is adjacent if its cell shares either a side or corner with `grid[rowj][colj]`.
Return _an array of integers_ `ans`_,_ _where_ `ans[j]` _should be_ `1` _if the cell in the_ `jth` _query was illuminated, or_ `0` _if the lamp was not._
**Example 1:**
**Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,0\]\]
**Output:** \[1,0\]
**Explanation:** We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid\[0\]\[0\] then turning on the lamp at grid\[4\]\[4\].
The 0th query asks if the lamp at grid\[1\]\[1\] is illuminated or not (the blue square). It is illuminated, so set ans\[0\] = 1. Then, we turn off all lamps in the red square.
The 1st query asks if the lamp at grid\[1\]\[0\] is illuminated or not (the blue square). It is not illuminated, so set ans\[1\] = 0. Then, we turn off all lamps in the red rectangle.
**Example 2:**
**Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,1\]\]
**Output:** \[1,1\]
**Example 3:**
**Input:** n = 5, lamps = \[\[0,0\],\[0,4\]\], queries = \[\[0,4\],\[0,1\],\[1,4\]\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= n <= 109`
* `0 <= lamps.length <= 20000`
* `0 <= queries.length <= 20000`
* `lamps[i].length == 2`
* `0 <= rowi, coli < n`
* `queries[j].length == 2`
* `0 <= rowj, colj < n` | null | Array,Hash Table | Easy | null |
59 | hey everyone today we are going to solve the little questions spiral Matrix two a few months ago I solved the spiral Matrix one I put the link in the description below so you can check later actually we can apply almost the same logic to so spider Matrix 2. so you are given a positive integer n generate n by n Matrix filled with elements from 1 to n Square in the spiral order so let's see the example so n equals three so output is like one two three eight nine four seven six five so we can go around the Matrix like spiral like this yeah so very simple question so let me explain how to solve this question before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the right button or leave a comment thank you for your support okay so let me explain with this example so n equals z so I created three by three and all numbers are initialized to be zero and there is two variables DX and d y so initialize one and zero and this is a like a move Direction so we start from zero and then when we move next we remove um X Direction like a this way lightweight and then when we reach out of bounds I apply this formula so update DX with minus d y and the update d y with DX so somebody wondering how I can find this formula it's simple I just wrote them and then many times I try many times so yeah um this form this simple formula works for like a spider moving so let's see um so first of all we start from zero and then so update uh here to I think it starts from one right so update one and then next so one zero so this way and then um this is not out of one just update this price with two and then move next Updates this number to three and then move next but uh here is out of bounds so I apply this formula to dxdy and so update this two variables um like a simultaneously so d y d x should be minus d y but the current divides zero so DX should be zero and the update d y is DX so one so that's why one so now we can move like a y direction so one zero so that means we can move this way right so and then move next and then next number is four and then next we'll update this number with five and then now we reach out to bounds so now again we can apply this formula for these two variables so DX should be minus d y so now d y is one so DX should be minus one and then d y i update d y is DX so zero so that's why the UI is now zero so minus DX directions should be this way right so now we move next to operate six and then move next update V7 and then now we reach out to once again I apply this formula to these two variables so update DX with minus d y so zero and then update the d y is DX so -1 so that means and we can go up like this right so move next and then update this number with eight and then so here so we can go up butter it's so 0 is a place where we already visited because uh how can we find the so this number this place is already visited it's simple so we initialized with zero our whole places are initialized with zero so if next portion is not zero that means we already visited so this place is uh like the same as out of bounds so we should move this way so now we can apply this formula to these variables and then so DX should be minus d y so minus t by so current d y is -1 minus t by so current d y is -1 minus t by so current d y is -1 multiply minus one so that means DX should be 1. and then d y operate d y is DX so now zero so that's y zero so now DX is 1 d y is zero so that's why we can write the action right so move next and then um nine and then finish yeah actually this is a almost same explanation as a as parametrics one yeah so with that being said let's get into the code okay so let's write a code first of all initialize X and the Y so these two variables are used for current position and the DX and the d y and initial is zero one zero and I create a 2d metrics so let's say results variable with like a zero or underscore in range n times and the four underscore in range in the end times and start looping for I in length so how many times so this is a n by n Matrix so n multiply n right and then first of all update current price so Y and X so we use a this index number so index usually starts from zero right so that's why I Plus 1. and then check the check out the ones or not and if not zero greater than or equal X Plus DX less than n or not zero greater than or equal y plus d y are less than n or result variable so y Plus d y in the X Plus DX so next position is not zero so in the case um we can apply that formula I explained in the previous section so DX and d y equal minus d y in the DX after that update the current Place X Plus equal DX and Y plus equal d y and then that's it so after that just return result variable yeah let me submit it looks good and the time complexity of this solution should be order of N squared so that's because um we created like anybody n Matrix and we visit all places once so that's why we execute like a n by n that means on Square and the space complexity is also o n Square so I created the like a n by n Matrix here so that's why yeah so that's all I have for you today if you like it please subscribe the channel hit select button or leave your comment I'll see you in the next question | Spiral Matrix II | spiral-matrix-ii | Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 20` | null | Array,Matrix,Simulation | Medium | 54,921 |
502 | Hello gaze MLA Agarwal welcome ji all owner on coding channel co tricks made by you made for you so let's learn today is lead par pehla match ki problem kya bol diya 264 moving whatsapp problem na van mein discussion for 2 day problem se samaj mein a Those who want to try it themselves, see what was said here that I had given myself profits and capital, there should be no doubt about what the area with its own profits is trying to say and the one with capital. What Eric is trying to say, but the first important thing here is that you should never think that the profit you want will always be sorted or the error related to capital will always be sorted and you can get it sorted at any time. A new one can also be found, there is no fix, it is okay, it is not given anywhere in the question that it will be found sorted only, because what happened here is that there was a shortcut in both the first and second examples, so do not do this at all. It is sorted, first of all, it is okay, what is the most important thing, second one, what is there here, it was like that in the first two, you have zero capital, if you have zero capital, then you can invest only in those with less than zero capital. The particular point of time but what happened in the run time is that as soon as you invested in a company with zero capital and your profit increased, now the profit increases. What are you saying that now I mean even in a vacuum, those who have capital. This is an investment, it was till the van, I can invest in all of them, I repeat myself, it was till the end, that means even now these zero ones also exist, ok, this is the cost, we will remove it, particular, but there are more zero ones. If yes, then you can still invest. Okay, so what is there at run time? At run time, you will have to increase the capital you have, there is not much question about it will be done very easily and the rest will be in our video. Those who have not understood the problem, there is no need to type. First of all, you are going to easily understand what the question is trying to say. Later, we will build its approach and say the financial question. What was the question you wanted? The question was very simple. What you were saying was that you have been given one with profit and this capital has been given. Okay, what do you have to do? It is very simple that you understand very easily that your Pass capital initial, how much capital do you have, said initial, your capital is zero, okay, you have zero capital and you have some projects, this is the idea that if you show these projects, then you will get this much profit, okay, you will get this much profit on singing projects. It is so clear but what do you have time to study only two, you have to decide which two of yours will you do, okay now which two will you do, how will it happen, where will it play the most important role in the capital. | Because if in the capital. | Because if in the capital. | Because if you have zero capital, then you will do your project first. If you have zero capital, it is okay. If you had more capital, then people with more capital can also do the project. It never happened there that if you have more capital, If so, then you cannot do lesser projects. Okay, what will you see on time? How is he calculating his profit? Okay, so what did you do initially? Said, I saw that you have zero capital initially. So, which projects do you have with zero capital? Okay, if you have only one project with zero capital, then you will have to buy it and stop the bike. Only this will have to be done initially. If you do not have any other option, then you will have to do two. Out of which one has been fixed by one's own, okay which one will have to be done by one's own, it is clear, it was said so clearly, there was no doubt in it, now what happened after that, one's own two have to be done, see here, understand what has been done. If it is you, then it is absolutely right to give yourself two first. Out of the two, you have done one of yours, now you have one more left and your capital, brother, how is the capital van, because now it will be profitable, like this one. When the project is completed, it will be added on. I said, this is absolutely correct. Okay, so you already have the capacity. I said, brother, it is clear. Now tell me, which projects are the ones with vans? Brother, these are the ones with vans only. Both are there and look at the one which is smaller than a van, it does n't even exist. Okay, so the one with van has only two projects. Now see which one has more profit. He said, if it has more profit, then which one will you do first? There should not be any difference in this, it means that it is right, so Apna did another project from which she got the profit. 3. Did you say anything about any problem? How much can Apna do in total? Two, Apna Ne has done it, meaning it is absolutely correct. If yes, then how much profit has been made till now 4 No doubt till now I said, I have no doubt till now, I said that this was my answer, just the question is not very typical, still if there is even a little doubt, then rewind the video for one minute. You will try and see that it is very important to understand the question first. Now I hope here you have understood the question well. Okay, now let's move towards its approach. Brother, what will be the approach? Hey, approach will be nothing will be done yet. Whatever you have said, will you implement it on anyone, first you said it and then what happens in the court, only what you think, what you set with your logical mind, you just implement it in your code, brother, who uses your mind. I am making a vector in my mind, I am making my own index, first I made it, then three has come, I just put a store in it in the tractor and there is no more, okay, so look to understand what I said here, initial apn, what I said is that I have zero. If there was capital then what did you say, only those with zero capital or less will focus on it, there is no point in focusing on the ones bigger than this, but you cannot take them, okay Han, it reduces very well, initially let's make one like this. Let's make one in which what we say is stored according to the 15 capitals so that we do n't have any problem in future, here I go, I went here, then came back, went to zero, then went to you, then went to three. One went supposingly and then came back one with zero. Okay, so now what is it that whenever 0 has to be seen, how many ones are less than zero, okay, then what will have to be done every time is that it will have to be traded on the whole. Okay, what are you doing? You are getting it sorted according to the capital. Okay, if you have sorted it according to the capital, then zero. Let's take this big example. Okay, zero comes three times, then van twice. Yes, then you came and then three came, is there any problem, no, okay, so how much profit is there with zero, initially said your van, okay with this zero, take profit man, you take profit man with zero, then one more van. Also, how much profit was there, I said, let's take 0 man, it is fine as per tradition and with this method, let's take our profit man, along with this, let's take zero man, okay, now there should be no doubt in this, we have taken one normally, just like this. I have made a factor in which Apna has done the taste according to you D capacitor, said no problem brother, there is no doubt in this is clear, there is no doubt in this, it is fine, very good, now let's do one less, it is so clear, isn't Apna one? Apna reduces what you had thought in this, if Apna Jo initially said how much is Apna Capital, it is zero, if Apna's initial capital is zero, then what will Apna say, Apna or less than zero, as long as we are coming, Apna will say this on top of this. If we trade, there is no problem, we did not say that there is no problem, so we reduced it by one, treated it on top of it and whatever profit we got in it, we put it in it, is it okay, so there was a possibility, from zero to you. Profit was possible, then from zero to three was also possible. Now look, these three are such profits, these are such profits which are possible even with zero capital or less than zero capital. Said ok, so what will you do, whichever is maximum profit. It was supposed to be taken by your own people, no problem has been said, okay so till now you have made that profit, wrong three, there is no doubt, said no okay, what will you open, we will remove three from it, okay, as many as are given in it. That blouse is very nice, now what did you say, now what happened at this point of time that as soon as one of your conditions became true that you had done on your own, initially you took all the ones with zero capital or less than zero capital. Got it all stored in a vector and then what did he say, now let's reduce one, take whatever is the maximum from it, okay, after that now there will be a van here and we will increase the capital which is a pantry. I closed it by saying that brother, I have already implemented it once and have made the site vector, I am not making it my own dish, I have just removed three from it, but it should not be a problem, okay, very good. Okay, then what did you say, now reduce one, we have reached till now, after this see if the van is smaller than three, it is absolutely correct, the van is smaller than three, then one less. Do this, push you also inside it, okay first, so you came, so what do you do, this one will have to be made a little longer, now this one, you came, it is absolutely right, it is shorter than 13, what did you say, Han Bhaiya, this is capital. This much capital investment was required and in my speech 3 to apan aapka aashirwad hai to apan kya bahu 3, apan kya bahu nahi hai, this is also less, apan aapka aashirwad hai to apan kya bhala, this too is less, apan kya hai, this is equal to this also You can take it, but okay Guruji, tell me if there is any problem. No, absolutely not okay. What will you do in return? We will do maximum thing from it. It is okay, it is not very necessary that you get it only on three rupees. How much profit was being made on three rupees, it was zero. So, we will take the profit of three, because we will see, brother, whether we are getting three profits on the van or three on zero, we will take the three on zero, it doesn't matter, he said, okay, so we have taken the three on zero, no doubt, zero. We will already take the third one. No doubt, no, there is no doubt, we have taken it, okay, so remove it and add more to your profit. How much will be the total six here? How much will your total moves be now? If so, how much will it become? Keep it at zero, the question has been reduced and how much has become of your answer. Six. Well, brother, why is there four in it? Let's change the question, first it does a lot of value increment, its profits have been incremented, hence your answer is different. It is okay, there should not be any problem in this, it should be very clear as to how it was done, how it was implemented, just because we are going to write this in the code and solve our question, it was not a very hard question, do not panic after seeing it. Said okay brother, it's done, okay come here and see let's come here. What did you say? One has made N, is there still N, nothing is okay, there is no need to pay attention to N, just change the size of your gesture and something. It is also not okay, the quality is very good, then what did I do after that, I did not do anything about the plus, I have made a leg on one side, what is this vector of pay, this vector is nothing, these are the pairs who are going to get their store done that is zero. And got the van stored in one leg, got it stored in which the first value is there, look here, what is the first value, here is the first value, okay here, what was your first value, what did you take, the capital is just for understanding, here the profit is yours. We are taking it further and it is simple to take it, that is why there should not be any problem, so what did we do, we inserted the profit inside it and inserted a capital inside it, there is no problem in it is so clear that we said. Han Bhaiya, this is absolutely right, it is clear, after that, did you call a short function because brother, you will have to short it, Han, you will have to sort it, that is why you had created a vector inside which you can do your shorting. Okay, you have shorted it, how did you sort it brother? Short, you had made a comparison of your own, according to what you said, first of all, check this, first of all, what will you check? What has come second? What is the profit and what is your capital in seconds? So if the capital is not from your own then you will be sorting according to these capitals and if at any point of time it is from the capital like this If all three are from the capital, then what will you do? First of all, the three will say, is there any problem? No, it is clear, there is no problem in it. Why did you do? We are going to look ahead, there is no doubt in it, there is nothing to be worried about. Okay, then why did you make yourself a priority? Why did you make it a priority? Brother, this one is a vector. It means nothing. Yes, this is the vector that you have made. You have made it a priority so that whatever is your maximum, you should always find it every time. You don't have to find the top variety directly. What happens in this is that you either find the minimum if you want to stop inside your vector or if you want to find the maximum then you can find it very easily. You don't have to do cigaretteization if Why have you done the initialization with maximum? Okay, you have done with maximum hip, so what will happen in that, you will get the topic, you will always get the maximum element open, what did you do here, you have initialized the maximum priority, there should be no problem, okay then. What will we get to always be at the top, that is, as long as we have to run on our own time, we will adopt as much investment as we have, that is, we will open as much as we want to complete. It is a blessing, right, that you will not want to go up by doing increments, it is absolutely right. And at the second point of time, what did you say that the value of your capital is the only thing that is clear to you that it should be less than what your capital is now? Like, if your capital is less then what will you do, what is the profit? We will keep pushing inside the vector. Clear said, Han Bhaiya, it is clear, that's it, and then what will we do? Every time we will take the top element of the vector and then we will move it back and keep reducing it. There should be no problem in the end. Whatever capital you have, what will you do with it? Will you get your return done? After submitting it, you will see and its code. | IPO | ipo | Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects.
You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it.
Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_.
The answer is guaranteed to fit in a 32-bit signed integer.
**Example 1:**
**Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\]
**Output:** 4
**Explanation:** Since your initial capital is 0, you can only start the project indexed 0.
After finishing it you will obtain profit 1 and your capital becomes 1.
With capital 1, you can either start the project indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
**Example 2:**
**Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\]
**Output:** 6
**Constraints:**
* `1 <= k <= 105`
* `0 <= w <= 109`
* `n == profits.length`
* `n == capital.length`
* `1 <= n <= 105`
* `0 <= profits[i] <= 104`
* `0 <= capital[i] <= 109` | null | Array,Greedy,Sorting,Heap (Priority Queue) | Hard | null |
56 | hello guys welcome back to techdoors and in this video we will see the merged intervals problem which is from lead code number 56 and this is a greedy type problem after discussing the intuition and the solution to the problem we will look at the most important follow-up look at the most important follow-up look at the most important follow-up problems which you can get in an interview so stay tuned till the end of the video I would like to announce about our DSA live training program which will guarantee understanding of every programming concept it makes you interview ready in just three months and it will maximize your offers so that you get the best possible pay and in the best possible company you can all the sessions will be live interactive sessions so you will get the feel of a live class and you can ask all your doubts throughout the class in order to get more details please WhatsApp us on this given number let us now look at the problem statement in this problem given an array intervals where intervals consist of two items start at I and end of the interval which is n and I merge all the overlapping intervals and return an array of non-overlapping intervals an array of non-overlapping intervals an array of non-overlapping intervals that cover all the intervals in the input now let us look at an example for better understanding in this case you are given an array of intervals right so you are given let's say 1 comma 3 comma 6 5 comma 8 and 10 comma 12. if you need the visual representation this is how it will look like so 1 2 3 is an interval 3 to 6 is another interval and 5 to 8 is yet another interval and then you have 10 to 12. now if you merge all these intervals in such a way that all the overlapping intervals merge into a single interval then you will see that 1 to 8 will become a single interval because there is something in common it will always be continuous like if somebody is standing at this point and you are getting the top view right if you are doing the top view of this entire figure then all these will seem like a continuous line if you are doing the top view and hence it will merge into an interval of 1 to 8 but since there is a gap in between 8 and 10 hence this will create a different interval from 10 to 12 so this is the X Y plane all these are actually on the x-axis so all these are actually on the x-axis so all these are actually on the x-axis so the question may ask you about how many of these different intervals you have formed like how many independent intervals are there so there are two independent intervals one from one to eight and another one from 10 to 12 or it can also ask you to find out the exact intervals after merging now let us look at the possible solutions for this problem now one possible solution can be let's say the intervals are given and there are four intervals in this case if I take the current interval as this one let's say this is my current interval which is one two three and if I keep comparing all the adjacent intervals in such a way that if the adjacent intervals are overlapping then I will include it in the same interval now the first condition is how do I check two intervals and consider them as overlapping or non-overlapping now let's overlapping or non-overlapping now let's overlapping or non-overlapping now let's see for the first interval my start of the interval is 1 and my end of the interval is 3. now if I have to check the current plus 1 8 interval that is the next interval which is from 2 to 4 you have to see that if the start of the second interval is actually less than equals to the end of the first interval right so if this 2 is less than equals to 3 then it must be overlapping if this 4 is greater than equals to this 3 right so if the end is greater than equals to this end value which is e and the start is less than equals to e then definitely there is an overlap and what can be the overlap value the new merged interval will be the starting point will be taken as the minimum of the two starting points and the end point will be taken as the maximum of the two end points which is e and end let's say that and this will be the new interval so if you follow this then it will be the minimum of 1 comma 2 and the end point will be the maximum of 3 comma 4 and by this rule you will get an interval from 1 to 4 as the new merged interval after merging one two three and two to four and you can visually see that it will be the answer so you will get a new interval where the start point will be 1 and the end point will be 4. now your current will shift to this point and this point will now have start equals to 1 and end equals to 4. now we will be comparing this to the next interval four to six now let's see this 4 is already less than equals to 4 correct and 6 is greater than equals to 4 that is also correct hence they are overlapping so the new start point will still be 2 which is the minimum of 2 comma 4 and the new endpoint will be maximum of 4 comma six so this will be updated to 6. so after merging the three interval that means the third interval as well you get a single interval one to six now your current will shift to this point and you will now be checking with the next interval so this is from 8 to 10. now let's look at it is this interval overlapping with the current interval is from 1 to 6. now 8 is not less than equals to 6 8 is actually greater than 6 and if the start point of the next interval is less than the previous end point then definitely there is a gap and this interval is not overlapping so this now becomes one of the merged interval and you have to restart another interval starting at this point eight and you will assume that 8 comma 10 is the current interval and the current will shift to this point and now you will be comparing with the next interval that is not present in this case hence after doing the merge interval solution you will get 1 2 6 and 8 to 10 as 2 independent intervals after doing all possible merge operations this approach is very important we will be using this approach throughout the video so if you didn't understand this approach please rewind the video and do it again this is an order of n solution where n is the number of intervals present here so this solution works for this example but is this solution going to work for every possible example let's see a counter example for that approach what if the intervals are unsorted basically the previous case works for sorted intervals but what if the intervals are unsorted because the problem doesn't guarantee you have the sorted intervals right so if the intervals are unsorted let's say from one two three five to eight and two to seven if you again apply the same process let's again apply it you have the current interval start Point as 1 and end point as three now when you compare it with the adjacent interval the next one which is 5 to 8 I have just given the visual diagram the top two down is the actual flow okay so the first interval is one two three second one is five to eight and the third one is two to seven so if you compare this you will see that the 5 is greater than 3 hence they are not overlapping so 1 comma 3 will be declared as an independent interval and now you will be restarting a new interval with 5 comma 8 so the start point will be 5 and the end point will be 8 and this will be your current now you will be checking with the current plus 1H interval which is this one and you will see that there is an overlap and the overlap actually updates the start point to 2 and the end point remains as 8 so this will be updated to 2 comma 8. now after doing the merge operation using approach one actually the previous approach I'll call it as approach one so doing the approach one on this particular example will give me one two three and two to eight but you can see that the answer should have been one to eight as a single interval but this is giving me two intervals which is wrong so we know that approach one alone cannot solve the problem of merge interval so we have to come up with something else now the possible correct approaches for the previous problem is one thing we can do Brute Force which is creating all possible combinations and getting the result and the second approach can be doing the Sorting algorithm and by sorting we mean that we can sort based on the beginning of the interval or the end of the interval so interval has two points begin and end so we can sort based on the first value or on the second value we will see both the solutions but let's first see how the Brute Force solution would work so let's take the same example and we will try the Brute Force solution The Brute Force solution is nothing but applying the approach One n number of times that means if you keep applying approach one the interval number of times then you will definitely get to the result why didn't we get our result in the previous attempt like in this attempt why didn't we get the result because we just did this process only once this is the first time we are doing it but if we repeat this process keep repeating the process and time surround minus 1 times then we will definitely get to the result like if I repeat it the second time then I will get 1 to 8 because this will be the current value and if I check with current plus 1 then definitely I'll get 1 to 8 as the result so if you apply it only once then it will not work for the unsorted intervals but if you apply it n number of times approach one then it will definitely work right so that is the Brute Force approach and this is the visual representation of the previous example using the Brute Force approach so in approach one you will get one two three and two to eight as two different intervals and after that if you apply the approach one us the second time you will get 1 to 8 which is the correct answer approach one actually takes order of end time and if you apply it n minus 1 or n times then that becomes order of n Square solution that is the Brute Force solution but this is not the expected solution in the problem if you look at the constraint then the constraint expects something else write the intervals length n to the power 4 so if it is 10 to the power 4 and you are applying n Square then it will go to 10 to the power 8 but your solution should run below one second so it should be below 10 to the Powerade so something better than n Square will be accepted so let's try to apply the Sorting algorithm now the Sorting can be of two types since we have two values starting an end value so let's start by discussing sorting by end value that is the second value so let's take the same example which is example one and in this case the end values of each intervals are 3 8 and 7. if we do sorting by second value then we get one two three two to seven and five to eight this is sorted by end value right now if I apply approach one like taking the current here and trying to merge in order of end time I hope you know this by now then you will get the answer as 1 to 8 and the time complexity will be order of n for applying approach one for sorting it was n log n so these are two different independent steps so the total time complexity will be n log n plus n which will be n log n right and this works for this example but let's try to take a counter example in example two I have taken one two three five to eight and two to nine if you sort by the second value then you will get one two three five to eight and two to nine now if you apply approach one solution again which is order of n merging then you will see that you will get one two three as a different interval and 5 to 8 will be merged with two to nine and hence you will get two to nine so it will give you two different intervals one two three and two to nine but actually the answer should only have been one two nine so this sorting by end value doesn't work right didn't work on this example so if you can come up with at least one counter example then you can actually nullify that entire algorithm whatever you have chosen Why didn't it work this did not work because we need a guarantee that if we have seen a interval starting at some point S1 and ending at T1 the next interval should not have a start point which is less than S1 that should be guaranteed and that cannot be guaranteed if you are sorting by the end value therefore let's try to do the same thing by sorting by the start value so I have taken the second example which was the counter example in the previous case and let's try to solve that problem one two three five two eight and two to nine if I sort by the first value which is 1 2 and 5 then I'll get one two three two to nine and five to eight and if I again apply the first approach that is linear time merging using the current variable then you will get 1 to 9 as a single interval in just one step so here the time complexity is n log n and this solution is bound to work for any type of example unsorted sorted whatever it may be it will always work you will not be able to come up with a counter example so this is the expected optimal solution for the merge intervals problem and I hope you have understood why other Solutions don't work and why this solution is working and why the time complexity is n log n let's quickly look at the follow-up problems and then we at the follow-up problems and then we at the follow-up problems and then we will look at the code so the first follow-up problem can be so the first follow-up problem can be so the first follow-up problem can be printing the merged intervals if your problem was about finding out how many independent intervals are there then the follow-up can be print all those follow-up can be print all those follow-up can be print all those intervals and if your problem was about printing all the merged intervals then the follow problem can be print how many of these merge intervals are there I mean how many of these independent intervals are present the second follow problem can be printing the non-overlapping intervals printing the non-overlapping intervals printing the non-overlapping intervals you can practice this by going to lead code number 435 and the third follow-up problem which is and the third follow-up problem which is and the third follow-up problem which is slightly related to this same problem is the minimum platforms problem and you can do this by watching my video on minimum platforms you can search on YouTube if the link for it will be given in the description below as well now let us look at the code for the merge intervals problem in this problem we are given the 2D intervals array and I have found the number of intervals in N then I have sorted all the intervals based on the start point so by default your library will sort based on the start point and then we have taken the answer intervals which is the all possible merge intervals and simply we will apply the approach one so this is basically approach one where we have chosen the start Point as the first interval and the end point as the second I mean the first intervals endpoint so this was three I guess in the previous problem and then we will be iterating through all the adjacent values until we don't find any Gap and that particular the start and end value will be merged into our list of list which is in the answer so you can go through this code and I think if you have understood approach one then this is the code for the same approach applied along with the Sorting so this is the Sorting step in just one line and after that it is just approach one the PDF of this video will be present in the telegram group so you can follow us on telegram to have all the previous videos PDF as well you can follow us on Instagram as well to get updated with all the interview Trends I hope this video was helpful see you guys in the next video thank you | Merge Intervals | merge-intervals | Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104` | null | Array,Sorting | Medium | 57,252,253,495,616,715,761,768,1028,2297,2319 |
146 | hello everyone in this video we're going to be going through lead code problem 146 lru cache so this problem has a 99.3% popularity is the second most 99.3% popularity is the second most 99.3% popularity is the second most popular question after tuome this says to design a data structure that follows the constraints of least recently used cash now what is least recently used cash actually well cash is basically amount of memory that's stored um for easy retrieval so think of your computer let's say you go to a website and access and to a website and access and to a website and access and you do that every day so that will be stored in your cash but then once in a while you might go to a different website it might take a second or two to load it because that one is not stored in your cash but after you access it will be stored but the cach has a limited amount of space so that's why this problem is so important because you want to remove the stuff that you haven't used in a long time and so to do that we're going to implement this uh solution so lru cache will pass in an INT capacity and we'll do that with a positive size capacity then we'll have a get method that passes in an integer the key and Returns the value of key if it exists otherwise we'll return the default value of negative one next we're going to have a put method which will input the key and the value and if the key already exists it will update the key and the value otherwise add the key value pair and if the number of keys exceeds the capacity this is where the least recently used cache method comes in it will evict the least recently used key and the functions get input put must each return o of one average time complexity so let's look at the example they give us and instead of looking at the input and output we'll just go through the explanation so the first thing we're going to do is instantiate lru cache class to a new lru cache and pass in a capacity of two then we're going to put the key value pair of 1 one into the cach and then we're going to put the key value pair of 22 into the cach so as you can see here the cach equals 1 one and 22 next we're going to get the value of one so we're going to pass in the key which will return the value one now we're going to put in key 3 value three so this is where um you have to activate the least recently used solution so the last key the least used key was two so we're going to evict key2 so the cach will become 1 one and 3 three and the reason that two even though we put two in after one we accessed one and so two becomes the least recently used so then we're going to try and get the two and it's going to return the default value of negative 1 because it's not in the cash anymore now we're going to put four4 so the least recently used key is one because we put 33 after we access the one so 33 is now technically more used than the one so it's going to evict the one so the cach is Now 44 and 3 three then when we try and get the one it's going to return Nega one it's not found get key three Returns value three and get key four Returns value four all right let's see how to implement this so let's take care of some overhead information first what we really need for this problem is a hashmap which has the key value pair but the hashmap doesn't consider ordering and so we need a link list to keep um everything in order and that's where a linked hashmap comes into play it extends the hashmap class and implements the map class which in turn extends the sorted map so we get the Sorting as well this allows for key value pairing and also maintains the order so this is the syntax here link hashmap we're going to pass in the capacity we're going to have a float for the load factor which I'll explain in a minute and a Boolean for the type of access that we want to use so capacity is a number of buckets in the link hash map in the lead code example we passed in a two so the capacity was two the initial capacity is simply the capacity at the time the link hashmap is created so if we had a capacity of a th you wouldn't automatically uh assign uh the capacity limit to a th000 the initial capacity might be like 100 or something so load factor is the measure of how full the link hashmap is allowed to get before its capacity is automatically increased so let's go back to the capacity of thousand let's say the initial capacity is 100 and you get to you put 75 entries in and the then the load Factor kicks in and says oh well we've got 75 that's the load Factor so now we're going to increase the capacity to 200 and this will keep working all the way up until we hit the max capacity of 1,000 so as a general rule the load the 1,000 so as a general rule the load the 1,000 so as a general rule the load the default load Factor 75 offers a good trade-off between uh time and trade-off between uh time and trade-off between uh time and space so the number of entries in the hashmap exceeds the product of load factor and the current capacity then the hash map is actually just rehashed and finally the access order determines how the data in the hashmap is retrieved so if access order is true it takes into account when the data was last ACC accessed which is just perfect for this problem I actually think link hashmap was created just for the lru cache situation so if access order is set to false it takes no account when the data was last inserted like a stack or a q which we don't care about in this case so the lru class will extend the link hashmap now the link hashmap class will be accessed using the super keyword we're going to use Link hashmaps method get or default which will pass in a key and return the value otherwise it will return uh negative 1 if it doesn't find it we're also going to use the put method which will do put in the key and the value now the put method behind the scenes calls this remove eldest entry function passes in the key and the value so this is a length L list method returns Boolean true or false and the way we're going to determine true or false is we're going to use the size method and return the number which Returns the number of key value mapping so we're going to compare size to the capacity and if uh size is greater than capacity then we're good to go but if capacity if size becomes I'm sorry if size becomes greater in the capacity then we're we have to remove the list entry okay so let's code this so public class lru cache this is what lead code gives us we're going to extend the linked hashmap class passing in an integer for the key and an integer for the value so the first thing we need to do is Define an integer capacity to store the capacity that gets passed in because we need to use that later um in the remove uh eldest entry uh method so public lru cache into capacity so this is the Constructor for lru cache which is going to call um the instruct the Constructor for the linked hashmap class so it's going to pass into the capacity it's going to pass in that 75 that we talked about and pass in true for the access order then we're going to assign the local V variable capacity equal to the Past in capacity in the Constructor and that is pretty much it for the initial uh solution now we need to implement the get method so we're going to pass in a key and we're going to return linked hashmaps method get or default which will pass in the key and return either the value or negative one if it can't find it then we need the put method which will pass in the key and the value and this is just basically going to call link hashmaps method put passing in the key and the value now this put method will call this remove eldest entry and its input parameter is map entry key value and they'll call it eldest and all this is going to do is return if the size is greater than the capacity and again and that gets called automatically uh through the put method and that is pretty much it so let's run this through the debugger see if that doesn't help so I use the first example or the only example they gave us so let's step through this so the first thing we're going to do is instantiate a new lru cache passing in the capacity of two so this calls the Constructor which calls the link cash Maps Constructor passing in 2.75 and true and then we passing in 2.75 and true and then we passing in 2.75 and true and then we assign this capacity equal to capacity which is two all right so we're good to go so first thing we need to do is put one so key1 value one into the cache so we use the put method one and you see automatically it called this remove eldis entry and the Elis entry is one because it is the only uh key value pair we have in um the cache size is good to go so we add it to the cach so if you look at cache it's now size one key1 value one so now we're going to put the two in again we're going to call this remove L the Sentry is still the one and size is good to go so puts 2 two so now if you look at the cache one1 and 22 key value pair of 2 two okay so now we want to get the one and this calls the get method passing in the key and because we have one in the cache it's going to return uh the value one now we're going to put 3 three this is where the fun happens so key3 so we're going to look at the eldest now because we put one in before two but we accessed L1 or accessed one after the two the eldest now becomes two and so the capacity or the size is actually greater than capacity so we've got to evict the two and put in the three so now if you look at the lru cache it has the one and the 3 three so now we're going to try and get the two um which should return negative 1 because yeah we don't have a two in there so now we're going to put 44 in so 44 looks for The Elder centry which is still the one because although we got the one we put in the three afterwards and so the one becomes the uh least what is it yeah the El sorry the eldest entry and so we have to evict the one because the size is greater than capacity so now if you look at lru cache it's 33 and 44 now we're we going to get or look for the negative we look for the one which is going to return negative one because we don't have a one in there anymore the key one so now we're going to pass in key three which return the value three uh yeah result is three and finally we're going to pass in or we're going to try and get value four so we pass in the key four Returns value four and that is pretty much it so let's run this through leak code and see what happens is accepted this is example one and we submit it is greater faster than 70 basically 71% is greater faster than 70 basically 71% is greater faster than 70 basically 71% of the entries and it uses least amount of memory in almost all the submissions so that's good news all right so finally we'll go through the time and space complex so time complexity in this case is O of one we're just putting getting removing all the entry there's nothing that's going to increase uh the time on that but the space complexity is O ofn So as you can increase the capacity then the cache gets bigger and so um the Big O notation is O of and that is it so hopefully this made sense let me know if you have questions and uh see you next time | LRU Cache | lru-cache | Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, null, -1, 3, 4\]
**Explanation**
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
**Constraints:**
* `1 <= capacity <= 3000`
* `0 <= key <= 104`
* `0 <= value <= 105`
* At most `2 * 105` calls will be made to `get` and `put`. | null | Hash Table,Linked List,Design,Doubly-Linked List | Medium | 460,588,604,1903 |
399 | hello hi guys good morning and oh God this question is one of the best questions for intuition purposes like okay you have a question and you have to build on what data structure you can actually solve this particular problem on what on What algorithm like you want to solve this problem so basically building that part from here the question part to actually going on to the data structure to actually solve this problem it's one of the best question I have seen so far which actually is very hard to go from this part which means the question Reading part and actually applying okay what should I use that okay it is being used okay it can use it cannot be used that stuff that is that's the reason like I'll just I just love this question so yeah without further Ado uh without further appreciating the love for this question and let's go the question itself um I'll just quickly go through question basically we have equations as I where it just says as we have the value which means it is ultimately means that AI upon bi has a value as values of I cool and then it is also said that we have a queries of five which is also exactly as c i comma di is actually nothing but same c i upon d i now uh we have to return okay if the answer cannot be found for this query so basically we have to find the answer for this query which means CI upon d i ultimately we will be having many of such AI upon bis like having a values and we have to ultimately find CI upon d i which is the query answer which is we have to find if it is cannot be found then we have to write a minus one and one conditions answer is always valid the base will never be a zero and there is no contradiction at all which means it can't possible that you can as you can get a two different values from two different values of AI upon bi such that okay I will show but yeah there can't be any condition at all so please note this point it is very important because when I start like initially read this question I didn't read this point and I was thinking of the hcso what if this happened what if this happens so we don't have to think all that stuff cool now we have the question and let's see the example particularly we have this equations as you know it is a comma B it will be represented as a upon B now a upon B I just wrote but what is the value 2 here 2 is nothing but the value of that corresponding a i comma b i right then B upon C which is equation of B comma C it is actually a b upon C and its value is nothing but 3. good so it is the input which we are having now for this input I have to find the output as in add fund value of a upon C which means I have to find okay it is queries of a comma C but I have to find the value of a upon C this I will just say okay I have the input right here a upon B and B upon C if I have to find a upon C mathematically thinking we can easily find a upon C by because multiply this be upon C then I can just cut or cancel this B I will get a upon C so basically it is multiplication of a upon B and B upon C which is 6 which we get okay cool if I want to find a b Upon A oh I can actually see that okay I have a upon B I will just reverse this down which means inverse it which means 1 Upon A upon B it will actually be a b Upon A which means 2 was the value of a upon B so 1 Upon A upon B is 1 upon 2 which is 0.5 that is the answer let's which is 0.5 that is the answer let's which is 0.5 that is the answer let's see if a phone Find value of a upon e but I didn't e was actually not present right correct so we can't find the answer for this that's the reason answer is minus one cool um a Upon A was also present a was also present and a Upon A is itself just canceling out both of them I get a one that's the reason answer is one for example X upon X although X upon X answer should be one but X was not present so according to the question itself you should return a minus one because it was not present for us now cool uh you saw okay I really looks like mathematical shall we is something of so basically as soon as the question comes in now if you have to think what we have to apply right uh one thing which comes in your mind is okay let's take an array and Aryan we have to find a upon C now what I will do is I will try to grab some pairs which means which will have a and which will have seen the denominator and then by some mathematic operation I know that all these will be get all this will get canceled so I will just try to take this thing out I'll say okay uh that looks nice but how will you actually keep track of it which means okay you have this a you have this C still you can have many A's and many C's which means a upon let's say you have D you can have a upon e also you can have a upon F also then how will you keep track of stuff you can apply rule for stuff that's nice but I will keep track of it let's see this with a better example let's say if I just have the sample a upon b as 2 B upon c as three C upon D S5 right ultimately let's say I want C Upon A to be my answer now basically what I am thinking of is okay C Upon a C Upon A I have to reach basically a upon B I am going from a okay and something is being divided then I'm reaching 2 ultimately as we saw okay mathematically we are about to find the answer C Upon A is nothing but simply C upon B into B Upon A which means reversing B upon C because it was 1 upon B upon C it is reversing so it is kind of that I am trying to go from this C to the a any a possible so what I did was I just tried to go from this C to this B because of this B it try to reach to this B and for sure it can have multiple B's which means this B could also reach to another B which is B upon let's say d and maybe this D is reaching to some other thing let's say p upon F so it can have multiple right so it is a reason I can see okay from this C I can reach to Mom B because it is opposed like above me so I can reach to that b and if I just say I am reaching which means I am finding my C upon B right by one way C upon B it is actually a three sorry B upon C is actually a three so C upon B is 1 upon three I can keep this operation for side but now I am thinking I am just thinking because I have to ultimately find the answer for C upon it so I'm thinking how can I reach because ultimately my goal is to grab C to grab a now I can start from C and let's see how I can reach a because ultimately my goal is to grab both CNA and grab this okay what is the multiplication like so ultimately I thought okay let's grab start with C then okay for C I have above B so for sure I will grab B now for I want something as a anywhere so I just want okay for all the B's I'll just go and try C okay where all B's are there and then from that b okay if I just reach it to AO I can just simply take this path of B of c b a to actually reach from C to a you understand how this problem transformed from numerator to denominator to actually reaching from one point to another point we started from here itself where we saw okay I have to get a upon C which means anyhow I have to bring out this a upon C so we thought okay let's see okay how we can reach basically connect both of them basically reach from this a to this C or basically from this C to this a that is how we thought okay it is kind of looks like okay I am just going from one note to another node then to another it's a path it's a graph that is the reason how we thought okay this problem can be converted to a graph and then maybe we can just solve it because ultimately I have to find the answer for a upon C or basically upon it anything which means I have to reach from C to a or from a to c and I have multiple options because the option one right here shows okay I can go from A to B and now RN you say I can go from A to B but A to B so what this two means in here so if you just go on for us already then we can easily say okay if I can go from A to B then it is 2. no uh if I just can go from B to C it is 3 which means if I want to go from a to c which means a as the numerator and C is a different address so it will be 2 into 3 so ultimately the edges which means these edges I can just multiply them to actually go on as I am going on to every path which means as I'm moving forward in the path I can just multiply this edges to actually Rush from this a to this C and if I just reversing back which means a up a upon B because it is the denominator which means it is the uh dividend and it is the divisor which means two is a dividend which means a is a dividend and b z divisor so I can simply say Okay a upon B is actually going from A to B and if I just come from B to a you will see that okay it is nothing but 1 Upon A upon B that's the reason I just reverse the same thing it's two it's one upon two it's three h one upon three it's five it's one upon five that is how we can actually go from this node to this node and build a graph out of it what happened because of this is now if I want to go from C to a I can simply go and type let's try to go from C to a and try to reach a yeah it is possible I can just go okay one by three is multiplying my answer then one by two is multiplier and I can reach a that is the reason starting note I can just choose as C because ultimately C is my numerator or the if we did and I have to reach to a divisor which means denominator I have to reach which is actually a in this case that is how we can actually reach now you saw how we built a graph from U to V which means if we have U and let's say the value is X so basically it's the numerator it's a denominator which means U upon V I will can use I can reach from U to V if I just take X which means U upon V will be X and Y is also V upon U will be 1 upon X that is the reason I just buy this way firstly we thought of how actually is like what they have what we need to use now we like found out that we can use a graph now we can use a graph but still graph needs of something all the values which are given for us we should be able to recognize that in our graph right so I just tried to build a graph out of these inputs and this is how we issue a conclusion okay A to B I can just add a 2 which is a upon B is actually a 2 and vice versa also because B Upon A is actually a 1 upon 2 and this I built this one upon 2 and then C B to C and then C to B and you will see it's a directed graph because ultimately if B upon C is three then C upon B is 1 upon three so both have different values same for this case now what will happen is a upon B is 2 B upon C is 2 if I want to go from a upon C which means I will try to go from a to c then I will just go on the path go on in the path and whatsoever values are coming in I'll just multiply that part and I'll just ultimately reach Upon A upon C's answer which is numerator and denominator which means starting from this node and reaching to the this node if I had to reach from C upon it so I will start from the C and try to reach a I will start from C and try to reach a and ultimately I will have these values as the multiplication which means 1 by 3 into 1 by 2. that is how we can simply build the graph multiply the result which comes in because I want to go from a to c and thus get the answer for any number and for short please remember that there is no condition at all there will be no multiple paths coming into the same point and having that follow if the parts are coming in also then still it will have the same value there will be no conversation at all that is the reason they was written that they can be no contradiction else you will because you will be just confused okay which value to 2 which value to 8 if from this path or from this path right here that's the reason it's just see look there may be no connection at all now we just for sure know okay we have to find answer for every query right so let's look at the constraints once if it is possible if to act or like we can actually just simply do a traversal graph Traverse because it was simply trying to reach from C if I want to find transfer sleep on a simply starting from C and trying to reach a that would be all right starting from C reaching a that would be all so a simple graph reversal would actually work but let's say that constraints if we have got to optimize something or not if it is not of the case so let's quickly verify that okay if something else or something observation you should be done or we can do a simple graph traversal and you would be good so for every query I would be needing to reach for let's say the query says okay reach C Upon A so basically from C I have to go on the entire graph and reach a so basically for every query I need to do an entire graph traversal craft reversal it just it's simply a DFS or a BFS as we have seen and if book can be applied it is shorter to right so usually we prefer to write a DFS function because it is shorter to write like we can write very fast and BFS both it can also be used okay it's a bit longer code although both are easy both are the same time complexity same space complexity everything you say this is that okay one is easier to faster right because it's recursion it's a bit iterative so it is actually applicable but yeah uh for every query if I just try to apply a simple graph reversal which means the if I just say okay the edges are e multises are V we can see equations length is 20 so by Max different vertices it can be at nice 20 now at Max 40 and edges it can also be like at Max 40 or maybe in this number so it can't go beyond let's say 100 or something for sure so for sure for every query queries are itself very less for every query I can very easy do a graph traversal and that would be it which means for every query I am doing a graph reversal let's say graph reversal takes a simple BFS or DFS which is nothing but o of e plus v then our total compressive will actually be Q of e plus b which is actually a BFS or DFS and that's like which means okay I can simply graph reversal for every query and when we say craft reversal which means we'll go from source to destination which is nothing but let's see if the query is C Upon A so basically going from C to actually a and finding the answer in between pull and let's see the code it's simply very easy we will be having our uh evident to divisor which means C Upon A I will start from C and I will try to reach my a start to end and that would be it I'll just break down the code although code is pretty big because we have to transform the input to actually a graph and then apply R Traverse on the graph so I have divided the code completely for you guys to actually understand the PDF is also download the code is also wrong so don't worry on that part I will make you explain every part this calculation X equation is actually the main function which we have to write so firstly as we know that our input is in the form of a graph so let's build this graph now how I build it because we know for every node I have another node and also the edge weight right you remember right that a Upon A B has a value as 3 which means a upon B is 3 so that a if it is connected to B and it can also be possible that a is corrected to C so it can have a h beta Square which means a upon C is actually Four so basically I can say Okay a upon 3 a upon C is let's say okay it's three let's say it is four cool for the example which are taken so if a upon C is actually a 3 and let's say a upon e is actually a 5. so basically I can have multiple rights so it is simply making your interacted graph directed weighted graph out of simple input which means I have a upon C S three a upon es 5 I can simply take a graph where graph is nothing but okay one part is nothing but strings for every string which is let's say a at this part I have another you can have a vector of pair you can have a map you can have anything here first simply I took a map so basically it is nothing but for this a you can have multiple outputs as you can saw it is bece so for this a I have c and e and then I also into store k for this a to see what is the actual weight it is nothing but three for a to e it is multiple five for A to B it would have been four that is how I will just store My Graph as a map of and when I say map or set it will always unordered so it is a map of my mainstream which is a to actually all the you know interest which is b c e and then also the weight like value which means let's say three five nine now like this it is how I will make my graph and for every node cool now my graph is let's say made oh okay how the graph is made show the code no worries let's see the code so you will see that okay graph I just passed the input as my equations and also my values because ultimately to build a graph I need equations and values because ultimately I want a upon B is let's say three so I just want to build a graph out of a upon B I just want to three that's it right cool so I just want to build a graph out of it now simply what I will do is I will just initialize My Graph as because I said it is another map of string it's actually another map of string two double that is how I showed you here now when it is done simply going on to every equation because for every question I have to find this result which means it is the numerator it is the denominator which is it is that if we didn't it is that divisor and it is the value so I need to make a to actually have a graph map to B and it's another value which means A to B is actually a three so it is I will simply do is okay everything is crashing today damn but no worries at all um what we will do is simply that for that a which means for that dividend a for that divisor which is B I will have this value as 3 that is the value and samely for this B to a I will have a value as 1 upon three so for this B which is the divisor to a the value is 1 upon value which is this particular V that is how I will just make my directed graph and I will return that graph now my graph is made now I will also initialize the answer because ultimately I have to return the answer for every query so it is for returning the answer for every query now okay cool the part of initialization from the graph is done um getting the query is done everything is done now going under the queries itself I went on to the query I find okay for this query I have to find the answer for a upon C which means a is the dividend C is that divisor I have to find the answer for a upon C I just found okay let's grab both C A and C now I also know if any of them is not available in my actual input which I had for sure I have to return a minus one as you saw in the above if I had example of this particular stuff let's go above very above uh as you saw a pony e was not there so the answer was actually a minus one X was not there so the answer was minus one so if any of the string if input which means let's say upon C so basically if any of them a or C is not there then I'm going to minus one so I will just go and check in my graph that okay hey graph do you have both numerator and denominator if any one of them is not found which means if the dividend which is the numerator is not found or if the divisor which is the kilometer it is not found I have to return a minus one which means I have to push back in my answer array as minus one cool now if both are there now start to find from this a try to reach to C which means you have to start from this dividend which means it is the start node you have to ultimately end to a end node which is the divisor ultimately passing My Graph and visit because for sure in uh PFS traversal we have a thermal rule that we visit every node exactly once now for that you have to keep track of what all nodes are visited we can have a simple unordered set of our strings because ultimately the input substance itself so to actually keep that okay what all nodes are visited and then ultimately it is done answer is nothing but okay final answer okay if I am able to reach I will overwrite this answer with my temporary answer so it I realize my answer is minus one because if I am able to reach I will overwrite this answer finally which means from I will start from this uh fourth note if I am ultimately able to reach this end node I will overwrite this answer and it will become something else apart from minus one but if I'm not able to reach it will still remain minus one thus I will just push in minus one but if I am able to teach this I will override with my answer and how is the actual answer it will be actually updated by this value as temporary answer that is how I pass it now going on to the actual function of DFS which you have to implement simply a simply very short small code of DFS how firstly I just take okay if this node I am going on right now is it actually is it or not if it is visited oh God run away run back if it is visited just run away else if it is not firstly Mark that note as visited so that you will never come on to that note again and also check if on reaching that don't you have finally reached your destination I told you right ultimately my aim is to reach this end which is the destination if I am able to reach this destination oh God just to say that upgrade as I said answer is storing the final answer and temporary answer is the okay so right now what is the answer if you are able to reach your final answer just which means the final note which is the destination just update your answer as by 10 and just return you're good else if it is not just simply try to go on to every of the neighbor as in a simple DFS that's what we do now as we go into every neighbor what have what we have to pass on the node right because ultimately our TFS is by another node now node as in are in graphs neighbor right now in My Graph I had something like this if you remember that a it had a map to actually be with hash with which had a value okay this has okay three now that a it can also have let's say C it can have a four now e can have a fight right it is how a upon B is 3 a upon C is 4 a 1 e is five now b c and e are the neighbors so basically it is nothing but that I'm just iterating on all the pairs of this graph of node so basically I'm trading on this now right because it is the neighbors of e as simple as that now neighbor DOT first is actually this particular value which is B C or E so okay because it is the neighbor actually now destination will always remain similar because ultimately my aim is to reach this assassination graph and visit it will remain as it is answer will not get updated at all because ultimately I update answer only and only when I am able to reach this destination part which I did here okay which I did here and but button I said that I will update my temporary answer because as I showed you that I will keep on updating my answer by this method as I am going on further and further you will see I keep on updating the answer as you saw here I was going on I have to go from a to c but meanwhile I go from A to B I have two now B to C I have 2 into 3 and so on and so forth I will just keep on multiplying and that is how I will reach my particular value if I have written that same thing down anywhere else yeah no but cool you got that point right A to B is 2 then I will just store this 2 in my temporary answer then if I just go from this next node to the next node I just multiply the uh I'm pretty by the next Edge variable which is three it was earlier two thus you will just get a 2 here so 2 into 3 which is 6. now ultimately let's say if you had to go to let's say d then you would have multiplied your temporary with five and it had been six already so it will be nothing but six and five thirty that is how you will actually go on from everyone which means you will keep on updating your temporary buy nothing but this multiplication of weight next to it next week and thus you will ultimately keep on updating the app sure multiplication of paths now ultimately as it goes on our DFS will actually be completed now it will actually return us answer as update answer and if the answer is no matter if it is -1 which means I was not matter if it is -1 which means I was not matter if it is -1 which means I was not able to visit my divisor at all from my dividend which means from the start mode I was not able to visit my endnote and if I was able to visit my Android Note gold very good answer will be updated by the actual answer and you need to push in that actual answer in your final array and that is how you will return your final answer that is potentialed and the capacity as we have saw earlier for every query I am doing a BFS or a DFS drivers both have same time complexity is e of e plus V Space operation is e of O of V so actually the visited and also if you just make a graph out of it so for sure your graph needs to be for every vertex because see graph is nothing but you have all the vertices here and then you have all the okay for this vertex what all edges you have it was very less 20 so that won't be an issue so that is actually depends upon your okay what all vertices you have a lot of edges you have and that is how you will just solve your uh space complexity code for C plus Java in Python is it down below although the code is a bit big and for sure it would be because it's actually a very good problem I hope that you guys liked it if yes then do hit the like button it has motivates a lot if you want to know anything about okay how I just write and stuff all the products are down below you can just uh check them out and that would be great if you have not watched the Vlog the shots anything we have live streams also so if you are just preparing for only assessments interviews everything stuff live streams happen daily which means every day the contest happens even if it is why weekly any contest of liquid happens we have the live stream for that so for sure do join us at 11 PM or 11 A.M 11 pm sure do join us at 11 PM or 11 A.M 11 pm sure do join us at 11 PM or 11 A.M 11 pm for bi-weekly is 11 A.M for weeklies for bi-weekly is 11 A.M for weeklies for bi-weekly is 11 A.M for weeklies take care foreign | Evaluate Division | evaluate-division | You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits. | Do you recognize this as a graph problem? | Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path | Medium | null |
319 | hey everyone welcome to techwide in this video we are going to solve problem number 319 bulb switcher first you will see the explanation of the problem statement then the logic and the code now let's dive into the solution so here I have an example so here n represents number of bulbs right so initially all my bulbs will be in off condition right and we need to toggle these bulbs in certain way so first we will see how we are going to do that and also we need to toggle these five bulbs in five rounds right so in the first round I will toggle every bulb so every bulbs gets on right so here I am representing 0 as of and one as on right so in the second round we need to start toggling from the second bulb so the second bulb becomes zero and then from here I need to check in next second bulb which is 4 right I need to toggle that one as well so it gets off so from 4 there is no 6 right so we don't have to do anything then we just copy the rest of the bulbs so next in the third round I need to start from third bulb where I will off then from third bulb I need to check the next third bar 6 right there is no 6 here so we can just leave and we can just copy the rest of the bulbs now same as we need to start from 4 so 4 is off here so we need to on and from 4 there is no 8 right so we can just Skip and copy the rest of the bulbs so same we can just copy rest of the bulbs and we can just toggle the fifth bulb alone which becomes 0 here so after five rounds after the nth round so we need to do it for the N Bulbs and the N rounds right so after completing the nth round we need to look for the number of on the bulbs so here we have two bulbs on right so we need to return two so I just explained this particular problem how to solve this problem in order of n time but there is more efficient way that is what we are going to see in this video which is constant time right so now we will see how we are going to do that so here we are having n is equal to 5 and we have five rounds here right so I have ordered here from one to five so what we are going to check is we need to check how many factors are there in each and every number right so for one there is only one right then for 2 it is 1 and 2 then for 3 it is one and three then for 4 it's 1 2 and 4 right these are the factors of 4. then for five it's one and five so now we need to see how many numbers are having odd number of factors so here one as only one factor right that is odd so I will count as 1. so for two there are even number of factors so I won't consider this then for 3 again we have even number of factors we won't consider then for four we have odd number of factors right we will consider this and we will increase the count by one so we will be getting 2 now then for 5 we have even number of factors we won't consider this so finally we would return two so this 2 can be arrived using by taking the square root of the value n and round to the nearest integer so if it takes square root of 5 will be getting 2 point something and we are going to round it to the nearest integer where I am going to get 2 right so the time complexity will be order of one time so that's all the logicals now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so basically we are just going to return by taking square root of n right that's all the quarters now we will run the code thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys | Bulb Switcher | bulb-switcher | There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb.
Return _the number of bulbs that are on after `n` rounds_.
**Example 1:**
**Input:** n = 3
**Output:** 1
**Explanation:** At first, the three bulbs are \[off, off, off\].
After the first round, the three bulbs are \[on, on, on\].
After the second round, the three bulbs are \[on, off, on\].
After the third round, the three bulbs are \[on, off, off\].
So you should return 1 because there is only one bulb is on.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `0 <= n <= 109` | null | Math,Brainteaser | Medium | 672,1037,1491 |
1,857 | hey everybody this is Larry this is uh this is day ninth of the liko April day challenge hit the like button hit the Subscribe button drum and Discord let me know what you think about today's Forum uh we have a contest in two and a half hours I'm excited for that we'll see how that goes so it is kind of late in later in my bedtime but um you know maybe once a week is fine uh today's problem is also I hope everyone's having a great weekend by the way uh Happy um you know uh gista well uh is that today I don't know when you're watching it right so uh whatever you're celebrating a happy weekend all right uh 1857 uh largest color value in the directed graph yeah so make sure you hit the like button hit the Subscribe and join me on Discord I suppose uh okay so there's a directed graph to end color notes and M edges okay the notes are numbered from zero to n minus one okay chemistry in colors but color survive is a lowercase English letter representing the color of the iPhone node silver index you're also giving a 2d away edges okay so the edges the directed edges I've added path in it in the graph is a sequence of nodes okay it's a path defining a path uh the color value of the path is the number of nodes that are colored the most frequently occur in color along that path the color value return the largest color value of anybody path in a given graph or minus one if the graph contains a cycle okay um so basically here you want do you always want to start at anything so looking at uh quickly at the constraints V and year 10 to the fifth so we want something linear or at least n like and at the worst case probably um my first thought is DFS with um with memorization but I don't know that is good um how many colors are there maybe that could be a thing is that oh um colors can be of lowercase English letters that's interesting right of course it's interesting because that means that there are most 26 colors and then now the question is um the question is can you just do it for every color right um because then now you have a dag or well okay so you have to the few components there's um you know you have to find a cycle if there's a psycho it's going to be a negative one that's pretty standard stuff and then let's say the no side goes then by definition is a dag because there's no psychos um and then with a dag you can do um dynamic programming uh for each of the colors and then you have 26 and dynamic programming in this case is just going to be linear uh or V plus e which is should be fine and then times 26 which is a little bit slow maybe but should be okay so yeah let's do that I think that should be fast enough um yeah right um so now first we have to do the psycho thing uh how do you download as a psycho if there's a back Edge going to something that's not the parent right so we're gonna do that before quickly yeah and we could do I'm gonna do it with that first search um or recursion maybe I could do a breakfast search or a queue but um I think it doesn't really matter that much either way so uh let's see uh and it's your link with colors almost typed out of colors but yeah um he is uh adjacency list is it good I just and this is a chemical right this is a what do you call it this is a tag is what I mean so it's a directed Edge so we have one it's going from A to B right okay just wanna make sure that I get the direction correct okay now determine whether there's a cycle right and then yeah my fingers that should be pretty free it should be pretty straightforward uh I don't it's been a while I have to remember how to write it uh or like with the edge cases right I'm tempted to just like you know have her used uh and this is what speaks to what sometimes when I'll practice on certain things it does take a little bit of time just like go for the education and then re-proof stuff right where you have our re-proof stuff right where you have our re-proof stuff right where you have our practice and you know this is the difference between a lot of waiting points if you care about competitive and contests is that you know I'm just thinking about edge cases and forgetting how to handle in them and then try to prove to myself how to handle them right oh excuse me huh do you do maybe I'll just do a reply for a search then you get a key because the thing that I'm just trying to think is whether I can just go like find a um you know but there could be multiple routes right which is where is it connected this graph doesn't have to be connected right so unless I miss you yeah huh so then you know if we start at the wrong node given like a psycho and a leave or something or a couple of leaves then we have to figure out how to do it without like doing n Square by accident right so that's kind of where I'm at wow I really should be better about this though so maybe this is good practice because I think this is pretty fundamental uh and I probably should be a little bit better about this but hmm but basically you could stop you could find a thing that has an in degree of zero and then what and then you do some recursive thing sure but then what how do you do it for the next one um I guess you could just do like the three color thing I was hoping that I didn't have to that's why I was trying to think about this simple thing but it's been a while maybe I mean maybe I'm re-ending the videos maybe not it's re-ending the videos maybe not it's re-ending the videos maybe not it's always sometimes a little bit hard to figure out which way to go but um okay fine okay I remember now oh oops oh yeah this is this big colors is also a little bit wonky that's why uh um what I always forget it whether you go from white to gray or gray to white but oh well it doesn't really matter just the size they're distinct and then basically can I spoke others I guess we'll just set it this way if we turn negative one right something like that and then now um we set it to Gray and then after the finished processes we finished we set the back way foreign visiting then we return uh true okay I mean and in theory there's stuff to clean up but I guess it always just returns negative one anyway so I think we're good here uh if it's great then is to go to White then we should visit it um that index this is V whoops this would have been way awkward I mean that's sick of course I suppose Indian ones um okay let's see if that works for that case yep uh let me actually make something slightly more complicated than that um just to kind of test this okay so it's still good but still not 100 convinced it's been a while but um okay so then now this is uh no psychos in this graph and then we can just do um you know for we in set of colors okay uh maybe see right then we go um let's say pasta zero how do we want to set it up um this is equal to Max best um calculate let's say calculate C return best and this is just a ways just to hide a loop but I think really um so now we have color and then yeah and end up now I think we can just straight out cash I'm going to use memorization here but yeah I mean okay fine I was going to just like be lazy and just memorize it memorizer memo but I could do it without that um but yeah so basically we go um the ppsc code to uh none times n um has cash and finally just about cash okay let's explain this part too much in this video because I think I do DP in a lot of videos um and it may be wrong so then it'll be very awkward if that's the case so definitely check that out but the idea here is just knowing ahead of time that um well I'll do the DP calculation now get longest but basically this uh dysfunction has you know index can go from zero to n so this is going to be all of n number of inputs and put ideally uh in total this is we press e because we just look at all the edges once um is to quite basically the idea even though you know uh amortized uh or Toto whatever yeah right so then now we just return so then presses you go zero uh for I and range of n um and I have to add the color here actually okay that's okay for shadowing um press is equal to Max pass uh get longest starting from uh I right and of course this assumes that we have no cycle already which we in theory prove that we do not so yeah um and then oh yeah well we don't have to um I guess this is already specifically color so I don't think I need it here it is already in the helper function um because that doesn't change in the scope of this function so yeah if has cash of index return cash of Index this is just normal dynamic programming things or memorization in this specific case um and then basically if it's called colors in index yeah if you go to color then how do I want to write this zero Maybe naming stuff is hard I'm just gonna name it uh current for now and then for we in with my craft thing called adjacency list index um I guess I still need a password so basically now we're just recursively going okay get me the longest uh thing all right plus current and that should be good uh well that should be good if but I forgot to cash long answer though oh um I don't know if I remember to count stuff because best should at least be current that's why because there's no outgoing Edge I was wondering about that best case or the base case okay um just another way I could write it is and then someone like that maybe it's a little bit slightly better okay um just give a submit because I'm lazy to finger badge cases looks okay 1104 streak well it's actually applying very fast but uh yeah what did I do last time because I mostly try to do the same thing no I did the same thing with psycho I thought that okay it's been a while I really need to do better on the psycho stuff this looks actually very similar to what I have now except for that I feel maybe I you know I'm a little bit proud of it okay but yeah uh going over the code really quickly uh this is basically the psycho determination um kind of had to you know that's what I mean by being out of shape and I'll practice right uh but yeah I still got to it so I guess I'm happy about that uh this is just to set up the adjacency list and then here uh it's here just text her okay what it asks the question what is the best color um in the graph taking advantage of the fact that they're only 26 colors and then here is just for each color um to the um the longest path in a dag right and that's a very standard which is a very standard dynamic programming problem which is going to be o of V plus e um which sometimes can be slow because of the size of the e but in this case um V plus e is pretty fine um cool uh let me show you the top again let me show you the bottom again if you'd like to pause and kind of check out what I did uh but that's all I have for this one uh yeah let me know what you think stay good stay healthy to good mental health I'll see you later take care bye | Largest Color Value in a Directed Graph | largest-color-value-in-a-directed-graph | There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`.
You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the `ith` node in this graph (**0-indexed**). You are also given a 2D array `edges` where `edges[j] = [aj, bj]` indicates that there is a **directed edge** from node `aj` to node `bj`.
A valid **path** in the graph is a sequence of nodes `x1 -> x2 -> x3 -> ... -> xk` such that there is a directed edge from `xi` to `xi+1` for every `1 <= i < k`. The **color value** of the path is the number of nodes that are colored the **most frequently** occurring color along that path.
Return _the **largest color value** of any valid path in the given graph, or_ `-1` _if the graph contains a cycle_.
**Example 1:**
**Input:** colors = "abaca ", edges = \[\[0,1\],\[0,2\],\[2,3\],\[3,4\]\]
**Output:** 3
**Explanation:** The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored ` "a " (red in the above image)`.
**Example 2:**
**Input:** colors = "a ", edges = \[\[0,0\]\]
**Output:** -1
**Explanation:** There is a cycle from 0 to 0.
**Constraints:**
* `n == colors.length`
* `m == edges.length`
* `1 <= n <= 105`
* `0 <= m <= 105`
* `colors` consists of lowercase English letters.
* `0 <= aj, bj < n` | null | null | Hard | null |
935 | Hello everyone welcome to my channel code sorry with mike so today we are going to do video number 75 of our dynamic programming playlist ok lead the number 935 but I am promising see these are many companies ok let's see the name of the question night dialer now look attention What Dena wants to say is that you will know that the horse which is good in chase, which is called a knight, you will know its move, it moves in one, two and a half, right, one, two and a half, or if you are here, then one, two and a half or Then if you are here then it is one two and a half, one and a half, then look, it is written here that if the horse is here, then look, one two and a half, it can move like this, it is fine, then this is for you. You know, okay, so a chess knight can move a knight in the chess diagram, or I told you how to move like this, or you would already know, okay, now what are you saying, we have a chess knight means a knight was given to you. Went and was given a phone pad This is your phone pad Okay now look pay attention What is the question trying to say It is saying that an integer will be given to you Return How many distinct phone numbers of length can we dial Okay you are allowed to place the night on any numeric cell initially and then you should perform n -1 jumps look here it is perform n -1 jumps look here it is perform n -1 jumps look here it is specifically said n - 1 jumps specifically said n - 1 jumps specifically said n - 1 jumps is an obvious thing like let's say you are told that two digits We have to form the number of n, the value of n is two, okay and it has been said that you can start from anywhere, so you will do one thing, right, if you keep night here, then a one digit number will be formed. If you want two digits, then you have to move one more step by 40, that is, you have to move one more move, okay, then look after this, you have to move one more move, so where can I move one, so it will move like this, one, two and a half in one jump. How do you know that in a jump, the horse walks like this or walks like this, then I am showing it by walking, I show it with a red pun, one possibility of this is that if I start the night from one. If he did then yes, how many more moves are left with him, n My moves are left, that is, one jump is left, there is only one jump, so in one jump, he can come here to S. Okay, now there is one way, this is one. What is the method, one can come here from A to A, see one, two and a half can go like this, look, two possible ways have been found from here because one cannot jump up, neither will one go there and here. If you can't even go left then these are the two possible ways. When did it become two possible ways? When you started from one. If you started from one then you are getting two possible ways. Okay, what other numbers are you getting? Let's see here. Let's also write, do you remember, you started with one, your digit became one and after that it ended with six, it was 166, one more number, look, 8 is 1, right, we had to make a two digit number, this is a two digit number. Here are the numbers 16 and 18. It started from one and landed at six. Here it started from one and landed at eight. So look, it became a two digit number. 16 and 18 are how many possible numbers it got. Okay, when it landed at one. If you had started, you are seeing the starting point. This is my one. This is my starting point. Okay, so if we accept two possible paths, then we remove all these. Now in the question it is said that you can start from anywhere, so yes. It is possible that I would make him start from two, it is okay, so if that guy starts from two, the horse, if he starts from two, then what are the possible numbers that can be obtained from here, on one jump, this and this. If possible, one can take one here, one can take two, one can take here, okay, so 27 and 29, 27 and what else did you get, 29, okay, two possible ways, you got it from here also, okay, so think in the same way, once you have seen the horse. Placed here, then placed here, okay, it is given in the question, you have to keep it only in the numeric cells, okay, so from row to row, you can place the horse in so many places, okay. After that, you can then explore how many numbers it can make, like let's assume that when I placed it on one, it is okay, then look, it made two numbers, when I placed it on two, then look, it made two numbers, okay, now let's assume that it is one. And let's take an example, let's say I kept it at zero, it's okay if I kept it at zero, here two can go, one will go to six after hitting two and a half and one will go to four, then see what you get. 0 S What else is there 0 4 Is it clear till now, so one last thing and I will tell you again, do not get confused about that thing, look at that thing, one last thing and let me tell you what I had just said that you should accept it as an example. The value of n has been given that we have to make a three digit number. Okay, so see, when you start it from any number, assume that you started with four, then how many more jumps does it have to take, sorry now. How many more long digits are needed? We need n-1 length digits because we have already needed? We need n-1 length digits because we have already needed? We need n-1 length digits because we have already taken four. We need three long digits, we have taken four. Now we need two more digits. That's why I am saying, look, N can jump and kill, okay. If it is clear from here, if you can hit two more jumps, then maybe you will hit one jump. Let's assume that you have reached nine here. Okay, so this is one nine digit. There is still one more digit left, so you can hit one more jump. So where can one go from here, one, two and a half, two can go from here, 492 Okay, so this is one possible way, now it could go from here to four, then from here, one, two and a half can go here, many possibilities. Okay, but you should have understood that the cell from which I started has already covered one digit, here I started from four, let's assume how many digits of n -1 and length are left. If there are left how many digits of n -1 and length are left. If there are left how many digits of n -1 and length are left. If there are left then it is okay and the answer can be very big. We will proceed by modulating the power of 10 by 9 by 7. Now see, let's build our intu. It will be a very easy approach. Trust me okay. So see, I have given you a clear cut answer in the question. That you can start from any cell, it is okay for a given N, you can start from any cell, you can start from zero, from one to two to three, after trying the possibilities from all the cells, as many ways are coming. If we keep adding all the answers from all the cells, then what I am saying is that for cell is equal to 0, we will start from 0, cell is equal to no, that means we will hit zero once, we will hit all the tries, after that zero is finished. Then we will try to kill one by one and so on, okay cell plus will give a chance to all the cells to start, okay now look, pay attention here, what I said after this, brother, let's assume that we have started from cell number zero. Okay, so what should I say, okay brother, start starting from cell zero, you are fine, but now you are at cell zero, so zero has come in your digit, okay, and how long was it, let's assume it was of A length, asked. The number which is A should be of length, so it has become zero, now how much is left, remaining n-1, so here we will say n-1, so here we will say n-1, so here we will say that okay, now we need a string of length n and from which cell did you start currently. If you have started from this cell, then it will bring my answer. Let us assume that it will bring your answer. Whatever answer it brings, we will keep adding it to our result variable. Let us assume that if the result is equal to 0, then the result plus is equal to this. We will keep adding, okay, in the same way, when the cell is equal to one, right, when the cell is equal to two, after my zero, when the cell becomes one, okay, then I will say, okay, now I am starting from one, n - 1. We need more cell digits and n - 1. We need more cell digits and n - 1. We need more cell digits and here I will send only the value of the cell, I am starting from one, okay, now pay attention to one thing, I think we have done the most major part, okay, now let's just go to our solve function. Our problem will be over, okay, so look now, I have not said till now that I am solving through DP, I have not said anything yet, I am just doing the same from every cell as I was told in the question. I am trying to start, okay and I am trying to get the answer. Okay, now I write the solve function, once it will be seen later, whether d is there or not, n is -1, so what do I send here? is -1, so what do I send here? is -1, so what do I send here? Here I take the name of the int variable as anything, I take n only and here I take the cell, okay this is the solve function, now I have to finish it, now look pay attention, here I will run one thing and show you the value. Let's take the value of n as 2. Okay, now look carefully, due to two values, your for loop is going on. This is the cell with cell = for loop is going on. This is the cell with cell = for loop is going on. This is the cell with cell = 0. Let's assume that you started trying from row, now what have you called? Solve n. - 1 because one length means Solve n. - 1 because one length means Solve n. - 1 because one length means one digit, you have got it, okay, now you need one more digit, okay, so sent n - 1, need one more digit, okay, so sent n - 1, need one more digit, okay, so sent n - 1, and now from which cell did you start, from the row number cell, okay, now see from where you Where can you go? With 0 you can go. 6s is fine and with zero you can go. 4 These are two places you can go and you can't go anywhere. Okay, with zero you can go only these two places and nowhere else can you go. If it is visible then I also write that from row to four you can go to six, so first let's explore the case of four. Let's assume that you have come here now, if you are on four, then it is an obvious thing. We will have to go and explore the place, is n't it okay, so first we will go to four and explore, after that we will return from there, then we will go to six and explore, this is where I got the feeling that we will have to write recurs, so first let's explore on four, see. Now I have come to four. Okay, so the neighbor of zero was four, so that means going from zero to four. So now I have come to four. So when I came to four, remember what I called. Solve n - 1. So here. But I write the function, Solve n - 1. So here. But I write the function, Solve n - 1. So here. But I write the function, n was n and n -1 means what is one n was n and n -1 means what is one n was n and n -1 means what is one and my cell was zero. Okay, now I found out from here that from zero I can go to four. If this is a possibility then I can go from row to four. So solve I went to row, I went to sorry four now I am on four and see this was n, now we will do n - 1 so and see this was n, now we will do n - 1 so and see this was n, now we will do n - 1 so here came row right so see when I came to four my value of n became zero. It is obvious that we had to get two digits, we got two digits, one row and one four, when four came to four, the digit became zero, then what is the meaning of the digit being zero, that we have got our one answer, 0 and then the answer of two digits. Only after getting it, look at the value of n, it has become zero, right? If the value of n has become zero, then I will return one from here that brother, I have found a way in which you have got the two digit number, 04, that is fine. Okay, so one has come from here. Now remember, there was one more possibility from this zero. Remember, six could also have come from row, so we will call again. Solve this is one, so we will call by adding -1 to it. call again. Solve this is one, so we will call by adding -1 to it. call again. Solve this is one, so we will call by adding -1 to it. 1 -1 0. Okay, 1 -1 0. Okay, 1 -1 0. Okay, where can I go? Six can I go? Okay, now I have come to six, so that means I have come here. Okay, so look, the value of n has become zero. It has become zero, which means we have got a two digit number. It is zero and this is six. Remember, we started from zero and when we reached six, we got a two digit number. See, it also has two digits. From here, I will tell you, brother, yes, get one more answer. If I have already sent one, then one more possibility has been found, so see, I will keep adding as many possibilities as I get. One got from here, one got from here, 1 point is found. Okay, so now you have noticed that if we assume the value of n is 3. It would be fine, if the value of n was 3, then here I am seeing that if I pass 3 my t is two then here comes t, then after two here comes this one, then even after this there are more possibilities, don't you see? Let us assume that you are four, so where can you go with four? You can go with four, one thing you must be seeing is that you can go one, two and a half and you cannot go with four, right? If you can't go anywhere, then here I will also write that brother, where can you go from four, if you can't go from three, then you are noticing one thing, you will have to make an adjacency list as to where from which node you can go. You can go, okay, if you make this edge, then you can easily find out that yes, from zero I could go to four and from six, from four I could go to 3 and no, okay and so on for all the digits. We will make the adjacency list here, okay so this is all, what will we do first before completing the code, what should be our first step, here I write the first step, it is the ADJ list, first of all we will make the adjacency list, okay. And now see how easy our solve function has become. What did I tell you just a little while ago that if n becomes 0 then it is okay? If n becomes zero then it is an obvious thing. What will I return? Will I return one? Why? What does zero mean, I have got all the digits, we have got a number, two digits means N digit, okay, A has become zero, okay, now after this, if A is not zero, then A means now this cell. You will have to see where you can go from there, so what I said for Int and Neighbor is fine, Neighbor can either tell the next cell where the next cell can go, how will they be extracted, we will store it in the adjacency list of cells. Okay, now look, pay attention to the Nex cell, you must be understanding this, look at Adjacency of Cell, assuming the value of this cell is zero, then what will we store in the zero in the Ad cell, 4 s, all three one by one. We will hit try on both of them, we will hit try on four once, here when four comes, we will call recursion for four, solve n-1, we will send it and solve n-1, we will send it and solve n-1, we will send it and send the next cell this time four will go, then this for loop is still going on. Then the turn of six and six will come, then there is no and so on, there will be some answer from everyone, so here we take the result equal to 0 and meaning or take the name of whatever variable, answer is equal to 0, answer plus. Eq to solve is fine and in the end, as soon as all these neighbors finish cursing, return answer as it is. Till now I have not even mentioned DP, I just wrote the code of what we learned from the diagram and what was asked in the question. As it This is fine, there is no mention of DP anywhere. Okay, we have written our rectors by writing a simple for form. Now you must be noticing that look, we can memoize this, write this, we can definitely memoize it with two parameters. Do you know what the value of the cell can be? The value of the cell can be either zero or one or two and so on or nine. The value of the cell can be three, nine or 10 digits. Here it is, apart from this there cannot be any digit, okay, and n will be your given, okay, the maximum value of n I think is 5000, okay, so we can do memoization easily, but without memoization time complexity time. Here we did not do any memoization, normal recurs is very simple and solved it is okay, so look at the time complexity, pay attention, if you are going to make the adjacency list, make it complete once yourself that from zero you can say where you are from 46 one. 6 8 You can go, look, this is a forest here, isn't it? Remember from the forest, where could you go? From the forest, you can only go here and 8 and you can't go anywhere else. Okay, so take this adjacency, so first you have to go. If you have to make that adjacency list then make that adjacency list here and so on 0 then 3 again you know you can go to three places th or zero also similarly from six you can go to three places 170 and now notice see f You can't go anywhere from 5. If you come at 5 then look, you can't go anywhere from 5. If you go out somewhere after one or two and a half hours then you ca n't go anywhere from 5. Similarly, draw the Adjacency List in advance and make it yours. What is ADJ and how to make ADJ, you must already know it, so keep one thing in mind, here you are looking at the worst case, maximum, how many places, how many possibilities are there for a given sale, there are three possibilities, I am telling you in the worst case, not more than three. If it is possible, then for a given cell, worst case, we take three possibilities, then from each cell you have three possible ways. Imagine that you have three possible ways and you are also hitting a try from every cell, then power of 3 n is time completion n, right, we have n. If you want to form the length, then it is okay, then you are looking at the possible maximum for each character. There are three possible ways to go, then it will become angular. If we did not memoize, then it is okay. But yes, if we did it with memoization, it is okay if we did memoization. So, I told you that two parameters were changing in the solution, the first was n, the second was our cell. Okay, so you know the value of the cell can be from row to nine only, so we DP, whatever we adopt, there are two parameters in it. There will be one for n and for the cell, okay, we will take n + one for n and for the cell, okay, we will take n + one for n and for the cell, okay, we will take n + 1 and we will take cell + 1, okay, so 1 and we will take cell + 1, okay, so 1 and we will take cell + 1, okay, so how many states are there, n * k, if there are n * k states, how many states are there, n * k, if there are n * k states, how many states are there, n * k, if there are n * k states, then time is also space, our o of n * k. And is also space, our o of n * k. And is also space, our o of n * k. And look at the value of k, it is constant, it will be from 0 to 9 only, so the value of k is only 10, so if seen overall, then how much has o become n, because k can have only 10 values, the maximum of k is Let's assume that the space is also our o of n. Let's assume it is clear till here, then this is our memorization with recurse. Let's quickly code for recurse memorization. After that we come to the bottom up and you wo n't believe bottom up. This is way more easy. Now see, only the code with recursion will be converted at the bottom. So let's quickly code it with our recursion and memoization. Okay, first of all let's take a variable named result. Okay, adding answer in it. So, I told you that we will try from every cell. Cell is equal to no cell plus. Okay, now whatever answer comes, we will keep adding it. Result is equal to result plus solve. For now, just use one cell here. How many cells did you take, n - 1 length left, you are ok, n - 1 length left, you are ok, n - 1 length left, you are ok, this is the value of the cell, now you start from here, you will return the result in the last, okay and in the question it is said that int m = 1e to the power of 9 + 7. We will keep taking modules = 1e to the power of 9 + 7. We will keep taking modules = 1e to the power of 9 + 7. We will keep taking modules here, okay, so look here, I will also do module m. Okay, now remember I told you what we will do, we will also make an adjacency list from which cell you can go to where, so see that. I had already created it here, I just copy pasted it here. Okay, so I have created the adjacency list. Now we don't have to do anything else, we just have to write a simple solve function. Remember, I told you that if the value of n is It has become zero, meaning we have got our number of length n, so return one, that is, we have got a number. Okay, now what did I say here, now we will go to all the neighbors and try to hit int and where is the next cell? We will extract the ADJ from the cell till this point is clear. Okay, now the result is equal to the result. No, here we take a separate variable for the answer that came from this. Answer is equal to the answer plus call the solve. Okay, n - 1 answer plus call the solve. Okay, n - 1 answer plus call the solve. Okay, n - 1 because one more cell. We have used the next cell. Now on which cell are you standing? Stand on the next cell and n - 1 length Stand on the next cell and n - 1 length Stand on the next cell and n - 1 length is left. Okay, we will do module m of this also. Now we will return the answer in the last, isn't it clear even here, memoize it too. Now let's do it, see the maximum value of n is given, it is 5000, so I take 5001 and remember the maximum value of the cell was 10, so take 10 and what else is there because see what can be the value of the cell 0 1 2 3 4 5 6 7 8 9 Isn't it, that's why I have taken 10 here, okay and let's set our memoization DP to Memset t my size of t okay, similar Java code will also be available, don't take tension about that and Before returning here, store the answer in Off A Sale and put a memoization check here that if we have already stored the answer for Off A Sale then return it T of A Sale is ok, we will see after submitting it. We are fully hopeful that we should be able to pass all ten cases, indeed yes we have solved this question. So look friend, let's quickly come to the bottom up and the code of the bottom up will be exactly the same, we will convert it, this is the solution, isn't it? We will convert this in the bottom up. Now see how to convert, then see we come to the bottom approach. Remember this recursion code, we have just written it. Look at this. Solve. When we used to make a call, two things were required: A and Cell means a required: A and Cell means a required: A and Cell means a state which is defined by these two things A and cell. Okay, so our bottom up will also need two variables. Okay, that means DD is needed, so what will I do, I will take one DDP, okay two. What is the meaning of the dimension? What is the meaning of TI? Do you know the meaning of T? What is the total number of distinct phones? Numbers are ok of length i when you are at cell j ok if you If you are standing at cell j and you want a number of length i then total will be so many veg of a j you can get so many numbers ok do this st definition Now look, pay attention, we will derive the code from this, pay attention, if the value of n is zero, then the answer will always be one. It does not matter what the value of the cell is, if the value of n is zero, then we are returning one. This means that What happened to the value of t of n, if it is zero, this zero has been put, isn't it, this is my memory, the length of the number was the length, if n becomes zero, then the cell may have any value, the answer will always be one, see, every time it is one. Okay, so what can be the value of the cell? The value of the cell can be zero, it can be one, it can be two, and so on, so here I have written the cell, so first of all this is the number. We will do that for int cell e to 0 cell is less equal to na cell plus na this is initialize this was my base case in recurs and here we initialize it like this t off if n0 is cell Whatever is the value of , t off if n0 is cell Whatever is the value of , t off if n0 is cell Whatever is the value of , its answer will be one. Okay, remember, we have derived this from the base case. This thing is clear, we have covered it. Now let's come to what we go to the neighbor. Okay, see. Pay attention, since you have found out for n = 0, remember Pay attention, since you have found out for n = 0, remember Pay attention, since you have found out for n = 0, remember this was the length, you have found out for n = 0, this was the length, you have found out for n = 0, this was the length, you have found out for n = 0, now you have to find out for n = 1 n = 2. now you have to find out for n = 1 n = 2. now you have to find out for n = 1 n = 2. Okay, so here I write for int. i equ to look, this row has been removed, let's start with i = 1, okay start with i = 1, okay start with i = 1, okay i < n, you are okay, either take i, n, or else i < n, you are okay, either take i, n, or else i < n, you are okay, either take i, n, or else write like this, i take i n - 1, look at n- write like this, i take i n - 1, look at n- write like this, i take i n - 1, look at n- Why is there 1, remember I told you earlier also that you have to take only n more move jumps because you are currently starting from some cell, then how many n-1 how many n-1 how many n-1 cells and b more will be left, okay, this thing was important. Here I have done the same thing that now I am taking out for the remaining length. For one length, it is okay till n my length. Now see what I said after this that the length is this, now we will check from all the possible cells that for int cell it 0 cell is lesson equal to no cell plus no see this is what we used to do, we are trying every length and we are trying every cell, we used to do the same thing in dicks too, now look at me two There were states, one was length and one was cell, so look at the for loop of both of them, we have written that this is of length, this is of cell, this is what happens, to convert in recursion, we have to write for loop, bottom up. To convert to , bottom up. To convert to , bottom up. To convert to , we did the same and ran a for loop of length and a for loop of cell. Now remember what we did inside after that, we went to the neighbors to the right, so we will do the same here also, end answer is equal to 0 and all We will take out the answer that we get from the neighbor. Okay, so here I am doing the same thing. Now look, int answer is equal to 0. Now let's go to all the neighbors for int and next cell, current cell, what is my cell, how will I go to the next cell from ADJ. We will extract it, okay, inside the for loop, remember what we used to do, it was very simple, answer is equal to answer plus, now look pay attention, here we used to call solve, then and remember there we used to call n-1 and remember there we used to call n-1 and remember there we used to call n-1 and call next cell. Here n-1, what is the length? Here n-1, what is the length? Here n-1, what is the length? Look, here we are talking about length, so instead of n, we will do aa-1 and what will we do instead of next cell do aa-1 and what will we do instead of next cell do aa-1 and what will we do instead of next cell solve, we will do t and is this what happens? In Deep, the conversion is done i-1 next cell i.e. n-1 i.e. done i-1 next cell i.e. n-1 i.e. done i-1 next cell i.e. n-1 i.e. i-1 and next cell, we were doing the same i-1 and next cell, we were doing the same i-1 and next cell, we were doing the same in Deep in Rashan, that is why I said that you can derive bottom up from recursion only, you can do it in maximum queries. Yes sometimes it is quite tricky but in maximum questions you can find this way till now it is cleared and yes do n't forget to take module m okay as soon as this for loop is over okay means you currently t off a comma cell. Got the answer of Is equal to two answer isn't it? After that then cell will be plus then cell = T will be 1 then if we be plus then cell = T will be 1 then if we be plus then cell = T will be 1 then if we find out the answer of its neighbor from one then the answer of t will come out then the answer of Titu will be 4 of T 3 and so If it is on, then in this way we will take out everyone's income. Okay, now pay attention to one thing, this for loop will completely end. The entire for loop will end. Now this is a very important thing to pay attention to. Now see cell equal to 0 till cell e. Lesson Ekt 9 Cell Plus is not for loop written, see why it is written separately, you will understand, don't take tension about it, you see, it was said in the question, brother, we need answers from every cell, we have as many possible answers as possible from every cell. So now we will find out the answer from all the cells. We had done this by breaking and found out the answer for all the short lengths i = 1 i = 2 i = 3 but the answer has been found out the answer for all the short lengths i = 1 i = 2 i = 3 but the answer has been found out the answer for all the short lengths i = 1 i = 2 i = 3 but the answer has been asked for n, right? So now look, pay attention. Since you are starting from cell zero, how much length do you have left? N-1 length is left. You need the how much length do you have left? N-1 length is left. You need the how much length do you have left? N-1 length is left. You need the answer of this much. Okay, and from which cell were you starting? You were starting from this cell, okay. Here we make our result equal to 0, result plus equal to t of n-1 cell, okay result plus equal to t of n-1 cell, okay result plus equal to t of n-1 cell, okay and return the result in the last, this is what we had to extract, see, checked the possibility from every cell, remember the minimum length, when called recursor. Okay, so our solve function was from where we used to call the solve function, remember for cell e 0 cell len e 9 cell plus okay then remember we used to call from there we used to send recurse solve n-1 and then send recurse solve n-1 and then send recurse solve n-1 and then cell We used to send OK and keep adding it to the result, after that we had defined the solution somewhere, so here too you are doing the same thing, brother, look, wrote for loop, sent n-1 and took out all the cells and got the sent n-1 and took out all the cells and got the sent n-1 and took out all the cells and got the answer. Removed Datchi, let's finish it, so now look let's come to our bottom approach, all these will remain exactly the same, the ADJ and M which were defined are fine, let's remove all these and also remove the recurs, right from here because right now We have to do it from the bottom up, so we removed all this. Now look here, the result is equal to 0. Let's remove all this. Now I define my deeper vector of int which is DPR. This is our t. Okay and now our How much is the answer asked what is the vector of n int total how many cells can there be 10 cells can be from ro to na ok now you will know that int cell e 0 cell e le e 9 cell plus that t of 0 The value of the cell was one, I told you this, what is my base case, it is clear till now, after that it is very simple, when i = 0 is removed, very simple, when i = 0 is removed, very simple, when i = 0 is removed, then let's start the lesson from i = 1 then let's start the lesson from i = 1 then let's start the lesson from i = 1 till equ n-1. Ka i+ P Ok till now it is till equ n-1. Ka i+ P Ok till now it is till equ n-1. Ka i+ P Ok till now it is clear, after that for int cell it is 0 to cell lane equt 9 cell plus we will try everything ok int answer equt 0 for where can we go from this cell and next cell We will take out the ADJ from the cell, till now it is clear that the answer is equal to answer plus next cell i.e. solve off n-1 earn cell i.e. solve off n-1 earn cell i.e. solve off n-1 earn next cell. If we used to do this then instead of solve we wrote t, instead of n-1 we wrote i-1, it wrote t, instead of n-1 we wrote i-1, it wrote t, instead of n-1 we wrote i-1, it is ok. And the next sale will definitely be the next sale, it is clear that we have done a very good design here and it has been made in a very simple way, so actually there should not be too much fear of bottom up, right? That fear will also go away. Off is assigned to the cell here. Okay, after that it is the same in the last for int cell e 0 cell e lesson equal 9 cell plus result e equal to result plus t off remember used to solve n They used to call -1 n They used to call -1 n They used to call -1 and whatever value of cell they used to call, they wrote t instead of solve and the rest of the same, they wrote cell here, okay and in the last module, make M, okay, let's submit and see. Hope fully we should. Be Able To Pass All The Test Cases Indeed Yes We Have Solved This Question Using Bottom Up Also Any Doubt Raise In The Comment Section Try To Help Ya Out See You Go In Next Video Thank You | Knight Dialer | orderly-queue | The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | null | Math,String,Sorting | Hard | null |
904 | hello friends so today in this video we're gonna discuss another problem from lead code problem name fruits into basket so this is a problem from lead code which is a uh like a google interview recommended problem so it is somewhat asking google interviews so that's not a problem from those categories so i have made a video on that so stay with me and i will also make you understand this problem is so you are given a farm in which there are different type of roots which are lying in a row from left to right okay so as you can see like you're given an error now what you actually have to do here is you have a basket or like you have two baskets actually now every basket can like acquire only a single type of fruit so you have two basket and like only one basket can acquire a single type of fruit and like you have different type of fruit so the first food is of type one the second food is of type two and third photos of type one and so on now what you actually have to do here is every basket can hold any amount of roots like the first basket can hold any amount of food but the first basket should hold only one type of food okay now what your actually goal is you can start from any point and keep on collecting the fruits till you cannot collect any more so and you have to stop at any point at the point you cannot collect the food so i will tell you in simple term it states that you have to find out a sub array a contiguous sub array which only cos consisting consists of like at most two different elements so as you can see the maximum length of a sub array can take a sub array such that it only consists of at most two different elements now as you can see in this it is only one to two so the answer is like three because i can take i move from like this point to that this point and then it only consisting of fruits of type one and two in this i can start from this point and go till the end okay in this i can go from this point and go to the end so as you can see it only consisting of two fruit of type two and three see the last example i can go from this point and have to stop at this point because i can only collect fruits of type only two types so it is like one and two if i either collect this part of this part the number of total different number of roots will increase so in simple terms you have to find out a sub array it only consists of at most two elements okay so now uh you can pause this video if you want to like think about this problem but like it's a general error like a standard problem which can be solved using two pointers because you have to find out a contiguous sub array which consisting of only two different like atmospheric elements okay so the simple condition what you can easily write in the start is if the whole array is just consisting of only one type of element of two types of element like one type of fruit or two type of force so in that case you can take the whole area i hope you get the point so the basic like in the basic test case or like a basic uh answer what you can do here is just find out the total number of different fruits in the initial in the whole area so what you can do is you can make a set because that only consists stores only at one instance of everything so eat it over the whole fruit array and insert every fruit in that set which will give you what is the different type of fruits in this whole vector if it is less than equal to it means that it is one or two so it means that because the total number of foods is one or two in the whole area you can take the whole arranged answer so the answer is just like uh what is the size of the because you are taking the whole exercise i hope you get the point else in other cases what you actually have to do is because there are more than two type of fruits or three or four types of food you have to find out a contiguous available in that type of problem what you can actually like see in this problem is i can show you the part one two three one two one three what you can do is just move left right make one pointer at this point and another pointer move from this point so let's look at this and you have stored up like you have two three variables which is like a total variable which stored that how many different total types of fruits you have till now okay then you have a frequency variable which is storing how much fruits of each type you have till now okay and what else i have two pointers and total yeah so what you can see here is this is some sort of j which is like the this is the right pointer and j is the left one now as you can see when i'm seeing the first fruit for the first time because i am moving for left right i do not have seen any fruit till now i have seen the first food for the first time and my total is here because i do not have any fruit till now like not however different fruits i have till now zero i do not have any fruit still now so what i can do here is because i have seen a new fruit i will increment my total because now i have taken one type of food and the frequency of this like how many type of fruits of one type i've seen one so fruit of type one i've seen one now again now the other fruit is two so i will make my i go from this to this j will remain to this point because i'm like making a contiguous sub array so now i'm seeing two is another a new flute so i will increase my total number of fruits it will become two and a fruit of type two is also frequency one okay now i am on this point now i am again seeing a new food now i cannot take this as a new fruit because if i take this as a new fruit then the total number of fruits i have is three but i can only take a fruit of type like only two types so in that case what i can do is i have to move my jth pointer from left to right still at that point in which i like i will move my gh pointer from the point at which the jth pointer is moving towards right so that i will remove out one instance of a fruit completely what i mean by this is let's do i have one two three my i is at this point and my j is at this point which is telling me that i have a continuous sub array till this point which is like all the elements are only one or two like uh i have only two instance of numbers when i come to this point now the number of instances are three now i have three different numbers three different fruits so what i can do is to reduce the disk out i can move my j from this point to the right so can this sub array is perfect no because till now i also have different roots of three types is this is perfect now is this is perfect yes so i can only come to like i have to move my j till a point says that all the instances of one fruit are disappeared so how we can do that i have stored different instances in frequency so frequency as you can see frequency is storing that okay i have one instance of one so i will keep on moving my j till that any fruit becomes zero i have only two types of fruit one and two if any fruit of them become zero which means that i have deleted all the instances of that food so i will keep on moving my j so now my j will come to this point and i have not taken this root now so i will make this zero and as you can see now at this point my one fruit has disappeared now i do not have any one fruit till now so now i can add the fruit three at this point in my vector i hope we get the point so i can add three now if i cannot see the total amount of fruit still now is again three but now my number of fruits of type one has become zero and number of fruits of type three has become one and before that as you can see before changing before moving my j this actually tells me that this is a valid answer this is a valid sub array because after adding three it will become invalid till two like till from the starting j till two this is a valid sub area because it only consists of two different type of numbers so what you can do in this in that case because you know the starting position of j this is i so i minus j is the length of that sub array which is valid this can be the maximum this cannot be the maximum so i have to maximize this sub array length okay now 3 is there and this is my i now i go to the next i which is like this which is one now as you can see now again the total number different elements increase and it becomes three so i will again move my j to this point so now the total number of two will become zero and the number of one will become one so as you can see continuously the frequency is such that only two numbers are having frequencies other others are zero and because also at this point at changes i changed my uh like i changed because my total number of different elements change this is a valid sub array till now if i add this it will become invalid so before changing out before deleting this out maximize this particular sub array element and you have to do this continuously for all the sub arrays so then this will become two okay then like two is removed out so this is not a particular sub array which is like three one now i will add again two now because again two is added what we can see here is this is again forming an invalid because three one two are there so remove out three and now my j is at this point my j is this on this i and i is on this two so now if i add this to this is again valid because both the numbers are same if i now as you can see if i again this again one it is valid because see this is valid because i am only adding numbers which are not different as you can see when i add 3 now because 3 is added how we can say that this is a new number because see when i adding 3 the frequency of 3 is 0 at this point frequency of 3 0 which means that i am adding a new instance if a new number is inserting into the object in the frequency vector it is a new number and the total is 2 and i'm inserting on the new number which means that i am incrementing the total number of elements and i cannot do that so i will keep on deleting the numbers from the back so that the only instance will remaining is like only one type like only one or two type elements so as you can see now it is my j is on this i see if i delete out this one from this frequency because my frequency of this become two because i've seen two times once and two times two if i delete down this one will my frequency of one will become zero no which means that there are still some ones remaining in this sub array i cannot mark this as a perfect one so i will make this one and i will keep on moving my j so i'm now i'm my j is on this two cannot delete this out yes i can delete this out but still as you can see i do not i cannot delete down i cannot make this a valid sub array because there are still some twos ones so i will again move my j to this point now if i delete this two again now my frequency of two will become zero now as you can see now at this point if i take this sub array which is only consisting of one and three it is valid i hope you get the point so this is how we are moving this whole part now so i can move to the fourth part we make it more clear so uh so as you can see my only change my change which i've told you i will only measure what is the length of the sub array when i find out a different number when i find out that okay i'm adding a number which is new to my answer which is not like i have not seen this it is incrementing my answer so in that case what you can do either in the end you can check the irj or else you can add a fruit in the end which is not in the whole sub array because that number is an invalid field but as an invalid food that number is very large and the program will think that this is a fruit which is not seen and i have to add that food and if i want to add that fruit i will check that condition so what i have told you as you can see the total maximum length of the fruit the value of the fruit is 10 to the five so the maximum food have 10 or 5 so insert a fruit of 10 to 5 plus one so this is not a valid fruit this cannot happen in this vector so it's a invalid food but i'm inserting in the end i will tell you why so this is n this is j which is like the left pointer this is total which is the total uh like the answer uh whatever i can say the total number of different fruits i have till now this is the frequency vector which is the maximum answer we'll find out so we'll move my right pointer from zero to all the value till then now i have different uh categories so i just should go over this part yeah my first category can be i am inserting a new fruit and i'm inserting a new fruit when my total different foods are equal to two i have two fruits which are different but i'm inserting a new fruit so how you can check that if i'm inserting a new fruit my frequency of that fruit should be zero but what i've told you if i have encountered three and i'm inserting three then i knew that this is a new fruit when the frequency of three is zero if that thing is zero it means that i have to insert a new float if this is zero and my total number of different foods is two in that case i'm inserting a new food so before inserting a new fruit i have a sub area which is valid i've told you so i have to maximize it as you can see i'm maximizing my answer and before inserting the new fruit i have to move my j pointer such that one instance of a fluid is completely disappear so what i will do a while loop till j is less than i because i cannot go more than i okay i have two cases i have to keep on deleting a fruit if the frequency of a particular fruit i am on the jth pointer on it is greater than one then i will delete that fruit and then make my j plus one else if i hit a fruit which is equal to one whose frequency is one if i delete that fruit because only one frequency of that food is left if i delete that fruit the whole frequency of that fruit from this strawberry is deleted out because i'm looking over the subaru so i will delete that fruit increment my j and break out of this fold like this while loop because now i have deleted a particular instance of a single fruit all of them so now after that it is done so now i have to add the new fruit which i have seen till now so i will increment my new fruit which is like at the ith point so this is the case in which i am inserting a new fruit in the end in the sub area and also like changing my sub array length to adjust to only store two different numbers else the other case can be i'm inserting a new fruit and my total is not equal to two i'm inserting a just a new food so let's in the start i do not have any fruit in the sub area i'm inserting a new fruit so in that case when i'm inserting a new food for total will increment because i'm inserting a brand new fruit i have inserted a new fruit and my frequency of that food will also increase else in the other case if i am inserting a fruit which i have already seen so i have a sub array which is like one two and the other number is again two so it is not falling under this if condition this is not in this if condition it is falling on a condition in which i am just inserting a food which i have already seen and it is perfect for this sub area so i will just increment that frequent like fruit frequency in this frequency vector i have to get the point i will do this it's like a two pointer thing the i is moving for like a right pointer and the j is adjusting itself if i hit a point in which i have more than two types of it just like a two pointer problem it's a very standard like not too standard problem but it's a very important problem to understand and graphs i hope you understand the logic and the cool part for this problem if you have any doubts you can mention down i will say exponential length recording and bye | Fruit Into Baskets | leaf-similar-trees | You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces.
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
* You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold.
* Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
* Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_.
**Example 1:**
**Input:** fruits = \[1,2,1\]
**Output:** 3
**Explanation:** We can pick from all 3 trees.
**Example 2:**
**Input:** fruits = \[0,1,2,2\]
**Output:** 3
**Explanation:** We can pick from trees \[1,2,2\].
If we had started at the first tree, we would only pick from trees \[0,1\].
**Example 3:**
**Input:** fruits = \[1,2,3,2,2\]
**Output:** 4
**Explanation:** We can pick from trees \[2,3,2,2\].
If we had started at the first tree, we would only pick from trees \[1,2\].
**Constraints:**
* `1 <= fruits.length <= 105`
* `0 <= fruits[i] < fruits.length` | null | Tree,Depth-First Search,Binary Tree | Easy | null |
835 | So welcome to aspects of time but challenge and asked questions images and more share give into images and chief and I want to identify the maximum overlapping and account and between the president in all directions of dietary fats to paneer one 00054 points 151 liquid 9999 honey unique Identification Adham Maximum Boiled Between Two Sub Meter Two Meters And You Can Move One Meters And For Directions Up-Down Left Right Declared In This And Mother Up-Down Left Right Declared In This And Mother Up-Down Left Right Declared In This And Mother For Directions And It's Not Very Complicated Problems Subscribe Computers A Hai So Lets Users Liked His Creative More Westerners Image And Andheri Waste Oil Divided Into Two Parts Subscribe Button Subscription 251 Subscribe Button Subscribe To I 224 Clean Spot Organization Positives This Audit Recent Problem Se Chini To Slide subscribe and subscribe the Subscribe Button And another young man continuously after getting over and chatting what Is The Match Account Point Submit Possible Mid Day You Will Arrive At Solution subscribe to the Page if you liked The Video then subscribe to the Page Is Dam Tubelight Ratio Adhik Complete Matrix Starting From 0 To 10 With 6000 The Matrix - 151 - 134 Hai To Do Only Thing That This Affair One Teaspoon Of Liquid To Dash Live With Right Direction Do Subscribe And Subscribe The Channel And Subscribe To Like You Will Just Before Yourself And Process Playlist Color K Pimples And Process Set This Special President Jasbir Subscribe Must Like Something This and Remains 10 Days As Moving Inter Left Direction Now 20 Minutes Loop Directions With Respect To Where The Opposite Of School Change Reference Points Direction Reverse Iss Pumik subscribe and subscribe the Channel Ko tomorrow morning absolutely ball seam abe today also discus Channel Gautam Shifted To Identify A Baje Maximum Overlapping Account Vipin To Take It's A Private And Get Maths-Maths Account A Private And Get Maths-Maths Account Is Vijay That In Matrix From America That Indigo Airline To Studio Dealing With Arvind The Role Of The Length Of The Following Of A Guy Role quite a requirement of being so don't worry about the point 620 is loose plus points 100 plus that of 150th account main mere inch le 0f of i ko masjid absolutely one and a half aaye ko masjid absolutely studio aaye to maje hai urine treatment accounts were countless PLUS THAT UNDERWORLD DON SONG DOWNLOAD 2015 NOV22 STAFF IS DUE TO RISE A POINT AND SLIDING WINDOW WILL ALL STAFF BUT I WILL BJ I START ANOTHER SOBIE TREATMENT CHIEF JUSTICE REFERENCE POINT OIL SLIDING CROSS HANDED UP TO GOD USB MUSLIMS LIVES WITH CLEARED And Staff's DJ A Particular Peeth Ki Store Ki Now Sahar And Similarly Ko Stop DJ And Ayub Ali Updating Your Pan Clear Now Vijay Bi I Account Sentence Ashwin You Move In The Slide Up 2 Minutes Receive Do Subscribe And Further For The Time Looping Across The Volume Two The Petitioner Marks Account T-20 Unlimited Petitioner Marks Account T-20 Unlimited Petitioner Marks Account T-20 Unlimited Dekh Lena Possible Mein Hi Laut Land Ka Point Start This Battle Iceland I Plus Point Ye Kurushva Yadunandan Z Plus Ki Hanuman Stuart Ki March 28 Box Account Ko Ma Gate March Account Ki A 1 MB Jab Tum Aa Icon Matching Ki And Rate Ke Should Be In Exams Point Reduce Akhilesh Ko Interest Starting Point Yadav Sliding Point Rate Cases For Biya The Sliding Meter Is Andhra The First One Don Is Account The Competition Are Countless Expect Semi Calling and all listen type home o kya hai ki tabiyat search then atul increment quite well in the recent judgment a this is not the correct answer a below time trade ki Akshay more complexity of bus sliding off everyday is oil show world famous pollution and internally do For the record too complexity don't be order of these four simple and tuition hazel flirting and to the times and the total complexity mean mode of and square and audio and rest where for and thank you for watching my video and come payment Clear Respectively in the Proposal Accept Any Don't Feel Free to Get in Touch | Image Overlap | linked-list-components | You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values.
We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the **overlap** by counting the number of positions that have a `1` in **both** images.
Note also that a translation does **not** include any kind of rotation. Any `1` bits that are translated outside of the matrix borders are erased.
Return _the largest possible overlap_.
**Example 1:**
**Input:** img1 = \[\[1,1,0\],\[0,1,0\],\[0,1,0\]\], img2 = \[\[0,0,0\],\[0,1,1\],\[0,0,1\]\]
**Output:** 3
**Explanation:** We translate img1 to right by 1 unit and down by 1 unit.
The number of positions that have a 1 in both images is 3 (shown in red).
**Example 2:**
**Input:** img1 = \[\[1\]\], img2 = \[\[1\]\]
**Output:** 1
**Example 3:**
**Input:** img1 = \[\[0\]\], img2 = \[\[0\]\]
**Output:** 0
**Constraints:**
* `n == img1.length == img1[i].length`
* `n == img2.length == img2[i].length`
* `1 <= n <= 30`
* `img1[i][j]` is either `0` or `1`.
* `img2[i][j]` is either `0` or `1`. | null | Hash Table,Linked List | Medium | 2299 |
65 | Hello hello everyone welcome to our channel code with sunny leone in this video i will be talking about the one up the good problems of displaced number index number 6 and problems of the heart problem sub delete code ok khandwa drops very small amount of likes Register and Dislike Isko Inch And Like Almas Double To The Number By Playing 120 Passion Has Been Obscene Interview Like Facebook Twitter Discussing What Is The Best Solution Of This Problem You Feel Like A Different Topics Like Basic Solution Program 12345 Like And Subscribe And Will Not With A Solution Number Plate Up Into Decimal Number And Subscribe That He Long Diamond Grading Established It's Like Very Much Computing What Like Painters Worship Lord Defined By 10 Per Not Like Us Sign Actress Present Chocolate Least One Digit President Going Into Details And Just Going To Mention In Each And Every Detail Separately To Whatsapp Page And Defense System Editor Also Like Question District Mention In Everything In A Detail In Order Made To Keep The Software Is To Understand This Complaint Number Ward Number Is Decimal Volunteers Were Followed By This Characters Mauli And Capital Ltd World Bank And Anti Jail And Liquid Number Is A Decimal And Anti Sahi And Evolved Alien Optional Written Over 100 Ballot Number Can Be Given Only Enemy Decimal Point Teacher And Flat Number Candidates Selected When Plus This Character Depend Plus Allotment Inch Plus 19th During Twilight These Statements Back R Rid Bro And Sis Team Idioms Here To Kodak And Easier To Understand All This When You Are Just When Everyone Is Just Going To Understand Problems Tricks And Worship And Support Of Such As Possible So Worst Thing And Solving Problems Will An Understanding Problem Statement The Best Possible Way All Want Tips Latest Most Distant Decimal Number And Latest We Should It Clear Interior Is Like Professional Character Post Present Age Plus And Minus Sign In At Least One Digit Up Sid Via Is Consist Of At Least One Digit Bhatk hai tractors option and shipping dead skin quest character here plus and minus and computer ka plaster - character minus and computer ka plaster - character minus and computer ka plaster - character president hai to way request digit plus app and buy at least one reduced blood definition of the teacher and father hangouts per decimal number it's like to character a Plus Minus 2 Inch Plate Optional Time First in This Character Plus the Decimal Definition of Doing It's Good That Present Where and for Every Day Life The position of this top important OK and after death like 4.0 and like point 500 yards can also like after death like 4.0 and like point 500 yards can also like after death like 4.0 and like point 500 yards can also like point 0.57 subject flight point 0.57 subject flight point 0.57 subject flight points mode of country also for acid founder B here under-19 which is the definition of here under-19 which is the definition of here under-19 which is the definition of decimal like they were eliminating the request character Weather plus or minus one considers this effect contestants definition re-tweet weakness thing is soviet then check re-tweet weakness thing is soviet then check re-tweet weakness thing is soviet then check weather my teacher school's black walnut and note stinginess 500 it means better did not a single on this occasion captain this present verses in my number lies in this Category Noida Up Check Weather Duro Scooty Laker Decimal and Teaser To First Time To Check Weather A Teacher In Teacher And Note Swapn Condition Of Ditties Like Kar Check Weather Station Option Character President And Notification Is Not A Plus And Minus Point To Apply This Category At Least One Digit Suri's Lower Middle East Digit Character President To Visit Temples To Determine Through Yes Episode Number Let's Talk With A Small Okay So This Is Maulik Ward Number 9 Nickel String And Not What Is My Condition Office Numbers Check Decimal Number And Teacher Is President and note extinct pra with reliving this category and this category details and this number get out so it's going to be like a sister first category and proven contented with my number having numbers stitched in it fast category and second category previous sirvi president vaz se lies in The Second Category No Entry Check There Must Co-exist Previous Condition Check There Must Co-exist Previous Condition Check There Must Co-exist Previous Condition Physicist Optional Condition Ho Which It Must Be Followed By Policy Under The Key Must Be Given In Teacher Vacancy Country Note Interior Present But He Also Not A Single String Report Daughter Poems Written For It Ability to single dot write this point like this category which must be the decimal roti when international seabed not reduce this character dot slot bank loans in teacher category famous check on distraction that Pandey said Mr. Siddheshwar like this type of dot co dot Panch Yagya Shri Siddhabali Single Daughter Digit After B.Sc Siddhabali Single Daughter Digit After B.Sc Siddhabali Single Daughter Digit After B.Sc B.Com Vitamin Flying in This World Can B.Com Vitamin Flying in This World Can B.Com Vitamin Flying in This World Can Easily See This Trick To 18 Electronic Cigarettes Are Directly In The Records For The Must Subscribe Like When Do Subscribe To The Channel But I Runtime Is Not Vote For Them A Night Stroll Improved And Finally Have Got Zero MS Per Second Richest Man In Black Fast Turn On One Hundred Percent Of Idly Servi Submissions And Just Talking About This So And Just Trying To Understand This Post Will Fix Thum into it's friday subscribe 158 more definition of work and definition of middle-class subscribe my channel subscribe this time to aya mastak par demerits like pravesh pocha war characters like plus two three qualities like 235 subscribe starting from this position 150 hundred mastering 22222 so Next Option Character Worst Position subscribe to the Page if you liked The Video then subscribe to The Amazing Subscribe to 0.5 Inch Width Meganet Most People This Nine Considered Se Two Option Characters Presented To Be Difficult To Spread This Will Be Deleted Patel And Considered Least One Digit But E Can Usually A Plus End And Late And Members Best Twenty20 Cricket Return Full End Final Year Check Return S DCP Ko Sentence Previous Sub Screen Brightness 108 System Character Like Please Subscribe Health Benefits Subscribe And This Limit Subscribe Starting From Way subscribe this Video not Be Like That at Least One Digit Don't Forget to Subscribe Pimpri Gifts Like This Day Small Function 108 Support and Consent to a Bill Return Gifts and Sweets Plus or Minus Subscribe Point Position of the Match David Richardson Key Typing Position Due To Its First Subscribe You Must Take Care For The Like This Point Tree Again This Point To 9 Taste subscribe this one UP The Amazing Subscribe Position Start You Must Take Care More Request At Least One Day Before The Start And After 10 Daughter and told not to make all characters should be like digit form like it should be like dedication jasmine explain support is also best in this ad blurry see its president over her item position to rate objects president explosion dot s its president of doctors 6 subscribe Decimal Number Vidmate Characters Of The Daughter subscribe Video then subscribe to the Page if you liked The Video then subscribe To My Recent Polls It's Not Possible To Bring The Decimal Number 102 After Doing Right Veerval Kauts Composition Of This Don't Like This Awal Check the scheduled at least Awal Check the scheduled at least Awal Check the scheduled at least one middle-aged person channel like this for one middle-aged person channel like this for one middle-aged person channel like this for electronics key but you must not according to the definition of station superintendent at least one day the considered na dhoe cheye donge nalue is number wale don't know the temple of quote approach to find out the Counter this only it may be present in this context Maulik Paun Inch Rui The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing David J Remedy must subscribe and not the position of the person Shravan id this video must subscribe Subscribe to ok dam application fee very simple because after death checking condition holds detained after the position of this back all the digits only character certificate got 2006 fixed deposit position of key decibel like dress while making number and end teachers a night after taking exception in This case is worth that one is written as a teacher and International day of this country don't create bullion result for the country should avoid you for watching this problem person this word shift benefits do not forget to mention in the comment section or video and will Not Wish To Live Video Share Video And Subscribe Our YouTube Channel Latest Updates Thank You For Watching This Video | 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 |
1,877 | hello folks in this video we will see how to solve the problem minimize maximum pair sum in array which is a medium level lead code problem so in this question we'll be given an input array containing n elements and we need to pair the elements such that we'll be having n by 2 paired elements so here in the constraint section it's given that n is even that means if we pair the elements we will have exactly n by 2 paired elements that is one thing and also in the constraint constraints it's given that the elements of the array cannot be negative right that is it can range from 1 to 10 raised to 5. so we have these two observations and the question is to minimize the maximum pair sum so we have what we have to do is we need to anyway form pairs from the given array and it should be paired in such a way that the sum of the elements of a pair should be minimized okay so first we need to do that like we need to uh generate pairs from the input array in such a way that when we uh when we consider a pair and add up the elements out of the two l two elements it should be minimized okay uh to the maximum extent we must minimize the sum right so that is one thing and uh that is one thing we have to do is we need to take care of making the sum minimum okay and after minimizing we need to find what can be which pair or which pair can generate the maximum sum out of the all the generated uh all the generated pairs we need to find out which one can generate the maximum sum when we add up the elements of the pair so what we can do is first we will sort the input array so once we sort the array we will have all the smaller element on the left side and all the great greater elements on the other side right so if we take one small element and one great greater element or the one larger element from the other side that becomes a pair and also it satisfies the condition that the sum will be minimized right when we add two larger numbers that will create a larger number compared to the sum of one small smaller number the smallest number and the largest number right so that way we can generate all the pairs okay once that is done what we can do is uh we can find out from them like uh once it is paired we can add up the elements and find out like whether this is the greatest some we can get right from all the pairs so that's the main idea so let's get started first we can have uh these sorted uh first we can have uh these sorted nums right input array so we can sort that nums dot sort now namsulu's nums will be sorted in ascending order so we have all the smaller elements on the left and all the larger elements on the right side and also uh now we need to now we have this num sorted now we what we can do is we can use two pointers right so we need to pair the elements right so we have to take one from the left most and one from the right most side so we can use two pointers to or pair of the l elements right so let i equal to 0 that is one at the left most end and let j equal to length of nums minus 1 so j is at the rightmost side now we can use a while loop to uh keep on pairing up the elements and uh the condition we can put is like while i less than j right if i equal to j or i great i is greater than j that is we will be moving i and j towards the center okay so till i is less than j we can pair up right and in the question it's given that n is even so uh we need not worry about that odd number of elements condition so that's not a problem here we will get exactly n by two pairs after pairing so we can use a while loop here while i less than j or we can generate a pair right so we can say pair equal to uh pair and we n we need to anyway we need to uh we don't want a pair here we want to calculate this we want to take the sum of the pair and see right whether it is great greater than uh it is the greatest pair we can get right so we need not store it we can i think we can calculate the result on the go okay so what we can do is uh anyway we can have a variable here max pair max square equal to zero so uh we can set it to zero initially because in the question it's given that input elements cannot be negative it starts from 1 to 10 to the power 5 right so let max pair equal to max square equal to 0 initially okay there are no negative elements so we can set it to 0 initially and uh here inside the while loop we can say max pair equal to max off we need to get the maximum of maximum pair right so either it will be max square or the currently calculated result that will be nums of i plus nums of j okay so max pair will uh will get updated accordingly if it finds a great greater sum it will get updated so during each loop we need to increment the point is right i will move towards right and j will move towards left so both pointers are moving towards center till uh we exhaust the or we till we find all the pairs right so j minus equal to 1. now after the loop uh the max pair variable will be having the minimized maximum pair sum right so we can return that return max pair so let's try running it's working see you in the next video you | Minimize Maximum Pair Sum in Array | find-followers-count | The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs.
* For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`.
Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that:
* Each element of `nums` is in **exactly one** pair, and
* The **maximum pair sum** is **minimized**.
Return _the minimized **maximum pair sum** after optimally pairing up the elements_.
**Example 1:**
**Input:** nums = \[3,5,2,3\]
**Output:** 7
**Explanation:** The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
**Example 2:**
**Input:** nums = \[3,5,4,2,4,6\]
**Output:** 8
**Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
**Constraints:**
* `n == nums.length`
* `2 <= n <= 105`
* `n` is **even**.
* `1 <= nums[i] <= 105` | null | Database | Easy | null |
72 | so hello everyone welcome to this new video and in this video i will be explaining the problem 72 edit distance which is a hard problem but to be honest it's not that hard i will explain you the concept how to solve this problem and you will realize that this problem is pretty easy to implement once the concept is clear so without any delay let's get into the problem so first i will be explaining through an example and then i will be coding it so what the problem says is that i have been given two words uh i hope you would have already read the problem so i won't spend much time here so you have been given two words you have to insert a character delete a character replace a character you can choose any of these operations and the result should be that the after doing these operations both the strings should become same so let's understand this problem through an example so let's suppose i have been given two strings uh let one be uh one second uh let one be b cat and one b matt so you know how we identify that it is a dp problem is that because here i have been given some operations that i can either replace i can insert or i can delete or i can do nothing let's let it be n nothing so these are my choices so i can do whatever i want so whenever you have been given a with a set of choices you can it is you should uh think in the way that this problem is asking me to implement dynamic programming so let's understand that suppose you see here that t is matching uh our decision will matter on the character so if i let's say that this strings length is n and this strings length is m so our uh decision will uh that whether we want to do any of these operations will depend on the characters that we are comparing so here we see that t are matching so it means that if they are already matching do i need to do anything replace insert or delete obviously no because i have to return in minimum operations so what i will do is that i will do nothing let it be w1 w2 so i will do nothing and i will shift my pointer towards this a on both sides so what it is becoming is that it is becoming n minus one and m minus one okay now i am at a here i see that these two are also matching so do i need to perform any operation the answer will be obviously no so i will again shift one step back on both of these now comes the interesting part here c and m they are not matching so i don't know what should i do i can either replace i can either insert or i can delete let's see what happens if i replace let's uh assume that we are replacing this string we are playing with this string so if i replace this m with c i replace m with c then what happens these two will become matching and i will shift my pointer one step back okay so uh what is what happened here is that i am shifting my pointer whichever index i am by minus 1 so n minus 1 and m minus 1 now let's assume okay let's assume that i am here or let me use the eraser to let me use so i met here again i can uh do another step thing i can insert a character so what will happen is that if i insert c here i will insert c at this position okay so now these two will match so what will happen next is that my this pointer will move to here and this pointer will remain here only so because i have inserted c here so like cat are matching this section is completely matching so in case of insertion the n minus one pointer this pointer has shifted by one n minus one and but this pointer will remain at the same spot uh also my another operation can be uh delete okay i hope you have understood the insertion part so now uh erase this uh okay so now my second operation i am again here these two are not matching so what i can do is that i can delete this entirely okay so if i delete this what is what will happen it will happen that my these i have matched these two okay whatever strings uh characters that are ahead but uh suppose here was x so as since i have deleted it this my this pointer won't move here because this string here it still has to find a match for c in this string so let's say here c was present so what will happen is that my this pointer the other the pointer in w2 will move one step back so that will become m minus one but here's it has still not found a match for it so it will be present here so these are my uh operations that i have to do it will be more clear once i start coding it another thing i want you to understand is that suppose you are given a string let's say race and another string is empty then how many operations do you need to do so the answer will be four operations because since this string is empty you will either have to like insert four characters here or you have to delete all characters here so whenever one of the string either of the string is empty then you have to return the number of characters size of the string that is present in the another string so now let's begin the coding part so let's assume that the string names are w1 and w2 oh sorry x and y so before so let's uh begin so what i will do is that i will write a function called solve so return what solve and uh solve x comma y comma x dot size comma y dot size so first i will be solving using recursion and then i will memoize it will be super easy to understand once you if when i will relate this to this example so after doing this i will write the function int solve string uh ampersand x string ampersand y comma let's say int n comma int m so after this what i will do first uh so any essence i am solving using a recursion any recursion has two parts first is the base condition and the second is the choices so let's write the base conditions first so what are the base conditions this is going to be my base condition that if either of the string is empty then i will the return the size of another string so if n which is the size of x string x if n is equal to 0 and is equal to 0 then i will return what m and if m is equal to 0 then i will return n so these are going to be my base conditions now coming to the choices so to make any choice i am comparing the characters so to compare the last character since i'm starting from end so to compare the last character let's say if x n minus 1 is equal to y m minus 1 then in that case i will do something what i will do nothing return solve x comma y n minus 1 comma m minus 1 as you have seen earlier uh when both the strings were matching i was moving step one step back so if this so this will be my answer in this case and now if these two are not matching what i will do is that since i will have to do one operation return one plus what minimum of the three choices delete or replace or insert so solve x comma y so first let's say if i am replacing then both of my strings will be moving one step back n minus 1 comma m minus 1 comma minimum of my insert and delete operations so as you can see in insert see in replace n minus 1 in insert n minus 1 and in delete m minus 1 so this will be basically copy pasting it so i hope you are understanding that how easy it is to implement the recursive part so solve i'll have to take care of the brackets now it's good so i will just subtract one so like these have handled all the cases so it should run but it will give me time complexity error let's see check for any compilation error so this is well and good but this will give time uh what tle because it will take too much time uh since i am because i am making a lot of choices i am not mapping my choices so like for every uh non-matching i am like for every uh non-matching i am like for every uh non-matching i am making three choices so for total uh length it will be approximate it will be expansion exponential 3 raised to power n so to solve this problem i will make a dp vector so vector it will be only of two lines of code okay vector of vector it dp and now i will initialize my dp so dp dot resize what x dot size comma plus 1 vector int y dot size plus one comma minus one so i have initialized my a vector with uh minus one so it will contain all my choices at specific when the size of the strings are n and m so i will just before returning i will just store my choices uh store my result in my vector so that if i arrive at the same case any other time i will already have it calculated so dpnm is equal to this and dpa nm is equal to this so if there is a pro sub problem that i have already solved i will just do one thing that if dp ah let's copy it dpnm is not equal to minus one that is i have already solved that sub problem then i will return dp nm so yeah this way i will avoid going into recursive calls again and again for the problems that i have solved so you know how easy it was i just developed a recursive approach then i inserted one if condition on my array and the problem is solved so i hope it is clear to you so please like the video and subscribe the channel if you understood it so thank you and have a nice day bye | Edit Distance | edit-distance | Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**Output:** 3
**Explanation:**
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
**Example 2:**
**Input:** word1 = "intention ", word2 = "execution "
**Output:** 5
**Explanation:**
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
**Constraints:**
* `0 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of lowercase English letters. | null | String,Dynamic Programming | Hard | 161,583,712,1105,2311 |
423 | hi guys welcome to algorithms made easy in this video we'll see the question reconstruct original digits from english given a non-empty string non-empty string non-empty string containing an out of order english representation of digits 0 to 9 output the digits in ascending order so the note attached with this question says that the input will contain only lowercase english letters and input is guaranteed to be a valid input and can be transformed to its original digits that means invalid input such as abc is not permitted input length is less than 50 000 so for example 1 the input letters are scrambled letters for 0 1 2 and for the second example these are the scrambled letters for 4 5 so let's see how we can solve this particular question so here i have taken the string representation for all the numbers that we have from 0 to 9 and if you notice there are some unique cases in these numbers z occurs only in 0 w occurs only in 2 u occurs only in 4 x only in 6 and g occurs only in 8. so by using this particular property we can simply say that these numbers are present in the given string if they occur in the string apart from that if we want to find the other numbers we'll have to derive it by using the counts of the 0 2 4 6 8 and other digits that we have so let's take this aside and now find the uniqueness in all the remaining numbers so over here you can see that o occurs only in one if you keep aside these h occurs in three f and five s in seven and nine still has no uniqueness so we can say that one occurs the number of times i have o in my string minus the number of zeros twos and fours that i have already found out so that is given by this formula similarly for 3 the count of h that i have for my string minus the number of times i have found 8 similarly for 5 and for 7. for 9 you can consider any of the characters now you can consider i or e as that is unique in this particular string as well so my nine would be the number of times i have found i minus the number of times i have seen these digits that is five six and eight so taking into account everything that we are doing we will take a count array that would store the count of each character that we have in the input string and then we'll find the count of numbers for the unique characters that i have that is for these numbers in a different array that is my digits array that i will be having and then with the help of these i'll find the rest of the derivative counts that i have for 1 3 5 7 and 9. so this was the approach that we would be using to solve this particular problem so let's go ahead and code this problem so the first and the foremost thing is to find the count of all the characters so let's take a count array and write a loop to do this the next thing is taking my digits array and in this i'll be storing the count of all the numbers that i have in the string so let's start with the unique cases so my num of 0 would be count of z i have and similarly for the other ones so these were the unique cases now let's find the derived cases so now we have all the counts with us we just need to loop over them and prepare the result string so let's take a string builder and we loop over this digits array or the number that we have so here i am appending the number of times it is occurring in my num array and finally we just need to return it and that's it so let's run this code for all the sample test cases and we are getting a correct result let's submit it and it got submitted so the time complexity is o of n for this particular loop that is the length of the string that we have and the space complexity is o of 1 because we just have used these two arrays which are constant space that is 26 plus 10 so that's it for this question guys i hope you liked the video and i'll see you in another one so till then keep learning keep coding bye you | Reconstruct Original Digits from English | reconstruct-original-digits-from-english | Given a string `s` containing an out-of-order English representation of digits `0-9`, return _the digits in **ascending** order_.
**Example 1:**
**Input:** s = "owoztneoer"
**Output:** "012"
**Example 2:**
**Input:** s = "fviefuro"
**Output:** "45"
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is one of the characters `[ "e ", "g ", "f ", "i ", "h ", "o ", "n ", "s ", "r ", "u ", "t ", "w ", "v ", "x ", "z "]`.
* `s` is **guaranteed** to be valid. | null | Hash Table,Math,String | Medium | null |
1,921 | hello hi guys good morning welcome back to the new video so this video we're going to see the problem eliminate maximum number of monsters so as you can see it has been asked by gole not much frequently and last in one two years let's quickly see the problem statement itself what it says so it says that uh we are playing a video game and in that video game we are def like we are defending our city uh from a group of n monsters so basically n monsters are coming towards the city now we are giving a zero index integer are called as distance of size n where distance of I is the initial distance in kilometer of the I point monster you can just imagine from me which means from my city a monster is T distance apart right the monsters walk towards the city at a constant speed so I'm also mentioned okay I have for every monster let's say for I monster let's say it is my city for the I monster I know what is the distance and I also know that at which constant speed again it's a constant speed so there's no acceleration so he's coming with a constant speed right and I know that what's a constant speed with which it is coming so I know the S of I and I know the D of I also is the speed of the I monster in kilm per minute now uh I have a weapon that one fully charg can eliminate a single Monster however the weapon takes one minute to charge the weapon is fully charged at the very start so I can just imagine that at the very start which means at the zeroth second or the zeroth minute I have my fully charge weapon I'll just shoot it as soon as I shoot it I will take 1 minute to actually fully charge it again so I wait for 1 minute then at 1 minute I can shoot it back again then I'll wait again then at minute two I'll shoot it back again then I'll wait then at minute three I shoot it back again so this is how the actual my weapon will work cool uh it is just now saying that you lose when a monster reaches your city if a monster reaches the city at the exact moment the weapon is fully charged it counts as a loss which means I'm shooting my monster at this H second my uh monster is not yet reached me but as soon as I shoot and like what if the monster has reached just like beside me which means it has reached at my place now the shooting point is no logic like he can just kill me right away so uh it just says that monster reaches the city at the exact moment when the weapon is fully charged still I'm dead and the game ends before you can cause uh before you can use your weapon cool now we have to return the maximum number of moners that you can eliminate before you lose or maybe you can eliminate all the monsters that's also very good or n if you can eliminate all the monsters before you reach the city which means maximum of monsters which you can eliminate before they reach the city now as you can see that I know that I will start shooting right and for my shooting thing can start from zero it can start to like it can start off from zero and at every minute I will have a shooting ability so I can shoot at 0 3 0 1 2 3 4 5 and so on so minute now every monster he has a speed he has a distance so for sure I can know as I know speed is equals to distance Upon Time right by this concept I can easily get to know that what is the time it is distance upon speed so I can know in what time that monster can reach me right cool so what I will do the same thing so uh I know that for every of these monsters I can calculate their corresponding time and how much time these monsters can reach me so the time actually will be distance upon speed right so I know the distance is one speed is one so 1 upon 1 is actually a 1 3 upon 1 is actually a 1 4 upon one is actually a 1 so my time actually will be 1 3 and 4 now Aran um like okay it is just now you want to kill some monster right you know that your capability of killing let's say killing capability starts at zero then 1 then two then three at Time Zero you have a kill you will have a killing capability at time one you will have a killing capability at time two you will have a killing capability so one thing is for sure that at Time Zero you will just kill the first Monster Which is closest to you for sure because like if I will like if at Time Zero I'll just casually kill the fourth like the monster which is coming at the fourth minute what's the point of that like I can also get it later on but who's close to me just killing like kill him first as you have like played the game itself you will just kill the first Monster Who's as close to you right so at the Z second I'll kill this monster and for sure I can kill right because at the zeroth minute I will have a capability and he is 1 minute for like 1 minute so for sure like he and I like my zero is less than one so for sure I can for sure kill him he has not reached me yet so that's amazing uh so I can just kill this first Monster great um as you can see next this is gone right this is gone this monster is killed next Monster coming in is at 3 so for sure I can um like which means that to reach my city this monster will take 3 minutes and I will have the charging capability at 1 minute itself so for sure at 1 minute I will just kill this monster because he has not reached me and he will reach me in 3 minutes which is more so I'll just kill him also okay this is my this cavity is also gone now at 2 minutes I'll just kill the fourth like with the one which is reaching in the four minutes to me so as is less than four so I just kill him so as you can see I will be able to kill all the monsters and that's the answer if you go to the next question you will see that again uh we can go and find now you might ask okay Arian um like this was very simple example uh but let's take a bit example like let's say if I ask you if the distance would have been here let's say one or let's say if the distance would have been here one so you would have asked me okay the time here would have also been one so the time here would have been one now you killed the monster who would come in 1 minute at the zeroth minute so that was okay because Z is less than one so you have the capability to kill at zero and he's coming at 1 so for sure he's coming late so you can kill him early but now you got the capability at 1 he can also come at one so before you actually able to shoot he will be standing beside you at one you got the capability at one he also has reached you sorry you are dead so as you saw that as your minutes and you can easily see that your minutes are just increasing order which mean 012 so you can just also Imagine these are indexes of this particular array I can just iterate and check okay my index actually should be lesser than my index should actually be lesser than the this particular time itself if this is the case I'm good if this becomes more than or even equal to I am done it's done I'm gone like monster will kill me for sure right away now the one thing in this is uh what if I ask you if there is a case that a monster is at a distance of uh three and the speed of that monster is to so for sure you would know that the monster will arrive me at the time 1.5 right again there's a monster at the 1.5 right again there's a monster at the 1.5 right again there's a monster at the distance two and having a speed two now the time the monster will arrive me will be actually a one right so I know one thing for sure at time one which means if I'm saying I have capability at time zero this capability this killing capability I have at Time Zero killing capability at Time Zero I can kill both of them it's true because it is 1.5 it is one I can kill both of them is 1.5 it is one I can kill both of them is 1.5 it is one I can kill both of them killing capability if I say okay uh if I want to kill at time one I can kill this I cannot kill this because at time one he would be reaching just beside me but he would be reaching at 1.5 time so it he would be reaching at 1.5 time so it he would be reaching at 1.5 time so it is easy so you will see that here we did a simple division this won't help us if either you can figure out a hack for it that how we will handle this case this kind of case or we will just have to make sure that okay we should we have to just mention okay if it's a value which has a remainder so please add a one to it which means if it's actually a remainder so please uh add a one to it and then compare it so that is one way which you can go about it so you will see just one thing that if the monster is at 1.5 so you can just have it as is at 1.5 so you can just have it as is at 1.5 so you can just have it as parity the just imagine that it will come at time two this will for sure come at time one so rather than comparing the floor value as we doing here what we will do we com like we will actually convert this value to a seal value so earlier we were doing a distance upon speed so now we'll make sure that we will do a distance upon speed seal value of distance upon speed or you can also the same stuff as D + S - 1 by S now if this same stuff as D + S - 1 by S now if this same stuff as D + S - 1 by S now if this is the case your time actually will become a two then you can actually compare this condition that your I should be greater than like if your I is actually becoming greater than equal to your time you have to stop your city is killed now you have to stop and that's the only change which you have to make sure that you are doing so as to accommodate that you don't do a flow Division and because of that flow division you might actually think that this monster which is coming at 1.5 this monster which is coming at 1.5 this monster which is coming at 1.5 minutes would also kill you at 1 minute but it's not the case it will kill you in 1.5 minutes and you still have and in 1.5 minutes and you still have and in 1.5 minutes and you still have and you can still shoot him at 1 minute Mark cool and that's the only thing that you have to do just simply get the times and for that time itself just compare at any point of time if my I becomes more than equal to my time then I have to just simply break it which means I can just say that I have killed I monsters so far and that is my answer if I have reached my end I can simply return the end which is the size of my entire monsters array cool let's quickly go and jump and write the code for it's going to be pretty simple uh we know that how many monsters we have killed uh we can simply like return the index but we also need to know that how many number of monsters were actually there in my entire Ed so I can just simply get the distance or speed both are of same size and for sure if you don't know the uh complexity for this is simply what time complexity is actually nothing but o of n log n as you know that we are simply doing a sorting again the space is actually over of and again uh because for sure you using a time aray but still if you can just in place modify distance aray with the new time that also can work for you but it's just a recom like it's just a recommendation that you don't change the input as such but still that can be changed to O of one if you actually go and modify your distance input itself else the time is O and log because of sorting why sorting because you know that you have to sort this times AR because the closest monster which is coming fast you will kill that monster first cool um now let's quickly go on and in this I'll just simply go and uh write out just going on to all my monsters and I know that for all these monsters um I can just calculate the time first so I can just take a uh Vector of int uh time as an array now I can just do a time dot push back and what I need to push back my as I told you a seal value which actually uh distance which is distance upon speed but distance upon speed uh we want to push in a seal value which actually distance as I show you distance plus speed uh minus one upon speed it is just representing or you can also do a seal of distance upon speed that also will work exactly same now when that is done simply do one thing that simply sort the time array which you whatsoever you had now with this sorting of time AR now you will have your entire AR of time sorted now simply iterate on all of your time array again now my indexing will actually help my I indexes will actually help me to know at I at time I have the capability to shoot the monster so if I is greater than equal to my time of I now sorry bro um you cannot kill this monster and your city will be killed but you would have killed IE monsters up till so far else if you have killed all the monsters and no monster you could kill so just simply uh you can just return it in and you would be able to actually kill all the monsters cool and that will be off in Lan cool thank you so much for watching see you then goodbye take care bye-bye | Eliminate Maximum Number of Monsters | eliminate-maximum-number-of-monsters | You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute.
You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start.
You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon.
Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._
**Example 1:**
**Input:** dist = \[1,3,4\], speed = \[1,1,1\]
**Output:** 3
**Explanation:**
In the beginning, the distances of the monsters are \[1,3,4\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,2,3\]. You eliminate the second monster.
After a minute, the distances of the monsters are \[X,X,2\]. You eliminate the thrid monster.
All 3 monsters can be eliminated.
**Example 2:**
**Input:** dist = \[1,1,2,3\], speed = \[1,1,1,1\]
**Output:** 1
**Explanation:**
In the beginning, the distances of the monsters are \[1,1,2,3\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,0,1,2\], so you lose.
You can only eliminate 1 monster.
**Example 3:**
**Input:** dist = \[3,2,4\], speed = \[5,3,2\]
**Output:** 1
**Explanation:**
In the beginning, the distances of the monsters are \[3,2,4\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,0,2\], so you lose.
You can only eliminate 1 monster.
**Constraints:**
* `n == dist.length == speed.length`
* `1 <= n <= 105`
* `1 <= dist[i], speed[i] <= 105` | null | null | Medium | null |
783 | hey guys this is chaser how's everything going in this video I'm going to take a look at 783 minimum distance between PST notes we're given a binary search tree with a root which is the minimum difference between the values of any two different notes industry four two six one three in one walk like the tree like this the minimum difference of course might be 1 2 and 2/3 or 3/4 right all of them 2 and 2/3 or 3/4 right all of them 2 and 2/3 or 3/4 right all of them generates the difference with one so we assure the return of one the BSA will be will not be new okay so for this tree problem let's just look in at the details of the simplest form which is 2 F 3 notes 4 to 6 like this is a left node is B the right note is C so because of BST we know that Abby's what a nice or Nancy right so if you need to choose two numbers from this three notes tree we need to choose 2 4 and a 4 6 there's the distance between 2 and 6 must be bigger than 2 4 or 4 6 right so the mean minimum must be B n a 4 a and C right so if you take a root note suppose there is the optimal result will be this root node with something else it must be what it must be say if root node is in the optimal result then it must be what the numbers to left are smaller than a right so it must be biggest of the left so it means Oh biggest left versus root and what root the right numbers well all of them are bigger than it so it might be space moderate smaller smallest left right so for each node we actually need to get the maximum of left and the smallest of minimum of right and to get the possible result so that's give us the recursion solution we'd create a recursion solution which we when we walk on a node we will get the minimum of left get the maximum right and the return the mean the minimum and Max of itself right cool that's wet so we get first we get we call the walk itself recursively after the left node so the main left max left would be walk note the note left might be new or so we handle no he nor here my keyboard has some problem man anyway I got a tanto ready Oh cannot tolerate this okay anyway sorry if it is normal then its minimum cannot be used right there's no minimum or maximum so we just return some invited values for the minimum let's say it's just infinity we get they we're getting the absolute value so it doesn't matter but for consistency I think for the main we choose maximum positive for the maximum which is negative right this be better okay now again you would get the mean right and the maximal right cool as we analyzed here we could update the result infinity the result should be mean self and these two intervals are these two difference right absolute value which means max left note bow yeah and math.abs right cool bow yeah and math.abs right cool bow yeah and math.abs right cool now we actually we've already updated result we need to return the maximum and return the Mean Max including this node right we return the minimum should be of course should be mean left right and the maximum right should be the maximum so this is it and return result so that's it I'm sorry ah we forgot to walk man we step on the roots walk no result will be up did it with a maximun left and mean right uh-huh a maximun left and mean right uh-huh a maximun left and mean right uh-huh get the minimum and if we return the minimum we should be enema left and a maximum right yeah and then we will step on their route we return the result I'm curious so where's the problem okay we walk on the node we will walk on the left and walk on the right so it's infinity the minimum it's infinity ah yeah I'm sorry infinity we he set it to the leaf node right so it might be infinity and actually we need to update it with being updated with the current node cool yeah I think we're doing great yeah so this is the recursion solution ty everybody's Travis for once in your time space there will be a call stack it's the height of the tree yeah this is the first solution with recursion and could we do something else I didn't come up with this idea but it's came up with some someone else I think it's very clever so the distance so the binary search tree is left node will be smaller than the middle will be smaller than a right if we do traverse the tree with inorder traversal we will create ascending array right let's see if in order traversal so the first case is in example we will get one two three four six and so the minimum distance were building bit between these two adjacent numbers right so yeah that we can easily get that okay so I'll create a walk method and when we are we need to do in order traversal and okay so how we do another trap so with your bird kerschen easy if node has left we walk on the node left right and then we process meat if node right walk you're right so this is the and we're done so this is the you know the traversal let's see if we if works know that you see we get one two three four six just as we won and when we're calculating a two adjacent nodes we need to keep track of the previous while right so that tree equals infinity and when we are processing a node we work updates the result subtractive with three if with no that vow right and don't forget updates of prefab you which is snow devour itself qu and I think that's done yeah so this is also work for time every node will be Travis for only ones so I mean your time space wow it's still we use a recursion so there will be a call stack so it would still be the height of the tree okay so that's all for this one personally I like this approach it's easy to understand we simplify the tree problem into tree with three nodes and detect the solution and just reuse a recursion to return the result a return they'd be intermediated data we want right okay this kind of two different approaches and Travis all you know Travis all seems like a trick anyway that's all for this problem will be ups you next time bye-bye | Minimum Distance Between BST Nodes | search-in-a-binary-search-tree | Given the `root` of a Binary Search Tree (BST), return _the minimum difference between the values of any two different nodes in the tree_.
**Example 1:**
**Input:** root = \[4,2,6,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,0,48,null,null,12,49\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `0 <= Node.val <= 105`
**Note:** This question is the same as 530: [https://leetcode.com/problems/minimum-absolute-difference-in-bst/](https://leetcode.com/problems/minimum-absolute-difference-in-bst/) | null | Tree,Binary Search Tree,Binary Tree | Easy | 270,784 |
1,044 | so everyone welcome back to another video of no mental forest today let's continue our little challenge today's question is : August articulate the question is : August articulate the question is : August articulate the Sabbath dream let's look at a question given a string is consider or duplicate a sub stream substitute of s that occurred two or more turns Terral currencies may overwrapped written any duplicate a substituent data has the longest impossible means if s does not have a tubular Sabbath stream the answer is impetus stream look at the first example code of banana what is na because the NA and in a duplicated look at a second example a be sitting there Unicode character so the without his impeded stream he tell the names is from 2 to 10 times 5 PI over 5 and s a considered a law case in English later from only search for 26 character forestry research they have a three popular algorithm - quota or ha coral seek algorithm an - quota or ha coral seek algorithm an - quota or ha coral seek algorithm an animal called KMP algorithm this reaction is suitable for single pattern research but an in our case they didn't give you fixed our pattern we going to fund a notice the duplicated string that actually going to do multi-pattern actually going to do multi-pattern actually going to do multi-pattern research so it attempted occasioning here so what is the Robin Kappa algorithm yeah you could have looking here funded a theory basically arm it actually just a convert a character to digital number and then you compare this number he's you look at that for API unistream you find out then you go into character find another fall game with the means that they are duplicated net snooker yesterday and banana as the example engineer we going I try my best to it was proper could we can you understand it a for the action it is not a simple question so if I have a he in a banana the hash wrapper you actually could be different I so for example I'm just I was still a equal to one the equal to 2 and C equal to 3 I will change this to the equal to 4 and the song in actually is 14 so we're going to use the panel search of first rock artists who have reductions and 3 so if we could have found a three character critter and people already duplicated refunded to it on search for two so we cut this half it is a sweet ordinance is 3 because intro father sweet duplicating he exists or not yeah we going to use the slide window we start at the left so action it is this one p in so we go into hash PA and what is the hash value for this one the PE is to the a is 1 the aim it is 14 so this it is 17 the hash value for this one then we move the hat window to here with job at a tepee and Iowa so the hash value attaches a and pay so in here is actually the one plus 14 and plus 1 so it is 16 and we have a half under duplicated over the year then we continue we go into job at the air again and move to this a and so now we find the - a and the - a and the - a and action it is 14 plus 1 temperance 14 Clinton DeHaven Tina and then we study continue another one we dropped in and either one with a guy injury it is dismal so the hash value going to fund is a and a equal to one plus 14 10 plus 5 it is 16 did I see before years are DC before so actually listens to answer and this is because we just cut on one half on the fund that you could be potential cutter it is a 4 to the ha Thunder that then you came into cutter okay if this is you if you cut a disadvantage then you are even you found that this is so fun that you actually either one more if you could have found the or not if they can't find it at doing just you move at that point that is what we are going to do so just let the right at a court so we're going to have a 10 insulin hunting for the string Denise are you going to and him and the first day they are going to convert this string to aware of integer so we could implement a Christian can slice through you have a hinge numbers so the name is days Jeanine stay in touch over dance nights three lessons then we have at a for loop we operate at a value to this character body we go into and changes we streamed out Haruka itit is I the man is this one because the take a look at I have in the Javits I have at each turn and Aruba's entered soon added havoc too high now come with the hinge in tomorrow's utilities you know me can choose and to search and we neither have the best value for this one and this the best values to five six the motor value is 1 0 1 we go into you today in see here he could be a peak is the numbers are we going to use the biggest bottom number so let's telephone you the best value are only used to 26 because he said only consider log has the English later only have a 26 character and butter then motor value villagers on user NOLA and now they're going to panel research leftist utter Wow with this video two characters were left in Ottawa but it is the day last y2 equal to in the master character noon day and the tendons go into the air I didn't get heated so when you do the panel research the air via Demeter so you're going to head a while loop to left another you go to the right then you're going to search so that you in action and in equal to ten left plus for this the panel research it is a pattern we need a remember if you see the Sun I don't see any reason you couldn't remember it so if you find it we call you to have a helper function we'll call it another search if you search you find out how you search you go into are looking for nice air and have the best value a and have the motor value and the hardness of this dream is a m-- and the hardness of this dream is a m-- and the hardness of this dream is a m-- and the numbers in the representative character if you found it if it is know that you called to let you move on it means you found it then left or equal to air philosopher you go in to add one more character see if that is also if you cut it too small means then yeah else either cut repeat then the right move to the air is a helper function we're going to Britain we have been looking for the lines and we have the best value a we have the known value is our model and we also have add a number with a character attendance and we have a aware of this when numbers will be put into the character weekly here we're going to finish by the people of initiative first leave you after you finish you have a day oh you already know the names is this one but you actually don't have they started a value when they started value action you could use this search help of function going to lift a man as one and in the best value and that is motor value and where this could define another static attend only the person never mind just putting in here anything it is the Nance and if you find that I started then to the return start going to equal to negative so your action is stop to restart take the South Street Bank if you didn't find anything in 30 now we just rewrite at is the search this is such a key the choice at the end open type of algorithm so what are we going to do and just we have a time no longer will compute the hash of this gym value so if the hash value 30 40 is the zero now we're going to compute it equal to the hash value times the best value and the you class this value number I and the yumoto the mortal and if we also because a to and searching in this array and noms I so they already we going to have a half - so the mega show we don't look half - so the mega show we don't look half - so the mega show we don't look at the search hash said long before the oldest thing so having the new hash patty for now we're going to convert a value to use the orphan so we're going to write it with the moon a little one and anger for me and if you also going to search we're going to learn in the Hashi cable down in the hush okay we need a dance here and if we need important note by the way walking no we're going to you possibly check it was contained this content is before let me just agree to give didn't then the Trece added before we loop him finish it didn't we - the we loop him finish it didn't we - the we loop him finish it didn't we - the winds didn't find then return negative one okay let's find a coda see if I have a single solution okay we have this stuff we started with the moon because when the that was weak to character and then we use this data is cheerio to little say but the mood next and achieved with a H times the best value - when start a minus one so I best value - when start a minus one so I best value - when start a minus one so I give the value history reality study means sorry but even otherwise they a yeah because you don't know home these are also the needs the second is you going to fund it so you go into this area then you going to modern motor it after the motor your action also going to add a dividing time you're going to water it and you're going to that the previous removes the other yeah we turn okay we to action this is them so you start not a equal to one so you found it means new conduct so they substring they start has left yes the dam the fund in a needs a permeated it accepted just literally captured this action quite a difficult question what are the action did a reaction adjusted today panel researched and names over notice that you predict a the subsidy and we called the help of function search and the search action networking has a slight window over nice air not a harsh the stream in this window we call that a sin stream in the hash and I try to find it if you look at the stream here we give it a bigger motor for loaning hash and either should be love for this problem actually there could be a hash Knesset one solution to have a two different motor for hash where we use hash map it'll authorities in unison string and non that lookup must is finish in methanol cavity can complicity actually for panel researching here for panel research that hand complicity is all log M but for their learning harsh UV actually is on the oval role so together with the time complicit is all eggnog in the basic complicity is all on the own article to each one only heroin hope even this help of action disquiet a difficult question and I'll show you only understand the positive the morality action is used this to achieve it if you did understand I just go here have a look up at a description and also such a sample splendid very well about this algorithm thank you for watching hope you found this helpful bye | Longest Duplicate Substring | find-common-characters | Given a string `s`, consider all _duplicated substrings_: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
Return **any** duplicated substring that has the longest possible length. If `s` does not have a duplicated substring, the answer is `" "`.
**Example 1:**
**Input:** s = "banana"
**Output:** "ana"
**Example 2:**
**Input:** s = "abcd"
**Output:** ""
**Constraints:**
* `2 <= s.length <= 3 * 104`
* `s` consists of lowercase English letters. | null | Array,Hash Table,String | Easy | 350 |
1,465 | welcome to june's leeco challenge today's problem is maximum area of a piece of cake after horizontal and vertical cuts given a rectangle cake with height h and width w and two array of integers horizontal cuts and vertical cuts where horizontal cuts is the distance from the top of the rectangle cake to the horizontal cut so these lines here and vertical cuts which is the distance from the left to right now return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontal cuts and vertical cuts now since the answer can be a huge number return this modulo 10 to the ninth power plus seven so here we can see if we cut the cake at one and three and one two four vertically our max area is going to be this cake or this piece of cake here which is going to be area four now notice that the cuts are not sorted in order and it is guaranteed that all the elements are going to be distinct now they kind of give you the answer straight out in the hints here but let's just ignore these for now say that we wanted to figure out the max width say this was a 1d array a one-dimensional array and we want to one-dimensional array and we want to one-dimensional array and we want to find the max width from this array how would we do that well if we had like cuts from one to three what we would do is basically just sort all these cuts and then uh figure out what the gap is from the ends as well so we'd have to append zero as well as the um the width of the ray whatever this is n and we just would find the maximum distance between um you know corresponding index points here we just find 1 minus i minus 0 or i minus 1 and so on and so forth so here we can see the max width is going to be well depending on what the n is here looks like it's going to be 2. okay so if we did that if we can that's pretty easy we can just sort it and then figure out the gaps how would we find the max area well notice that this is a rectangle right that means that each one of these lines always cuts the vertical line as well so all that would mean is we just need to find the max width and then find the max height and since we know that these cross-cut each other we know that these cross-cut each other we know that these cross-cut each other we could just figure out what the max area is because obviously the max area is going to be the max width and the max height right and there's nothing there's really not much else to that okay so let's do that let's first sort our arrays here and we want to append the uh ends as well so what we'll do is just take this horizontal cut and we'll uh append a zero in the beginning and we'll append the uh let's see horizontal cuts so this would be the height like that we'll do the same thing with vertical cuts get zero plus vertical cuts but this one is will be the width um am i doing this right here let's see horizontal cuts it's going to be the height yup and vertical cuts will be the width okay so now that we have that all we need to do is find the max width and max height so let's first initialize max height and max width at zero now we'll say for i in range of 1 to the length of horizontal cuts wherever this is right now we're going to find the max height so this would just be the max of max height and the absolute difference between horizontal cuts i minus one subtracted by horizontal cuts i next we'll do the same thing for vertical cuts but this will get the max width this will be vertical cuts finally just return the product of these two but remember these this can be huge oops so we are going to do a modulo 10 to the ninth power plus seven so modulo 10 to the ninth power plus seven all right let's make sure this works looks like it does submit it and there we go accepted so time complexity is going to be n log n plus m log m uh and we use constant space because well i mean i don't know if this counts as extra space technically does but considering that's just two extra values here i think we can kind of we can ignore that so this would be constant space okay thanks for watching my channel remember do not trust me i know nothing | Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts | maximum-product-of-splitted-binary-tree | You are given a rectangular cake of size `h x w` and two arrays of integers `horizontalCuts` and `verticalCuts` where:
* `horizontalCuts[i]` is the distance from the top of the rectangular cake to the `ith` horizontal cut and similarly, and
* `verticalCuts[j]` is the distance from the left of the rectangular cake to the `jth` vertical cut.
Return _the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays_ `horizontalCuts` _and_ `verticalCuts`. Since the answer can be a large number, return this **modulo** `109 + 7`.
**Example 1:**
**Input:** h = 5, w = 4, horizontalCuts = \[1,2,4\], verticalCuts = \[1,3\]
**Output:** 4
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
**Example 2:**
**Input:** h = 5, w = 4, horizontalCuts = \[3,1\], verticalCuts = \[1\]
**Output:** 6
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
**Example 3:**
**Input:** h = 5, w = 4, horizontalCuts = \[3\], verticalCuts = \[3\]
**Output:** 9
**Constraints:**
* `2 <= h, w <= 109`
* `1 <= horizontalCuts.length <= min(h - 1, 105)`
* `1 <= verticalCuts.length <= min(w - 1, 105)`
* `1 <= horizontalCuts[i] < h`
* `1 <= verticalCuts[i] < w`
* All the elements in `horizontalCuts` are distinct.
* All the elements in `verticalCuts` are distinct. | If we know the sum of a subtree, the answer is max( (total_sum - subtree_sum) * subtree_sum) in each node. | Tree,Depth-First Search,Binary Tree | Medium | 2175 |
53 | what's up interview hackers sam here from bite by bite comment in this video I'm going to show you how to solve the maxims subarray problem and if you haven't already make sure you hit that subscribe button in the notification bell to get notified every time we release new videos just like this alright in this video we're gonna look at the maximum sub-array problem and so at the maximum sub-array problem and so at the maximum sub-array problem and so in this problem we have an array and we want to find the contiguous sub array within that array that has the greatest Sun and specifically we actually want to figure out what is the sum of the greatest contiguous sub array and so I'm not going to go through all of the details of the exercises that we're in module 2 I would encourage you to look in the workbook because we have written explanations for a lot of the specific stuff but I just want to cover the problem as a whole to make sure that you understand what's going on here and so with this problem we're given an array of numbers and we're looking for that contiguous sub array in this case we can see that our you know you can you could test this for yourself but this is going to give us a sum of 6 this sub array here and so that's gonna be the greatest sub array in our entire list and so let's start here with defining what our function is going to look like and so in this case it is important for us to make sure that we're properly defining the function because it would be really easy to think okay we actually want to return this sub array but that's not the case and that's not what the question is asking the question is actually just asking us to return this number here and so what we're gonna do is we're gonna write a function so we're gonna you know something like you know max sub array and all its gonna do is it's gonna take in and enter a and it's gonna return an integer right and so that's all we have to do here for our function definition and now let's look at like what would be a brute force solution to solve this problem so hopefully you're starting to get comfortable with the idea that most of the time our brute force solution is going to be to find every possible solution right and then we can just consider of all the different possibilities which of those possibilities actually gives us the best result and so in this case it's pretty easy for us to do that because all we have to do is we're not even looking at all the combinations we're just looking at the different subarrays and so we can just use a nested for loop we don't have to do any recursion or anything complicated we're just gonna say you know for I equals 0 and I is less than the length of the array and I have plus I plus and now all we have to do is say you know for J equals 0 and J is less than I J plus and for each of these all we're gonna do is you know max sum equals the maximum of the max and the sum of the array from J to I right because J is gonna be less than high and so in this case all we're doing is we're just saying you know let me consider all the different possible sub arrays I'm gonna sum up each sub array and for each sub array when I sum it up I'm gonna compare that to our current Max and so that would look like you know I'd start with okay I or J and I something like this I'd say you know my max is equal to negative one then I'd increment I and so I would get that my max is now going to be still negative one and then I would increment J and we would go on like this in depth and we would go through the whole array right so that's how we would do this as a brute force solution and of course we want to ask ourselves what is going to be the time complexity and the space complexity of doing this and so in terms of the complexity because we have this nested for loop and even though we have this J I find that I always found this really confusing when J is less than I rather than J also going to the length of the array because it seems like you know is it actually going to be O of N squared but the answer is that it is when we have this nested for loop we're gonna have a time complexity of N squared and it's really actually you know I'll I believe that there is a bit there's a video in the bonus section of the course on Big O notation and stuff and we cover a bit more like why this actually is that way so if you're not sure you understand the logic behind it go check out that video but we're gonna get a time complexity of all of N and then we're not really using any extra space here and so our time is o of N squared and our space is of 1 because we're not using any extra space but now the question is can we do this in a way that is going to use less time and you know from a logical standpoint it doesn't seem like there's any reason why we wouldn't be able to do that right in terms of our best conceivable runtime the only thing that we have to do here is that we have to iterate over the entire array and so as long as we're iterating over the entire array we know in theory we could figure out the answer and it's pretty clear as well that we're doing a lot of extra work here so like let's think about how we could start to optimize this well the most obvious thing that we're doing that's a lot of extra work is that we're computing this sum again and what that means is that we're summing up pieces of the stray pieces of the array multiple times because let's say that first I look at this sub array here and then I look at this sub array here now I'm actually summing up this piece two times I'm doing it both times when I compute it and so obviously that's taking us extra effort and so we don't need to theoretically is there a way that we could do this without summing the whole thing multiple times and so when we look at this you know I'm basically looking at that and then the other thing that I'm noticing is let's think about like are there any restrictions on like what our possible result could be and so I think that we can all agree that one restriction on our result is that the first element and the last element of our maximum some array are never going to be negative right and I want to clarify that for a second like let's look at this here and let me erase some of this so just I'll rewrite this in a second but just while I'm erasing this I want you to think about it like what would it mean if the one of the numbers at the beginning or the end was negative so it's negative 3 4 negative 1 etc and so I want you to think about like what would it mean if for example the first element was 2 or negative 2 well that would of course mean that let's just compare this subarray versus the one that doesn't include the two in that case we know for a fact that this smaller sub-array is guaranteed to have smaller sub-array is guaranteed to have smaller sub-array is guaranteed to have a greater sum than the one that includes the negative number on the front red because the negative number is basically forcing us to have a lower to decrease the actual sum of that summary and so we know for a fact that our sub-array is not going to have a sub-array is not going to have a sub-array is not going to have a negative number at the beginning and end and then more than that we can also you know extrapolate that when we're looking at the sub-array and when we're summing at the sub-array and when we're summing at the sub-array and when we're summing up the whole thing if there's ever it's not just about a single number if there's ever a sub array or whose sum is negative we never want to have that sub-array a pendant like to have that sub-array a pendant like to have that sub-array a pendant like prepended on to our resulting array because it's always gonna negate the full amount and so it's gonna subtract from the maximum and so that's never gonna give us a max and so let's think about what that looks like here so our array if we look at this we are never going to have to be the first element of our method right because it's negative to be the first time we're also never gonna have 1 2 or negative 2 1 be the first element the first two elements because we are if we did that then that would still mean that it was negative because the sum of these two is gonna be negative 1 and so it's going to decrease the total we would never have negative 2 1 negative 3 and so on and so forth we're never gonna have anything that starts here we may though have something that starts with the 1 and I'll do this in green instead we may have something that starts here because this is going to be positive and so we could have something that starts here but we're never gonna have anything that includes these first two let me do that again this one we're never gonna have anything that includes the 1 and negative 3 because that's also gonna negate our total right and so we could have this one by itself or we're gonna skip ahead and we're never gonna have the 3 because the negative 3 is negative again and then so we're never gonna have anything that starts there and so we basically have now taken this first section of the array and we say that we either have this one here and that's it or we know that our resulting array has to start at 4 so it could start at 4 negative 1 because that's still going to be positive right that's gonna be 3 it could be 4 - 4 negative 1 2 be 3 it could be 4 - 4 negative 1 2 be 3 it could be 4 - 4 negative 1 2 because that's so positive it could be for negative one to one because that's gonna be positive right we're gonna have six it could even be four it could start with this it could even include the negative five because this is still positive but some of this whole thing is one right and so if there was a lot of stuff here at the end we might want to prepend one on to the rest of that and then finally it could be this whole thing because all of these are positive and so let's look at when we look at this what we're basically seeing is that to figure out and then we're basically like if we wanted to actually figure out what the sum was let's look at the we can basically compute the sums here right we have four we had three we had five we had six we had one and then we had five right and so that was for each of these arrays and because this for at the beginning is positive we know that no matter what if one of these is our resulting array it's always gonna start at that four because if it didn't start at the four we're subtracting four from all of these values right and if we're subtracting four from the value so we're losing we're no longer at that maximum and so what does this actually mean because I'm sort of talking very hypothetical here and I want you to understand how this is actually going to translate into code and so it basically what we're looking at here is that we know that every time this prefix is negative we're going to exclude the prefix and start from zero essentially and so the way that we can compute this is actually very simple it looked it might look complicated here but it's actually super simple and all we have to do is essentially computer running some but when we compute our running sum anytime that running sum is negative we reset the running sum to zero because that's the equivalent of saying we're going to exclude the beginning and we're just gonna pick up from here and so I wanted to show you what this is actually it will look like if we were to compute the running zone so for this our running sum is negative it's gonna start at negative 2 and what we're saying is anytime it's negative we reset the running sum to zero right because we exclude that beginning so we get zero and like if you consider this as an array where it was just negative 2 then the sum should still be 0 because we would want to include no elements because the maximum is going to be 0 in that case if they're all negative numbers and so that's what you know we could we'd have to clarify if for example there was a requirement that our input or that our output included at least one element but based on the way that the problem is defined there's nothing saying that we can't have an empty or that we can't have an empty array and so 0 sort of going to be our default and then the running sum continues so now because we had we reset it to 0 now we're gonna add 1 to that and remember like we were talking about this before an easy way to think about this is just like what if our entire array was just this beginning part and so if it was just this then it makes sense that our sum would be 1 because we would just include that one element now we continue with the running sum negative 3 makes this negative again and so we're gonna reset back to zero which is what we were talking about in this section now 4 is positive negative 1 it's a negative number but our result is still positive and so we continue computing the running sum so we get 3 then we get we have 2 and so let me actually try and line these up a little better we get 2 so 3 plus 2 is 5 and then 5 plus 1 is 6 minus 5 is still positive so we get 1 and then plus 4 is equal to 5 and so you can see that it lines up with like these numbers that we had computed here is basically what we have in this and then you know let's say that we had a couple more numbers on the end like let's say that we had let's just add two more numbers so let me say that we had negative 10 and then we had 100 so now what would happen is that we would be going through our a and we would get to negative 10 and so we would reset to 0 because this would take us to negative 5 so it reset to zero and then the hundred would become a hundred and so now in this case for example you know essentially when we were looking at our arrays here we're going to say okay we got this we got to this five but then as soon as we include the negative 10 now that is no longer positive right now we no longer want to prepend this on to the 100 because if we prepended it on to the 100 then we would actually get only 95 and so we're going to reset to zero and then we get 100 at the end and so hopefully this makes sense but this is basically the framework that we're gonna follow here and I hope that you see with this what I really want you to take away from this problem more than specifically how to do it is like how logically I was thinking through the problem because it's not about what is the solution to this problem remember it's super important that we're not memorizing solutions here we're really focusing on like what is the how do we understand what's going on and how can we recreate this in the future and so hopefully that made sense the way that I walk through it the code actually you know as you can see here once you understand how to do it is super simple all you got to do is just basically do a for loop and that gives us an of and we're just summing everything once right we eliminated that repetition and so we're gonna get an event time complexity here and our space complexity we don't actually need to compute all we don't even actually need to compute or store this whole array of running sums we can just keep the current running sum and what the maximum is and so with that's all that I got for this problem again will include the code so you can take a look at that as well and I look forward to seeing you in the next video thanks so much for sticking with me to the end of this video if you enjoyed this and want a ton more like it go over to bite comm slash 50 questions and you can download our free 50 coding interview questions guide where I'll take you through 50 of the most common coding interview questions and if you like this video make sure you subscribe and hit like because it really helps us with the YouTube algorithm | Maximum Subarray | maximum-subarray | Given an integer array `nums`, find the subarray with the largest sum, and return _its sum_.
**Example 1:**
**Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\]
**Output:** 6
**Explanation:** The subarray \[4,-1,2,1\] has the largest sum 6.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** The subarray \[1\] has the largest sum 1.
**Example 3:**
**Input:** nums = \[5,4,-1,7,8\]
**Output:** 23
**Explanation:** The subarray \[5,4,-1,7,8\] has the largest sum 23.
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle. | null | Array,Divide and Conquer,Dynamic Programming | Easy | 121,152,697,1020,1849,1893 |
1,042 | hello everyone so in this video let us talk about from the problem from lead code the problem name is flower planting with no Edison wow a nice problem name actually so okay let us go down to the problem statement so you have n Gardens labeled from 1 till n and an array of paths where pathophy is denoted by X of i y o five which means that there is a bi-directional path between the garden bi-directional path between the garden bi-directional path between the garden X5 and Wi-Fi so it's actually just some X5 and Wi-Fi so it's actually just some X5 and Wi-Fi so it's actually just some sort of a graph problem in which a different nodes which are mentioned as Gardens and there is a bi-directional Gardens and there is a bi-directional Gardens and there is a bi-directional path between each Garden like not each Garden there is a bi-directional path if Garden there is a bi-directional path if Garden there is a bi-directional path if it is present in it is present inside the map which is mentioned as path between these Gardens okay now if each Garden you want to put four type of flower like any like you want to place a flower of any of the four types okay now uh the types are let's say this mentioned here one two three four and it is guaranteed the answer exists okay what the problem is that all the gardens have at most three parts so okay there's a country condition on the number of parts that is coming or going from a particular Garden okay your task is to choose a flower type for each Garden such that for any two gardens connected by a path they have different type of flowers okay so let's say if I have a particular graph in which if a particular node has some type of flower it's a one then all the surrounding nodes of the particular node uh should have been should have a different flower and another different flower so they should not be having two addition nodes with the same type of flower that's our problem statement I think so yep so uh it guarantees that the answer exists and you just print out any of the choice of answer that you want to print out okay so let's say the first example it is it has a like a graph from one till two so one okay let us not give it Arrow so one two and then I think the two three and then three to one okay two to three and three to one that is the uh like the actual graph that is let us say that if I put the first type of flow on the first node the second type of flower and the second node and the third type of flower node because I have four type of flowers four types I have okay that is fine because that is the old thing but the overall idea will generally comes from and position problem is that let us start from any of the notes okay let's say if I start from this node then all the adjacent node for this particular node should be having a different flower type okay let's see if I start from 1 then what I can directly do is that I can Mark out all the adjacent node for this node as to okay so let us start that technique out but like whether it is true or like it is correct or not so let us try that okay so let us move everything out let us start from the first very first node and give it a flower type of one now what I'll do is and because it is marked as now this is done only okay now I will Mark all the innocent nodes of this as the type 2 okay then what I can do is that I will mark this as 2 and because this is also a reasonable Mark S2 then I'm marking any other node S2 then I have to like if I'm marking this as 2 then it is fine but whenever I'm marking out another node has two I should also have to assume that if it is marking us to the other node Associated to that node also should not be 2 okay if this is also two then what I have to do is that I have to mark it as 3 actually like if this is 2 then I have to mark this as 3. and then it is fine so what we will be doing out is that if any node data marked out if I any node that I Mark out is let's say for it is 2 then all the adjacent nodes I will just like all that's and notes of a particular node I will just Mark out to be same let's say if it is one average Market out as one plus two like one plus one with that is two for two all there is a nodes will be marked out as three and from three all the recent notes will be moderate as four and one four all the Eraser nodes announced again marked as one so any nodes let's say if I have node like this one then two then three then four then five and this is again let's say one more hundred let's say six and it has let's say sevens let's this says let's say eights so I will first mark this node as with the flower one okay and all the nodes are acted to do with that flower too okay because they are addition so I should not like all the addition nodes should not be having the same type of flower so first node with one all that instead of this two then the adjacent of this two should be three okay and also keep in mind that they should if they are filtered out then I should not be filling out the only condition is that if I want to refill this the only condition is that if that's theme if this is 2 and if and this is also holding two then it is bad then I should also fill that but if the adhesive one is like different then just leave it okay this is two then this is three then this if this is three then all the relationship before this is four now from 4 this will again come down to be one now if I just mark this as one and this is again let's say select connected to this then this become false so if I'm marking this as one I should be also ensuring that the other one should not be one so if it is one I will mark it as two that is fine so that's the overall thing that you can able to do this tall amount and that's it that's the overall logic so I will be just doing out BFS because BF is just doing in a row wise server so because if I will swap mark it as one then all that isn't that twos and all that is in threes and again four so it's like a like level order trim itself that is just a BFS and we're just doing BFS over this so that's the whole thing that we're going out so let's move on to the code part now so what we have done is that we have first created an agency Matrix that is uh essentially list sorry so that is actually required how to travel through the whole Matrix so that is the overall thing add essential is now how we were doing out because it is done from one index we can also make it from Zoom indexing you can also do it on one indexing whatever you want but I've just make it on season texting so just hit it over all the paths inside the uh this paths array that is just giving out the adhesive edges of the Matrix uh of the graph actually so if this is from zero just subtracted one because it's from one to n okay but my labels are in the let's say adjacency list it's going from zeroth index to like 0 to n minus 1. so just and like subtitle one so there's a buy Direction so from U to B and V to U okay that is how we are just making icency list now after that what we'll do is that we have to store out or print out the colors on all the let the nodes so we have created a vector for storing out the colors then iterating over every particular color one by one uh let's say that maybe it has happened that I will only start from a node that let's say it is not iterated over by a BFS okay let's say that there is two nodes up actually like this also let's say one node like this and like this okay there are four let's have four flowers like there are four uh four Gardens so in that scenario they are not connected so I should like this should be one type do two type and one type and two type so that is also fine so for these type of scenarios what we actually have to do is that we can iterate over every starting node okay if they're already listed and it already has a flower tab then we just leave it out okay so what we have done is that this is a color matter like color again that is initial zero so we just hit it over every particular node and if it is zero then only we'll start making out all the nodes like uh close to it with some color if it is already colored if it is not zero which means that it is already filled with some color so a color of flower so just we don't need to do an iteration of BFS from that filter no to other nodes because it is already filled by other downloads only okay so if this is not filled if it is not iterated or like previously this is note that has not been given any flower type so we will first give it a flower type of one okay from any node that we start from it will just give it a flower type of one and what I'll do is that from there we'll start a BFS so for the BFS we'll create a queue insert the particular node from which you want to start the V first that is the is that is the ith node in Centerview uh to start the queue uh like click on iterating over the queue until it is empty uh like push out like pop out the first element that is the element we just inserted and just hit it over all the adjacent nodes of the particular node that we are on okay that we have done that essentially less we can just hit it over all the adhesive nodes of the current node okay and now what we'll eventually have to do is that we have to check that all the addition nodes that we are editing were of the current node if they are zero which means that they have we had not given any color to it then we can give it a color what color the current color plus one so whatever node I was on I have to positive all the ancient nodes of that so I am editing all the edits and nodes of that particular node that is using this follow now after it you have to check that if they are not given any color or if they are of the same color if the all the recent nodes like any addition notes if they are the same color or if they're not having color then only you should give them color okay then what color whatever color I am on plus one so let's say I am on a color let's say two or three whatever color I'm on that color plus one I should be giving out to all the edited notes okay that is currently fine and if I have given the color to that particular node I should again do a iteration or like push that particular note inside the BFF so that we can again do a BFS from the other addition nodes also because now the recent nodes have given color like given the color so the addition notes of those addition notes again like because in the level should be given colors also so that they should not intercept with the current color that I have given to that particular node and that is how and if the number of colors so what I have done is that colors of J the listen nodes should be given the current color plus one okay so if it is gone like outer bound more than four so I just do it uh let's say what a four so that it will comes down to again for okay so all the nodes will be then given the color and that is how our BFS is like done over all the nodes and just in the final answer you should learn the color that we has been assigned to all the nodes inside the graph so that's the overall thing it's just a simple BFFs just have to understand that what is the overall use case for your BFS is so that's it that we have done if the current uh so it's uh you can say a particular uh like graph by portraiting type of example also so there is a generally very use a good case in which you have to buy part okay you have to uh like divide the whole graph into two set like two sub the sub segments in which uh all the segments from one half and uh such that uh we have to color the whole graph into two type of colors such that let's say green or blue and then all like you can have to group out the uh let's say graph into two segments so that there is no uh Edge between the current group but there is only Edge going out from the other like to the other group actually so that which actually means that there is no adjacent same color so this is just a bipartorting type of algorithm that we have used okay that is you have to take a graph and has to color that full graph into two colors so that no two recent colors are same that is a bipartizing type of uh you can say algorithm and that is also we have done okay but it is some sort of a slightly modified because we have four colors instead of two okay so you can also look into a more by bar charting type of algorithms online you can I will also message down in the comment box or like uh in the description of this particular video as well personal logic and the code part for this set like this problem as well if you still haven't segment in the con box of this particular problem thank you for watching till the end I will see you in National League coding and bye | Flower Planting With No Adjacent | minimum-cost-to-merge-stones | You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers.
All gardens have **at most 3** paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return _**any** such a choice as an array_ `answer`_, where_ `answer[i]` _is the type of flower planted in the_ `(i+1)th` _garden. The flower types are denoted_ `1`_,_ `2`_,_ `3`_, or_ `4`_. It is guaranteed an answer exists._
**Example 1:**
**Input:** n = 3, paths = \[\[1,2\],\[2,3\],\[3,1\]\]
**Output:** \[1,2,3\]
**Explanation:**
Gardens 1 and 2 have different types.
Gardens 2 and 3 have different types.
Gardens 3 and 1 have different types.
Hence, \[1,2,3\] is a valid answer. Other valid answers include \[1,2,4\], \[1,4,2\], and \[3,2,1\].
**Example 2:**
**Input:** n = 4, paths = \[\[1,2\],\[3,4\]\]
**Output:** \[1,2,1,2\]
**Example 3:**
**Input:** n = 4, paths = \[\[1,2\],\[2,3\],\[3,4\],\[4,1\],\[1,3\],\[2,4\]\]
**Output:** \[1,2,3,4\]
**Constraints:**
* `1 <= n <= 104`
* `0 <= paths.length <= 2 * 104`
* `paths[i].length == 2`
* `1 <= xi, yi <= n`
* `xi != yi`
* Every garden has **at most 3** paths coming into or leaving it. | null | Array,Dynamic Programming | Hard | 312,1126 |
205 | Hello Gas, today's question is, so here we will maintain small example maps and the second will be the hashmat of character bullion, so what will be the character bullion, what character bullion will do is that it will help us track which ones. Our elements have been done so that we can track them, how will we track them, now we will see when we create two hashmats, we will start and this is the character, it will store the character which is mapping and it will track this map and So what will be there in this track, now if this Hashmat is created in the beginning, then it will be empty, now I have filled it inside, don't think sochiyega, do n't pay attention that there is something in it, right now both these hashtags are empty, first of all we will do both the strings. First character from the first two characters will be ours. When two characters will be gone, first we will check. Now it will be empty in the starting, so we will check whether it is mine lying here, then it will not be read here because it will be empty in the starting, so what will we do? Which is Similarly, B and A will come, then you will see in the beginning, there is nothing on the map here, I have written this, but A and If you see A then it is not read here yet, now only Then if A and That this is correct then if C and S are there then C is here otherwise it will come here and see if C is also not here then it will make S true and then it will group it, then after that it will also group C and S inside it and then after that B will be added. And when A comes, you will see that B is lying here, so its A character here, check it with this A, then you will move ahead, now A and X will come, you will see that A is lying here, then its X and We will match it with its A and They will send a team inside, then A and If it has happened, then after making S true here, we will group it again, then after that B and A, if A is gone, then we will come here and see that B is lying there, then what will we do if B is read, then from its A to its A, We will match both of them. If there is a match then it means that the mapping is correct. Then after that A and V came and then when A and V came, we saw that here A is read here but here there is V and Here there is Now, the A below here should also be mapping with one of mine. If you see here, the A which is here is also mapping with B and with C also, I am mapping it with two. Also, you should not do single, otherwise nothing will be done anyway and when we understand it, then do not think at all about the court on time, you do not have to think about the court, you just have to think about what is the approach and how. How is the meaning of tax appearing? Do n't think about the court at all, it is okay, the first one is mapping and the second one is tracking, then it will come and then you will see. Here, here too, if it is empty, then inside of Will put inside this, then will A and If X comes then A is lying here and now but here X and C is A here so come here and see if C is lying in it No if C is not lying in it then let's see A further If A is lying in this then Han A is lying here then if A is lying here and C Han If you haven't read then this is wrong because one is mapped with one only, so if A is lying here then it is wrong, then this is one of our testicles gone wrong, then this is also my wrong, so we just have to think like this. Now we will implement only that approach and Han is one thing and as its length is equal to both then only mapping will be done. So first of all if lenthanon is not equal then mapping cannot be done. If it is not then we will return from here. Will say that this is my mistake, okay sorry, now we have to create another one, so this is my second one, only then it would have come, so we can take anyone's, this is equal to zero travels, how will the characters emerge first, will they emerge from the spring of S, what will be the rate? The first character will come out from the caret eye and how will the second character come out? If this is equal, if you are true, then nothing, then what do we do now, like if we come here, if one is containing, then we are doing something. If it is not doing, then we are doing something. So what are we doing the key is like there is If it is then what will we do like if the if condition is not there then it means that if is wrong then it will come from L then it will come in else where will it come here so if it is not there then what will we do? Will we search for Have read, if This character of mine is lying here, so what will we do with it? Will we return it if it is wrong? So what will we do with it? We will go inside our Hashmat Tu and see whether it is doing content. Is the character giving content to you? If the character is doing content to you. If it is containing, then what will we do? We will return that it is false, but if its mapping is containing, then we will false from there and if it is not containing, then we will put it to whom. Who has it and what are they doing after that, after putting it here, then we group these two here, like X came here A was not found, so he got A's team gives here and then in h1 also A's team gives, it will come and put in h1 also, what will actually come in actual and will put the character Van and the character will put you here, okay this much is ours. And if as soon as it comes, it is doing our content like it is already doing the content, if A and If we gate from the van, then ours will come out and it will be A, that if I am doing the gate, if he is not found, my character is not equal to yours, then what will we do, will we return, false return false, like A and X, if these two are together. If you don't get it, you will return it. False, okay, so did we do everything right? Ch2 Bullion cannot be converted, so let's see after submitting the care. So this is what we are doing. | Isomorphic Strings | isomorphic-strings | Given two strings `s` and `t`, _determine if they are isomorphic_.
Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
**Example 1:**
**Input:** s = "egg", t = "add"
**Output:** true
**Example 2:**
**Input:** s = "foo", t = "bar"
**Output:** false
**Example 3:**
**Input:** s = "paper", t = "title"
**Output:** true
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `t.length == s.length`
* `s` and `t` consist of any valid ascii character. | null | Hash Table,String | Easy | 290 |
1,784 | let's solve the problem 1784 check if binary string has a at most one segment of once given a binary string S without leading zeros return true if s contains at most one contigous segment of once otherwise return false the question is that you'll be given a binary string okay a string that represents a binary number something like 1 0 1 Etc it will have only zeros and ones and you need to return true if there is only once one continuous segment of one and not two so if this was the ex input string if this was s we had to return false but if say this was s then I would return true right if this was S I would return false right so all the ones should be at the start of the string right so how could I solve this simple I'll go through the string okay using a while loop while I less than length of s and in character at index I is equal to 1 then I'll increment I okay similarly once all the eyes are gone through it will look for zeros so it will go from wherever the I is at the after this Loop and go from there till all the zeros are covered okay then again I'll check the first condition that is there any once after the zeros if there is then I'll return false else I'll return true so what essentially will happen here is if say the input is 11 1 0 so it will go the first file Loop will go from start till here then the second while loop will start from here and go till the end and the third while loop will not run because the condition won't be true right that is it will reach the end okay the other way I could also do is I could just to something like this if it has not reached the end means there are some once after this right and say if all the numbers are once in that case the first while loop will run second and third while loop will not run and so it will return true if there are zeros after this even if there is one zero after this first while loop will run second while loop will run third won't run and it will return to but if there is another one after the zeros then this third while loop will run because this condition will hold true I hasn't reached the end and so it will return false let's run and see worked in these two cases let's submit it that worked for all the cases 5 milliseconds better than 97.3% of submissions | Check if Binary String Has at Most One Segment of Ones | minimum-initial-energy-to-finish-tasks | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "110 "
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
* `s[0]` is `'1'`. | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern | Array,Greedy,Sorting | Hard | null |
1,947 | okay hey everybody this is larry this week over q3 of the weekly contest 251 maximum compatibility score sum so for this problem uh the first thing to look um well so yeah so hit the like button hit the subscribe button join me in discord especially if you like solving this contest form come to my discord we talk about con test problems right after the contest so if that's it that's what you're into come hang out anyway so for this prompt um it's a little problem or a similar variation of a gnome farm so yeah there are a couple ways to do it maybe this maximum bipartite matching is kind of one thing that you can google up uh in other words like maybe hungarian algorithm things that are kind of really high energy high powered will take you a long time to implement though i'm sure the top people already implemented it and can copy and paste but in general so the first thing but knowing all that and knowing that those don't really come up on interviews and really rare even and competitive because they're just like trivia to some degree the first thing i did was i looked at the constraint and when i saw that m and n is equal to eight um or that there are eight students and mentors then i knew that i can do brute force all right i actually end up making a dynamic programming but brute force is good enough because if you put first it's going to be just ignoring the cache for a second if you prove first this is going to be 8 factorial and each of those eight factorial permutations we do a linear time thing right so let's just say i don't know this is roughly right i think but eight factorial times eight is going to be roughly 30 you know 25 000 right so that's gonna be fast enough the way that i did it was with dynamic programming so this is actually eight times two to the eighth which is you know if you know your math that's just two to the eleven you know this is exactly two to the eleven right because eight is two thousand two which is of course roughly two thousand so that's going to be two one four eight if you want to note it up but yeah so that's basically how complexity but and what i did was i used to bit mask dynamic programming i have a i have some daily problem type videos that are very good with dynamic programming or big mastering programming i'll put a link below let me know what you think about those but in general um yeah i pre cache the score here which is underscore is just what they tell you which is you know you compare the answers to um to kind of get it um this one this i don't know if this is necessary it probably isn't but it allows us to kind of do this thing in a more straightforward way because you know you don't want to keep on doing this every time because that's just more like if you have to look up i uh index and j every time uh you know that you're doing redundant work right so that's basically the idea behind caching it or just pre-calculating it caching it or just pre-calculating it caching it or just pre-calculating it and here it's basically okay so we have students at index mentors and used and the way that i think talk about bit mask is that use you can think about it as a in a list of boolean values because you can think about binary values as a bit mask as kind of um you know if we have a list of boolean values you can imagine it be like true false true and then if you convert those two numbers in with one zero one and you know and of course that's just a binary number right because now you can put them into a binary number which um and so that's basically the idea behind uh bit mask dynamic programming i have it more in depth in other videos so um i'll put a link below or a friendly user might um but yeah but in that case yeah so students are an index so we look at the students one at a time and for each student we want to map a mentor to that student um and it's pretty much straightforward in the sense that um yeah so we use up this student and for this mentor we use the jf mentor right and we check that it is unused first and these if statements look complicated but if you want to think about it as a boolean array then it will just be if used of j if not u sub j if this is a boolean array and this is just to um set you know this is essentially the same as doing this and then going recursively but bitwise version of what i'm doing here um yeah and of course matching um matching student i and mentor j is going to give us a score of i j which i have here and that's good enough to get us the answer um maybe i'm going a little bit faster on this one for that but i think leeco has just been doing a lot of these big mass dynamic programming lately so i have a bunch of videos on them so definitely you know look them up let me know what you think uh especially there were a couple of monthly uh was it the daily july problems or whatever maybe it was last month but yeah um if not come to my discord and ask for a link and i'll share it there um yeah so as i talked about earlier this is the complexity it's going to be because we do a dynamic programming cache it is going to be n times 2 to the n because oh actually i think technically it's actually n squared times 2 to the n and the reason is because well that's not true this should be n times 2 to the n um because index can go from 0 to n used can go from 2 to the n but there are a lot of unreachable states because for example um you know index at two use cannot be zero right because we literally match them up one at a time so there's some impossible states and i think it sums up to end times to do um yeah i think it sums to two to the end states oops actually it sums to the number of states total number is 2 to the n and the way that you can see that is that technically speaking the index actually adds no information it makes it a lot easier to program but it actually has no information then why do i say that because if you remove index from this it still works what you can do now is just um indexes equal to zero um and then now we can count used right so like something like for uh for j in range of m if used um equals to uh greater than zero index plus one right so this is actually the equivalent code and as you can see then that means that the total number of states is two to the n um this is actually a cool idea i think i it has come up a few times um and which is why i am able to kind of think uh talk about it um but because i keep forgetting to bring it up even i knew that this is a thing um so hopefully this is something that would be cool for you to learn um but yeah so that's just the total number of uh states and when i say states is equal to possible inputs and now that we've you know and each of these does of m work i keep on mixing m and number one well i think n is equal to m in this case i just misread it in the beginning but um but yeah so each of them does all won't work each input does all of them work let's just go back to n so total complexity is over of n times 2 to the n um that's pretty much it and you can kind of see that the space is the number of input which is also 2 to the n and this is true even if we just had index so yeah even though it doesn't look that way so sometimes it could be deceptive and you can look into it a little bit more anyway um yeah that's all i mean i think you can also add this to n squared times q i think but um so actually if you want to be more precise this is uh this is this times n squared times q and space is this plus n squared because we put it in the score just to make things easier so but given that n is equal to eight you know not really worried about it um cool that's all i have for this problem i think so let me know what you think and you can watch me solve it live during the contest next let's get to the next one even though you know a lot of jake's penalty okay maximum compatibility score some what is n okay n is eight so this is just going to be um big mass dynamic programming right um if it's if n is greater than a this is actually the hungarian algorithm or something like that depending on some constraints which i'm not looking at right now but may even be actually just be proved first because it's eight factorial right eight factorial is forty thousand times eight just in case it's n times n factorial so yeah um okay let's do it you can actually cache this but i'm still going to write it with big mask because i'm just more familiar with it i might as well cache it in that case okay yep okay and now that score and now to calculate the score this is equal to so they just literally go further away yikes did i mess this up why did you have four student 0 2 4 3 i agree that zero to two i messed this up j you know that's what okay so that looks good now that i stopped being dumb let's give it a submit okay good uh yeah thanks everybody uh thanks for watching hit the like button hit the subscribe button join me on discord hope y'all have a great weekend um yeah see you later stay good stay cool bye | Maximum Compatibility Score Sum | number-of-different-subsequences-gcds | There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes).
The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]` is an integer array that contains the answers of the `ith` student (**0-indexed**). The answers of the mentors are represented by a 2D integer array `mentors` where `mentors[j]` is an integer array that contains the answers of the `jth` mentor (**0-indexed**).
Each student will be assigned to **one** mentor, and each mentor will have **one** student assigned to them. The **compatibility score** of a student-mentor pair is the number of answers that are the same for both the student and the mentor.
* For example, if the student's answers were `[1, 0, 1]` and the mentor's answers were `[0, 0, 1]`, then their compatibility score is 2 because only the second and the third answers are the same.
You are tasked with finding the optimal student-mentor pairings to **maximize** the **sum of the compatibility scores**.
Given `students` and `mentors`, return _the **maximum compatibility score sum** that can be achieved._
**Example 1:**
**Input:** students = \[\[1,1,0\],\[1,0,1\],\[0,0,1\]\], mentors = \[\[1,0,0\],\[0,0,1\],\[1,1,0\]\]
**Output:** 8
**Explanation:** We assign students to mentors in the following way:
- student 0 to mentor 2 with a compatibility score of 3.
- student 1 to mentor 0 with a compatibility score of 2.
- student 2 to mentor 1 with a compatibility score of 3.
The compatibility score sum is 3 + 2 + 3 = 8.
**Example 2:**
**Input:** students = \[\[0,0\],\[0,0\],\[0,0\]\], mentors = \[\[1,1\],\[1,1\],\[1,1\]\]
**Output:** 0
**Explanation:** The compatibility score of any student-mentor pair is 0.
**Constraints:**
* `m == students.length == mentors.length`
* `n == students[i].length == mentors[j].length`
* `1 <= m, n <= 8`
* `students[i][k]` is either `0` or `1`.
* `mentors[j][k]` is either `0` or `1`. | Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a valid subsequence for x , then the subsequence that contains all multiples of x is a valid one too. Iterate on all possiblex from 1 to 10^5, and check if there is a valid subsequence for x. | Array,Math,Counting,Number Theory | Hard | 2106 |
1,457 | Loot Guys Welcome and Welcome Back to my Channel Our problem today is Shiv Palace Roaming Pass in Every Such Problem Statement What have you given us, here we have been given a binary tree in which the value of the note is from your lineage to 9 Okay, what we have to do here is to fine the number of you toe paint religious pass going from day root note to lip notes Okay, so to understand what this tuto paremi pass is, we have to understand who intro mix bread on the seats Okay, so let's first understand this as an example, what is our exact problem, is it in the studio talent show, then how will we solve it? Okay, so look here, Pseudo Paremi means that now we have given a number, you can edit it and tell us. -Can you convert it into enrollment number first? If -Can you convert it into enrollment number first? If -Can you convert it into enrollment number first? If not, then consider it as a suggestion. You have given Vansh 3121. Okay, now tell me, can you create an enrollment number using this number? Yes, it can be made 131, you will take it. Once our paste is made then this is your studio parents and mixed and this is your paintro mixed okay then see 1234 can you make pant dali number using this number can we become yours take two here follow husband Such people will go the way, your time will become tomic, not like religious. What is the meaning of any number, now you reverse this team, even after using it becomes your number again, then that leg would have been longer, you will learn Wright 101. If you reverse it will become 101. If you arrange this number, then you will get the remaining number, so it is in your parents and theirs. Now our problem is that we have to come from the root note to the written note and in between, by using the number army, can we first solve these problems? Religious number can be made, see if this is yours, can you make an enrollment number using this, are you free, then this can be made, here it can be made 323, this will become your academic height, then see, can you use this now? Can it be 123, can it be made by using it, can it be made Nirmal, then it will not be yours, it will be a part that has been given to you during the day, so can you make it by using it, can you increase your enrollment number? If it is 121 then this is your should parents and got mixed and here is the enrollment number then if you get that used toe parent milk powder then how much will you get in the spinal tree if you have to return that account then this is your one and this is your second. It is done, ok, now tell me, you have given a number in it, so how will you know whether we can make it, we can't make it, without ending it, how can you find out, then you have given a house number, see if you The number is given here, two three 46 certificate, account of the number given, if yours is even, whatever the number is, its frequency, if yours is Hussain, it is only even, then we will make it, we will be confirmed by this, why? Here also you have account of both of them. Here also you have account of both, this also has account, most of this is two, so from here you can make it, you will make it from broken, then here you will make the code file, you will make it like this, if you get education then you can make it. Here there is a fly, there is an account, there is a teacher, there is acid, there is a money plant, we can create work, for this we will leave it, we can increase the price of petrol, it is okay, if here it would have been kept for free. If you kept it, the teacher was giving it hurts, then who knows, you could have made it a PAN card number or not, edit it because its account is frequency one, its frequency is fine and its frequency is yours. There is seven, we cannot make it here because what is ours more than one, here is our chord, you can also balance the previous A, two, three, four, if you break it in any way, then this is not ours, okay, but this mask is listener fiber. What would have happened is that yours and the discretion are the same, the value is two of six, so you could have made it, so here I have given you the rule of what will happen, that if the other frequency is in the frequency of the number you have, there is only one such. It is the same number whose frequency is different, then what will it become of you? The number can become an academic. Okay, so we will do the same, we will use the data here and what will we do with the account of the number, what will we do till our lips note, by adding one place. We will keep the account, okay, we will store the account, then we will see when we come to the list, we will see if any number has more than one number and frequency in coming here, if there is more than one number and sequence, then our Will not be nearby but only one or one to number you and the frequencies, okay then we can create the path thing, so we will use the date here, together we will take care of the frequency, what will we do for this by doing next here Let's take it, okay, and because we know that our dip is the digit, the length of our note is from do one to the value of nurses, okay, so what we will do is add the tan size here, then the interest will be done. Zero 12345 680 Porn Your no deposit will be like a note, what will we do, we will take these fruits and vegetables, okay yes, this is a complete rebellion for most of the people, okay, so what will we do now, we will start from here, we will meet, you use the inverter, now free mode is on. You can post more, you can use it more, if you become a fan in the country, then I have ordered the belief here. Okay, so we will start from here, Saheb Alam, what will we do, we will keep the account of * here, we will keep it, okay. There is one, account of * here, we will keep it, okay. There is one, account of * here, we will keep it, okay. There is one, then if we come here towards this fort, then we will keep its account as one. I felt like we will find it towards the club, then we will find its account towards the club, then we will keep it as two. Okay, then after this, if we go here, then this is a tap, so see the light bill. What is the light bill? Have we found both the drains? This note is there. Okay, now our job is to check whether we have reached here, do we have any number which has a different frequency and is this number more than one? So here you will see that it is 797. There is one more rod and one off, so together it is also 715. Only one has been found or not, it can be yours because in the cord account we have just found two, which has a different number, but this number is only one, tell me which one. And the frequency with the account is your one, so now what can it become? So what will we do, we will take an account variable in this, what will we do in it, we will take care of ourselves, make this close, then the first part is made, your one will become OK, when you return that. You will go, his account will become one again, it is okay because we will not use it responsibly, there will be no 'V' in the factor, if be no 'V' in the factor, if be no 'V' in the factor, if it goes back, then this account will go that way, then it will go this way, his account will go to two, sorry, it will be 1.1. Sorry, it will be 1.1, okay, sorry, it will be 1.1. Sorry, it will be 1.1, okay, sorry, it will be 1.1. Sorry, it will be 1.1, okay, then it will look at the black side, so this is the recipe channel, this will also be rejected, I have memorized it and we will check again, even the account which is yours, what to see, its also all has not and frequency account's one. If it is there then there is three backbone i.e. number 3, your three backbone i.e. number 3, your three backbone i.e. number 3, your number is three which has more frequency i.e. number is three which has more frequency i.e. number is three which has more frequency i.e. from here you cannot make it, okay we will not make it, editing will remain till the work is done, we will give it back, okay like this, then again sorry, we will go towards the height of feet. Okay, we will go towards the right, Priyanka will see this again, when we come back, withdraw this cord again, okay, this is your card too, here again it will go to zero, then it will go to half hot, then it will go towards 251, the account will be again. Will we go towards the right side of the fee, why is it a wet canal but if there is a note present on the right side, then we will go here, okay, this scandal will be widely broken, or will we choose, will we go towards the left, is this yours? There is a tap, then we will see the light too, okay, then our job is to check the account, and the frequency here is only two, it is already gone. Okay, Mouni Roy, this one is two and everyone else's is zero, that is, what has become of you? If one cup of your bangles is Panchami part, then we will take account of you will do it, yes sir, what will go to you will do it, okay Sonu, let us look at the second example too, if we start from here, then account of 12 will be taken as ours, then 1 will be done. Will go towards one's account, will become one's own, then will go towards its lap, will go towards marriage powder, when will go towards its life, this is the channel, then you will see this too, no relief, after that you will check which you have started in the vector. Is it doing more pod frequency contact or not and if the frequency of the account is of seats only then it is one i.e. one to one will be then it is one i.e. one to one will be then it is one i.e. one to one will be less than one only, those who have seen their account in which they are keeping total pass will do sukoon plus. This is zero true, we will do this one, okay, then if we go back, we will go, its control will be taken, this is okay, then work will be done, we will become friends, then we will go, then the method will be worked, volume will go again, if we go left, then we will canal. Okay, let's take it back, there is seven percent on the right, it cannot be any more Italian, then we will go towards the right, it will be done again, it will be set again or we will go till the last, tap subscribe, then we will go to this, i.e. liquid. Will check the form, then we will go to this, i.e. liquid. Will check the form, then we will go to this, i.e. liquid. Will check the form, is the audit and frequency contact more, does anyone have it because it is near the bakery, that is, the frequency counter is also there, we will need only one or less than one, so this path is not possible for you, okay then we will go back. 1.1 It will be is not possible for you, okay then we will go back. 1.1 It will be is not possible for you, okay then we will go back. 1.1 It will be fine, your account will also go back to the plane's account which is one, this protest will go back to your account that we will put it, we are going till like this, okay one, what is yours here, who is theirs then consume it, move to the next. If you don't go and take the stitch, it will get rectified, then you will see that he also has a Tata account and his account is also yours, then what will happen in this condition that the number two job is drop oil, that is not a possible thing here, we will go back only one. Had only got the answer, does she come from this contest, second previous Adnan Sami, what to edit, you have taken a person, from the frequency name, its size is Patel, so that the index can be found from zero to 9 inches, from one to the leader of the hero. The search will remain the same, then what will be your account, whatever will be in the mark, what will we do, we will call the gas, we will make it routine, we will set the frequency in and we will make the account. Okay, so here we have taken the sequence, we will frill this beauty plus two. I will find it will be returned, we will type here, Prince will travel, we will do plus, okay, like end frequency of player is here, we will do it here, we will press here, then after consuming that number, we will move like that loop, okay now A class. 9th What will you do here, you will do that there is no electrolyte tap, it is a journal, then look at all the numbers that have been drawn in the chapter on your weight loss i.e. pregnancy in frequency, travel account, Skoda, numbers that have been drawn in the chapter on your weight loss i.e. pregnancy in frequency, travel account, Skoda, numbers that have been drawn in the chapter on your weight loss i.e. pregnancy in frequency, travel account, Skoda, okay, then someone's account and yours. If it is that vote account which is fancy and whose number is whose and is it your number more than one? What if it is more than one. Determine if it is possible. It is less than one. It is possible. First of all you have to point out how many numbers. It is fancy and so we have taken a carrier and an account, now we will see which one of yours started providing active sequences, then you see whose number is different, okay, you will divide by two, you will get one and who will press and stitch, how many numbers will your And do n't feel okay if it is more than oct 1 then we will not do account plus but if one or unity 1 tsp is less than one then we can do account plus okay so this will give you the text from the account in Mika Here we will tell you the difference food color, then it will be updated in the account, we will do the content of the final chapter. Okay, we hope you have understood. If you liked the video, then please like, share and subscribe. | Pseudo-Palindromic Paths in a Binary Tree | minimum-difficulty-of-a-job-schedule | Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be **pseudo-palindromic** if at least one permutation of the node values in the path is a palindrome.
_Return the number of **pseudo-palindromic** paths going from the root node to leaf nodes._
**Example 1:**
**Input:** root = \[2,3,1,3,1,null,1\]
**Output:** 2
**Explanation:** The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path \[2,3,3\], the green path \[2,1,1\], and the path \[2,3,1\]. Among these paths only red path and green path are pseudo-palindromic paths since the red path \[2,3,3\] can be rearranged in \[3,2,3\] (palindrome) and the green path \[2,1,1\] can be rearranged in \[1,2,1\] (palindrome).
**Example 2:**
**Input:** root = \[2,1,1,1,3,null,null,null,null,null,1\]
**Output:** 1
**Explanation:** The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path \[2,1,1\], the path \[2,1,3,1\], and the path \[2,1\]. Among these paths only the green path is pseudo-palindromic since \[2,1,1\] can be rearranged in \[1,2,1\] (palindrome).
**Example 3:**
**Input:** root = \[9\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `1 <= Node.val <= 9` | Use DP. Try to cut the array into d non-empty sub-arrays. Try all possible cuts for the array. Use dp[i][j] where DP states are i the index of the last cut and j the number of remaining cuts. Complexity is O(n * n * d). | Array,Dynamic Programming | Hard | null |
129 | hey there today we'll be doing this question that is one to nine some root two Leaf numbers on lead code and the given question statement is you are given the root of a binary containing digits from 0 to 9 only each root 2 Leaf path in the tree represents a number this part is very important for example root to Leaf path one two three represents one two three and we need to return the total sum of all root 2 Leaf numbers this part is very important that is root two Leaf numbers and what does that mean so let's understand this with an example so root to leave means we start from root till the leaf cloon and the leaf nodes are those nodes those are having no childrens and that is what a leaf node is so we have to generate all the root 2 Leaf nodes number and sum every one of them so what are the possible numbers here one of the path we can take is 495 this one and the other part can be are four nine one this is one of them and the other one could be that we take four zero this one so whatever the summation comes out to be that is our answer fine so this is what we have to return now how do we do this question actually so a prerequisite to this question would be you should know pre-order of the pre-order of the pre-order of the binary pre-order traversal so if you binary pre-order traversal so if you binary pre-order traversal so if you know pre-order traversal you'll be good know pre-order traversal you'll be good know pre-order traversal you'll be good to go for this question so pre-order to go for this question so pre-order to go for this question so pre-order basically means at first we go to the root after that we go left and then we go right that's what the order means so we'll be tracking the number in some Manner and we'll be taking on by doing a pre-order travel so let's see how so at pre-order travel so let's see how so at pre-order travel so let's see how so at first we started the route fine and let's just see we have a sum variable which is storing our sum and there is a variable called temp now what is the step two will come to it okay so let's just see we are at the starting point so at four so somehow in my number I'll just create this number okay and store it here and how are we creating which we obviously do know how to create these numbers that is whatever the number we have we say simply multiply it by 10 and we add the number sorry this should be the variable temp that is temp okay and this is a very uh simple thing that we do and this is how it gets generated let's just say if our first number is 4 so times value initially is 0 so 0 into 10 plus 4 will be generated okay after that we have nine so the next number would be 49 so my times value is 4 right now 4 into 10 is 40 plus next time I will have 9 here so it will generate US 49 so this is a pretty basic thing that we do to generate numbers right so yeah coming on to the times value at first we have 0 so 4 is generated now pre-order traversal 4 is generated now pre-order traversal 4 is generated now pre-order traversal means we'll go to the left first fine so here we come on to this part now here we will go to the root first and we know that is this is the root here right after that what are we going to do we are going to generate the number so we generate the number that is a new number comes out to be 49 right so 49 is generated now we go left after that we see that 5 is there now we generate a new number that is 495 49 is cleared and our new number is what four nine and five this that is 495 so now comes the most important part if we see we are at some node whose left and right child does not exist that means I cannot go any further then I'll see that okay whatever number I have generated till now add it to my sum so initially my sums value will be zero I added to my sum so my sums value is now 495 okay now comes the interesting part so we know in pre-order until this thing is done so it pre-order until this thing is done so it pre-order until this thing is done so it will go back now it will try to go to the right part obviously so now when we try to go back what are we going to do we are simply going to see whatever number I have in my temp I will just delete the last one and how are we going to delete the last number we'll just simply say temp by 10. we'll just divide it by 10 so that the last digit is deleted now my number stands out to be only at 49 okay so the large digit is deleted fine now as the pre-order goes deleted fine now as the pre-order goes deleted fine now as the pre-order goes we'll just simply go into one we'll create a new number that is 491 now again we'll just check that condition is it satisfying does this note not have left and right children that means that is true it only has none it does not have any children so what are we going to do we are just going to add it into our sum so 491 will also be added now this thing is also done now we go back now we try to go back this is done and remember while we were going back what are we going to do yes we are just going to delete one by one every number so one is deleted now when we go back to 4 what will happen we'll again go back to 4 so now again one number will be deleted now we are only left with four now we'll come on to this part that is 0. now we see that 0 is there okay form 0 done now yes again we just check if the left and the right node are not present that is it is null that means the childrens are not there it is a leaf node what are we going to do yes we are just going to add it into a sum and whatever the summation comes out to be we are just going to return that as our answer so this is the whole intuition and the whole walkthrough of this of how we are going to do it now if you will see the code you will understand it perfectly fine once you see the code it will be very easy for you to understand on how this is working totally and it will be very clear to you okay so now let's move on to the code part and also the code will be linked in the description you can check it out from there as well so this is a pretty simple code very small code so at first what have we done we have taken us some variable okay and we have taken a temp value if you see in the function this is right here so we have taken a sum variable and a temp variable as discussed right there now what are we doing we are saying if it is a null then return 0 what do I mean by this so let's just see somewhere around this if I try to go left is there any node there obviously not so we return something right we return a null so that is why I've said if there is no node present there you just return 0 you don't have to do anything but if there is a node I go inside and I do form the number that is what we had done there right we were just forming the number by that formula it is very simple whatever the number is multiplied by 10 and just add whatever the digit is it is very simple this thing so this is actually used many a times okay so after that we were just checking if it is a last Leaf node that means it is our Leaf node and we do not have any left or right children what are we doing we just see add it to my sum right that is what we were doing when we had found that this is the leaf node and that does not exist any left or right children that is what the meaning of leaf node is what did we do we just added whatever the number I formed into my sum that is what we are doing here now this is a simple pre-order travel still this is a simple pre-order travel still this is a simple pre-order travel still we go left first then we go right and remember whenever we were backtracking that means whenever we were going back what did we do we deleted the last digit so this is what we are doing we are just deleting the last digit and at the end of the day we are just returning the sum so this is the whole code here and I'll just reiterate the backtracking part that means this part let's just see four nine and five was formed when we are here this thing is done now we see that the whole number is formed left and the right children does not exist so we go back so what do we just delete this and now we come on to this one and we form this 491 okay so this is what the backtracking part is and this is the whole code right here and I hope you have understood the whole thing and if you still have any doubt you can ask me obviously in the comment I'll be replying to it and yeah if you did like this explanation | Sum Root to Leaf Numbers | sum-root-to-leaf-numbers | You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`. | null | Tree,Depth-First Search,Binary Tree | Medium | 112,124,1030 |
315 | welcome to june's lego challenge today's problem is count of smaller numbers after self you are given an integer ring nums and you have to return a new counts array the count's array has a property where counts i is the number of smaller elements to the right of num's eye here at five we can see that there's two numbers two and one that are less than five so that's two we see one is uh the only number that's going to be less than two so that's one and then so on so forth one zero so if we were to solve this straightforwardly we could easily do this in n squared time right like for five two six one we could just do a nested uh for loop and just check each time all the numbers right of it to see how many are less and then add that to some sort of output but instead of doing that um surely there's a better way to do it and one way we could think about this is if we moved backwards this would be one 1 2 i believe if we moved backwards we can see that the first number is always going to be 0 because there's nothing to the right of it right so what we'll do is build up some sort of data structure to add whatever numbers are in here going backwards so at one we know that's going to be zero automatically and at six we'll store one somewhere and check to see how many are less than six but that's the problem doing this would become another ends and number of time so what data structures can we use to like make it a little more optimal well first i thought maybe a heap would work and we'll just pop off whenever it's greater but the problem with that is we can imagine that if we had like a seven here and we pop off six when we get to two and add two there then we forgot in about six right so we can't use a heap what we'll have to do is use some sort of sorted list here what we'll do is like have a sorted list and we'll add one and we'll just add six and each time we insert that's going to be a log n time complexity and what we'll do is do a binary search to check to see where this number belongs to and however many numbers there are to the left of it we could figure that's going to be the number of numbers we can add here okay so let's begin by first from sorted containers import sorted list and what we'll do is initialize a sorted list just call that s and we're going to store our output and 4n in nums but we're going to move backwards we're going to do a binary search we'll use the bisect left function uh with our sorted list and we'll search for our end and i'm i believe i might have to do it like sorted list bisect left and we'll get our answer and we'll add that to our output and then we'll add to our sorted list whatever number this is and finally we can just return our output but make sure that this is reversed because we're going backwards okay so let's see if this works sorry containers that's our container contain those containers not containers okay it looks like it's working so let's submit that and come on barely there we go so that's going to be an n log n time complexity because we move through n and this sorted list is going to be log n every time we do it bisect left and do an insert here now there is one other method we could use a binary index tree rather than a sorted list i'm not going to go too into it because it'll take too long but basically if we have a binary index tree what we can do is store the index indexes of the numbers if we had sorted this what's the index number and we'll use that index number as the index at inside the array so if we had like six five i don't know two one each one of these are going to be represented by the number it would be in if we sorted it so this would be one this would be two this would be three this would be four and all we have to do now is uh see if we have like repeating numbers like two this would be two as well and we can use some sort of array to store how many we've had in here at this point so each one of these index points represents uh the index point here and each time we see one we can just increase it so a one um let's say we increase that and increase that to one then we increase this to one and then this to two and each time we just search all right how many at two here what's the sum of everything to the left here and that like here would be like one right and luckily using this query would be um login time as well so let's do try doing this what we'll need to do is first sort our nums well actually we got to first make into a set then sort it and then we're going to well let's call this e make some sort of a dictionary let's say enumerate this for index number and value and enumerate that and the value is going to have the index number okay next we're going to create our sorted list not sorted list i'm sorry our binary index tree and this will call b i t of what we need to pass in the length of e here right so everything else should pretty much be the same except instead of numbers we're going to have to create an indexes called indexes and this will say for n in nums what is the e n what's the index value here and this will be in the same order as nums right so now instead of nums we're going to move through our indexes and we'll um let's see we are going to first query our binary tree we're in query and we pass in our let's see index value and i believe i need to add one here it could be wrong but let's see and our delta is just gonna be one each time right now we query that and we append our answer and then we add to our binary tree update oh wait this is right sorry this would be i and let's see update i plus 1 and this would just be i query i believe everything else should remain the same let's see if this works first okay that looks like it's working so let's submit it um oh there we go accepted so it's the same idea really uh the only thing now that we're doing is using the index number as the array value here inside of our binary index tree because if we used the number itself well that wouldn't work because we could have negative numbers as well so um yeah same idea i believe this ends up becoming i actually think it's the same time complexity it's n log n or might be n log whatever the length of uh however many numbers we have is so that could be different and n lock m maybe all right well i'm gonna end it here thanks for watching my channel remember do not trust me i know nothing | Count of Smaller Numbers After Self | count-of-smaller-numbers-after-self | Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`.
**Example 1:**
**Input:** nums = \[5,2,6,1\]
**Output:** \[2,1,1,0\]
**Explanation:**
To the right of 5 there are **2** smaller elements (2 and 1).
To the right of 2 there is only **1** smaller element (1).
To the right of 6 there is **1** smaller element (1).
To the right of 1 there is **0** smaller element.
**Example 2:**
**Input:** nums = \[-1\]
**Output:** \[0\]
**Example 3:**
**Input:** nums = \[-1,-1\]
**Output:** \[0,0\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104` | null | Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set | Hard | 327,406,493,1482,2280 |
79 | all right so today we're going to be taking a look at the popular Le code problem word search and so what this problem is asking us to do is we're given an N byn grid of characters called board and a string word and so our goal is to return either true or false if word exists in the grid so as the name suggests we are searching for a word search now the constraints that we're given for this problem is the word has to be constructed from letters of sequentially adjacent cells so the adjacent cells are either horizontally or vertically neighboring and the same letter cell may not be used more than once so in the context of this problem how does this all play out well let's take a look down here at our example as you can see this is our board and we're given a string word AB BC c e d right here and the board is constructed like so it is a 2d array or a matrix and so we're essentially searching for this word in this board but exact actly how does this work now I'm going to be upfront with you there isn't really an efficient way to solve this problem in fact the only way to really solve a problem like this is to explore every single possibility in our board to see if we can actually find the word that we're looking for and so when you're dealing with a problem that has exhaustive search that's known as a backtracking problem we're essentially checking all possibilities within our board all right so let's take a look at how something like this would work so with backtracking problems we start from the ground up so in this case we're going to start with the first letter we're going to look for a so let's just say for example that we start at e so we start at e that's not a so then we look at an adjacent cell so let's say we look at C that's not an A Move Over Look at B that's not a and then finally we find an A so now that we found the first letter of the word that we're looking for we need to start exploring neighboring cells so we can find the next letter in this case b so remember when we explore neighboring cells we look horizontally or vertically so in this case we would look up left down and then finally right which is B which is the next character that we're looking for and then the backtracking process continues so we look up nothing there we can't look left because remember the same letter cell may not be used more than once also there's really no point in looking at a because we know it's already in our word we've already found it so we can effectively just ignore this from our search then we can look down at F which is not in our word and then finally we will look at C right here which is the next character we're looking for in our word and that's pretty much how this process works and we do that until we've essentially exhausted all neighboring cells eventually finding each letter in our word until we're finally able to construct the final word itself and so that's an overview of how we're going to solve this problem one last thing before we jump into the code the way we're going to solve this problem is with backtracking but more specifically we're going to be leveraging death for search or DFS death for search works perfectly with backtracking because we're still going to be looking at all adjacent cells it just offers us a structured and systematic exploration of the Matrix DFS allows us to essentially prune redundant paths and terminate exploration when we don't find the next letter in our word and generally speaking in coding interviews when you implement backtracking does make use of DFS so we can kill two birds with one stone by learning about backtracking but then also learning about the concept of depth ver search and how it applies to matrices so without further Ado let's jump in the code all right so the first thing I like to do for these backtracking type problems is declare constants for the length and width so in this case we can just call it rows and calls and this will just be the length of the board and length of board zero and I'm putting it in line like this because this will map to rows and this will map to calls this just makes it easier so when we reference rows and calls in our for Loop we don't have to actually write out length boards or length boards zero essentially it just makes our life easier and then remember we can't be using the same letter twice so we need a way to keep track of that the easiest way is by implementing a set now if you don't know what a set is kind of like a hashmap but it weeds out any duplicates so that out of the way now we can write our DFS function our def for search so another thing I like doing with these backtracking problems is writing a nested DFS helper function so we can start out like this we have our DFS function which will take our index of I and J and then we will include K which is the current index of the letter that we're looking at or the character that we're looking at so the reason we pass these indexes in is because we want to be able to look at adjacent cells and so the first thing we have to do in our DFS function is check if the indices that we're looking at are within bounds and the current Cell matches the word character and so we can start that off by saying if not 0 less than or equal to I less than rows or not zero less than or equal to J less than calls or board i j does not equal word K or i j inv visited now I know this may look confusing but the first part of this checks to see if we are out of bounds or if the current character that we're looking at in the board is equal to the current character in our word that we're trying to match or if we've already visited a particular character if any of these are true then we simply just return false this helps us break out of a d FS search early if we end up going in a direction that we don't want to in other words if we are either exploring out of bounds or if we're looking at a character that is not the one that we currently need or if we're currently looking at a character that's not in our word string or if we've already visited that character so having an early check like this is important next thing we need to do is have a case in the event that the entire word is found if this happens then we can return true now the thing to note here is that K will always keep track of the current index of the character we're looking at in our word string so if we reach the end of that string so length word minus one because strings are zero index like an array so once we reach the end of that word if K is equal to that and that means we've effectively explored all the paths in our board and have found the word that we're looking for now again we put this at the top because we want it to be one of the early checks we make before we start actually traversing and doing a bunch of work so this helps cut back on runtime so the next thing we want to do is add the current position to our visited set so that'll look like this visited. add and then we will add the coordinates in our Matrix of I and J as a tuple to our visited set so this just helps us keep track of the current coordinate or position that we're visiting so when it comes to DFS functions these are all pretty standard checks you always want to make sure that you're not going out of bounds or something isn't wrong we also want to have a positive exit condition in the event that we meet all of our criteria and then we also want to start by adding whatever it is in this case our position to our visited set to make sure that we aren't checking characters we've already looked at so once all this is out of the way is when we can actually start doing the exploring and so this is where we'll be recursing with our DFS so first we'll declare variable results and then we will start declaring multiple instances of our DFS function but with different inputs this will help us Traverse in the different adjacent directions so that'll look like this we'll start with our DFS and then we can say for this one I + 1 say for this one I + 1 say for this one I + 1 J K +1 now we have to increment K J K +1 now we have to increment K J K +1 now we have to increment K because every time we search we're potentially looking at another letter so we have to make sure that K is being tracked properly for our word but in this variation we're just advancing the I index plus one leaving the J alone and then performing our check which will then run all this code again and then check all adjacent cells now this isn't the only check we make we actually have to do three more cuz remember we have to check in all four directions horizontally and vertically and so these will all look very similar to each other so let me just copy and paste them all right so this is the end result of our exploration as you can see we have the DFS function declared four times here and it checks in each cardinal direction seems really repetitive but this is how we do it but it's not over just yet we also need to make sure we remove the current position from our visited set when we backtrack the general rule is whenever you add something to the visited set you also want to remove it after doing your exploration this is just consider general clean up so that will just look like visited. remove and then we'll just remove the tupple i j or the coordinate I and J after everything is said and done we will finally return our results so this is pretty much the DFS function for this problem so now the next order of business is to iterate through each cell to start the DFS exploration so we can simply do that with a nested Loop which will look like this we can say for I in range of rows and then for J in range calls if DFS i j z return true essentially this nested for Loop allows us to look at every single coordinate within our board and then run the DFS on it and so by doing this we're exhausting every possible Direction and every possible combination of letters to eventually find our final word like I said this problem isn't very efficient because we're going to be exploring every single possible combination of words within our board and then if the DFS returns true then we of course return true here which means that our word was found within our board and then finally we have to have the case in which we don't find anything or we don't find the word that we're looking for which in that case we just return false and so that is the code solution for the word search problem now before I end this video I of course want to talk about the runtime of this problem so as I've mentioned before the runtime for this solution isn't going to be very efficient but in either case let's take a look we know that we're going to be dealing with a board the size of M * n dealing with a board the size of M * n dealing with a board the size of M * n which is the length and width of our board then we also have another consideration to make as you can see we have DFS running in the four directions to look at the adjacent cells of every coordinate that we take a look at in our board so since we're going to be looking in four directions we can start with four and that will be to the power of the length of our word now why is this because in the worst case the length of the call stack for our DFS recursion is going to be the length of the word and we can shorten this by saying instead of length word we can just say n so the overall runtime is O of n * n * 4 to the overall runtime is O of n * n * 4 to the overall runtime is O of n * n * 4 to the n which covers the size of our board that we're going to be traversing Through Time 4 because this is the four directions we're going to be exploring to the nth which n in this case is just the length of our word so adding this all together this is what we get again like I said not a very efficient runtime but it is what it is in any case I hope you guys learned a lot hope you learned a lot about backtracking and DFS and I really hope you can internalize this sort of template that I use for solving backtracking problems because once you identify that you're working with a backtracking problem you can pretty much just plug and play this template that I have remember starting with defining the length and width of the search space that you're working with and then declaring some sort of visited set and then having an internal DFS helper function which follows us criteria of checking for out of bounds declaring an exit condition adding to visited and our case checking in the four different directions removing from visited and then finally returning the results and then after which you will apply that DFS to every coordinate in the search space that you're working with in your Matrix so you have to have a nested Loop and then if DFS with just default inputs and then either return true or false so again hopefully this all made sense and I hope you guys learned a lot and I'll see you in the next one | Word Search | word-search | Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_.
The word can 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.
**Example 1:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED "
**Output:** true
**Example 2:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE "
**Output:** true
**Example 3:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB "
**Output:** false
**Constraints:**
* `m == board.length`
* `n = board[i].length`
* `1 <= m, n <= 6`
* `1 <= word.length <= 15`
* `board` and `word` consists of only lowercase and uppercase English letters.
**Follow up:** Could you use search pruning to make your solution faster with a larger `board`? | null | Array,Backtracking,Matrix | Medium | 212 |
1,967 | welcome back for another video we are going to do another decor question the question is number of strings that appear as substrings in word given a array of strings patterns and a string word return the number of strings in patterns that exist as a substring in word a substring is a contiguous sequence of characters within a string example one patterns is a abc bc d word is abc the output is 3 explanation a appears as a substring in abc bc appears as a substring in abc d does not appear as a substring in abc three of the strings in patterns appear as a substring in word example two patterns is a b c word is a b the output is two explanation a appears as a substring in a b c does not appear as a substring in a b two of the strings in patterns appear as a substring in word example 3 patterns is a word is a b the output is free explanation each of the patterns appears as a substring in word a b let's work for the code we first initialized a variable count at zero we iterate through the strings patterns if a pattern appears as a substring in word increment count by one finally return count time complexity is o n space complexity is o1 the solution works | Number of Strings That Appear as Substrings in Word | longest-substring-of-all-vowels-in-order | Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc "
**Output:** 3
**Explanation:**
- "a " appears as a substring in "abc ".
- "abc " appears as a substring in "abc ".
- "bc " appears as a substring in "abc ".
- "d " does not appear as a substring in "abc ".
3 of the strings in patterns appear as a substring in word.
**Example 2:**
**Input:** patterns = \[ "a ", "b ", "c "\], word = "aaaaabbbbb "
**Output:** 2
**Explanation:**
- "a " appears as a substring in "aaaaabbbbb ".
- "b " appears as a substring in "aaaaabbbbb ".
- "c " does not appear as a substring in "aaaaabbbbb ".
2 of the strings in patterns appear as a substring in word.
**Example 3:**
**Input:** patterns = \[ "a ", "a ", "a "\], word = "ab "
**Output:** 3
**Explanation:** Each of the patterns appears as a substring in word "ab ".
**Constraints:**
* `1 <= patterns.length <= 100`
* `1 <= patterns[i].length <= 100`
* `1 <= word.length <= 100`
* `patterns[i]` and `word` consist of lowercase English letters. | Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring. | String,Sliding Window | Medium | 2186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.