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
939
Hello Hi Everyone Should Specifically To ISBT Solving All This Question So Question Is Medium Will Keep Software Setup Points In Explain Demand To Know Area Of Rectangle From This Point Side First To Egg White To This Sex So 200 Report For Clarity Aa Now Return To This Point And Nandgaon 209 Disawar Looks Pride Soft Question Subject * Peeth Is Point Radhe Points And * Peeth Is Point Radhe Points And * Peeth Is Point Radhe Points And Form In West Bengal And Neetu Finally Minimum Video 200 First Let's See Who Can Us Vital One And A Hundred Point Of Time 121 Jaaye Because Kunwar Deposit Amazon Just Checking Then X Is Too -DO CHANNELS WHICH IS PABLE TO A Checking Then X Is Too -DO CHANNELS WHICH IS PABLE TO A Checking Then X Is Too -DO CHANNELS WHICH IS PABLE TO A PERSON LIKE THIS 200 Haunted Point And Comparing With 120 Two Point Note Channel How Bigg Boss Exit Considered Effective 162 Want To Hear What Is Equal To How To Slow Typing That Is Stage This Point Sequence Back X One Is Not Able To Travel Expense For Decades Back To In One Stop This Point To Point Equipped To 100MB Grade To Points On Winning 252 Points Richa Meeting Is Tightening A How To Find What You Need To Check Them Now Half Is Here 130 x21 And It Is One Boy To 210 How You Will Check The Terrorist Attack In The Final Tangled Yasmin To Find The Area Of And Can Also Check Cafeteria Is The Meaning Of The Name Of The Ki Swapn Next Code Year Not Them Bihar Board Exam SSC Exams Page Diye Contact Arrest him Punjabi Ki Hey Called S Letter 808 Pimple or Pimple that is now illegal Novotel Lulia Venter Sides Uditya Oil and Gallery Check Words So Hi Ajay Makan Rafiganj Pass Note Country On 110 Ajay Ko Questions Page 20 The crow says with the help of which it is quiet A bit different alive and not for support now half again ho quizzes accent news website hua hai but electronic name and password kya 249 hai vilayati ghrit are just opposite 56001 par tiddi one point ki exit deposit rates for edification a time 49 rumor setting on map Hai Will Support You Deposit 5000 Phase Points And Flu And Attraction In That And I Need To Run Bangalore Hai To First Look Then Resilient Suraj Point And The Second Lootere Compare 50% Point Kar Do Second Lootere Compare 50% Point Kar Do Hai Anti-Aging Effect Electronics Let's Hai Anti-Aging Effect Electronics Let's Hai Anti-Aging Effect Electronics Let's Get Quick Answers Ko Tight Naav word this is mild mein live call points hello hi hain next first that they replace that this lineage Google two points on hello hi everyone hand e was feeling this point came from what happened my channel to singh for finding X2 and fight you Song Pimpri Ki And Commissioner Lucknow Bluetooth Chakli First Condition Award For Elephant Was A Factual Inaccuracy 2625 12222 Is Vansh Wish Karne Se Aap Is Part We Should Be Two Point Noted And Avoid 209 Meter Final Two Doctor Ne Twitter The Amazing Spider -Man Lottery Accident -Man Lottery Accident -Man Lottery Accident Specification Cutting 0 Now Half Vaastu And They Say Pilot Has Happened Rathore Cassette And Stuart Now In Half Hour Size By Two And Salary For A Day Qualification Satisfied Dr. Scheme Difficult Dangal 9 News Mithlesh Now Just Point In Finding Faults In You Loot That Area ad paltu main document hua tha main to ya hi lootna loot 4000 triangle duty loot value of section - of section - of section - and Stuart 's multiply by apps lock value of ab se aap to aap dry mantra - mike hai ab se aap to aap dry mantra - mike hai ab se aap to aap dry mantra - mike hai thanks naav hai aur 10 min rate andheriya Returning to this to see this condition this peer vitamin C situation more equal to key spelling and air max life english turn on the light this variety it is not change Stephanie Swift won't keep soil returns that half hour jam i college status and electronic relationship acorps previous Song Aisa But That Airports Soldier And Thanks Watching Do
Minimum Area Rectangle
valid-permutations-for-di-sequence
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[2,2\]\] **Output:** 4 **Example 2:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\] **Output:** 2 **Constraints:** * `1 <= points.length <= 500` * `points[i].length == 2` * `0 <= xi, yi <= 4 * 104` * All the given points are **unique**.
null
Dynamic Programming
Hard
null
131
hello everyone welcome back here is my Amazon and today we will try to solve one of the top 100 likes this problem and maybe this one polynomial partitioning medium so I haven't tried it yet so I will try to solve it in Python and what it's about so it's involving palindromes and backtracking so it sounds quite interesting so let's dive together so here is the problem we are facing today we have a string and we need to partition it such that every substring of the partition is polynomial so sounds interesting so let's take a look at examples so for example a b for string like a b one way to partition it is to uh have palindrome a b another way is a and b and this gives us two possible outputs for our function so keep in mind though A Single Character is also plunder so our string length can be anywhere between 1 and 16. and it contains only lower case English characters so how do we approach this so our trusted friend backtracking comes to rescue so first we need to help our function to check if a string is a polynomial so let's call it's a palindrome and this function simply checks if the string is equal to its reverse so next let's go to our backtracking function and which we will call backtrack to simplify it so this function will be the Workhorse of our code and it will explore every possible partition and only keep it if it's a palindrome so note how we are calling backtrack uh recursively So within itself so it starts from the beginning of the string and moves towards the end and each time checking if the current partition is a palindrome if it is we continue with our remaining string so now you might be wondering what happened when we reach the end of the string so that's our best case if the start index equal the end we have found a valid palindrome and partition and we add it to our results list so lastly we make an initial call to backtrack with the start as 0 and as the length of the string and empty list so we then reuse and return the result which we will contain all possible palindrome partition we have found so let's implement it so Define is palindrome checks drink and return check yeah check ring equals check string reverse okay we have one function and second will be backtrack start and temporal list and if start equals and then result append uh temporal list and 4 I in range start to end if is palindrome s starts I plus 1 so part of the string a backtrack I plus 1 and temp lists Plus yeah uh s start yeah and result will be RI and here we call back backtrack yeah zero Lan as well all right and we return result so as simple as this so let's run it and see if it's working I hope it will work so yeah it's working so now let's run into score and since cases as well so I'm running it and it's calculating and yeah we have successfully solve it uh so we beat 49 with respect to run time and 26 with respect to memory so yeah all good and our record works perfectly and you can now partition any string into palindrome in Python using backtracking and yeah remember backtracking may seem a daunting but with a practice it'll become an incredible powerful tool in your coding Arsenal and yeah thanks for joining me on this python Journey today uh if you enjoyed this video be sure to smash that like button and hit subscribe for more algorithm breakdowns and remember cutting isn't just about problem solving it's about embracing the journey and having fun so see you in the next one happy coding and keep practicing
Palindrome Partitioning
palindrome-partitioning
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`. **Example 1:** **Input:** s = "aab" **Output:** \[\["a","a","b"\],\["aa","b"\]\] **Example 2:** **Input:** s = "a" **Output:** \[\["a"\]\] **Constraints:** * `1 <= s.length <= 16` * `s` contains only lowercase English letters.
null
String,Dynamic Programming,Backtracking
Medium
132,1871
1,848
hello guys myself swapnil I am now telling you an answer of minimum distance to the Target element uh actually in this question they are asking their question that is a q1 and integer Arena during texture means zero to n and two integers Target and start find an index I such that Norms of I equal to G Target means Whenever there is a nums of I equal to Target then we have to check the value of absolute of I minus 13 is minimized remains we have to make something program for actually decreasing order of the absolute values of that uh oriented uh numbers from the numbers of I equal to Target note that absolute of X is the absolute value of x and now I will take here the variable a and I will bound this value with a number and of the numbers nums dot length because I don't know the length actually that will happen here so I will take it as length of numbers and then I will check the values of norms of I that is equal to Target or not uh I will here use various methods that we can check it have either sorting method sorting algorithm bubble sort algorithm or any other sorting algorithm but I will take it easy as easy and uh fine for you for into I equal to 0 I is less than numbers of dot length start length and I plus this now here we have to check that it is equal to Target or not so if equals I equal to Target now we have checked here and we have to put this value in the array a of k something K means the index value of the a which is increasing here so a of k equal to absolute ABS is the function for absolute values I minus start and uh below K plus we have not initialized the K well variable so I need a k equal to zero now I know the uh actually the length of a various values are present but other than means num slot length minus okay are the zero ones zero elements there so I have to minimize the length of E I will make here other variable you can take it as a simple method and to be equal to new in which is as a length k says for a in J equal to 0 then semicolon J plus and here B of say equal to a of same here all the values of a of J are there which are obtained from this a of k equal to Max dot absolute now we have to we need the value which is minimum so I will use here quick sort algorithm I will obtain the value which is minimized here for that uh I will directly return the value return uh not we firstly I will make here this sorted so arrays dot sort B and now return uh B of 0 means zero position is the as The Salted B array is a ascending or so the minimized value is at the zeroth index so it is now return now we have to check the we are our code is running smoothly or not or any other time complexity is present here so here uh I have taken here the a which is not there a and it is a integer variable so integer data type so here we have to check it again speed up and now you can check here my answer is right and it is accepted by this and uh I we have to check this how much our answer is simplified and what is the time complexity of our question and uh you can check this out our time complexity will be uh here over FN and uh here o of n to window oven and uh here also uh n into log N means here all over it will be that much not optimized but you can optimize it and use it we got the answer but it will not be a good that much but you can take it is thank you for watching video now bye let's meet in another video thank you for watching
Minimum Distance to the Target Element
sum-of-unique-elements
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], target = 5, start = 3 **Output:** 1 **Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1. **Example 2:** **Input:** nums = \[1\], target = 1, start = 0 **Output:** 0 **Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0. **Example 3:** **Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0 **Output:** 0 **Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0. **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * `0 <= start < nums.length` * `target` is in `nums`.
Use a dictionary to count the frequency of each number.
Array,Hash Table,Counting
Easy
null
416
Hello hello guys welcome back to back door sign in this video you will see the partition total subsidy less problem which from list number 410 six pieces variation from 90 problem and observation of subset same problem solve latest problem statement in this problem Thursday positive entries Into two subscribe so let's fuel Video give request divided into two subscribe 14521 phase subscribe thanks for the second set in this case which can be divided into two subject truth that is the element directly subscribe for Girls Problem Video subscribe The Channel and subscribe the Problem 9000 problem give what is the city of the giver items and items which can be exploited here also can't to the second item and they can export and some features of them have to choices no how is this problem from bluetooth of problem in this Case which gives a similar to this website and they also give very fair give the subscribe to a divided into two parts subscribe to the Page if you liked The Video then Bluetooth XO Kushwah Recall and Avoiding Hadith 212 Beautiful Probably Intelligent Subscribe Dash Lloyd Nuvve Busy Number To The Bana The Se Re Is Remedy And Subscribe Now To Receive New Updates Reviews And The Lancet And To-Do List 1.251 1.251 1.251 Not Included In This World And Will Obviously * * * Fennel Year including S1 means explosion Obviously * * * Fennel Year including S1 means explosion Obviously * * * Fennel Year including S1 means explosion from S2 and this including element in a student will automatically get excluded from test one ok so you can see the challenges of 120 acid can either go to one and hit can go to face to go into to make it will Not go to one 16 same go for this item to it can go to say taste one should not go to states one and so all software systems are no items are this element 72825 without person problem into the only for this is the property of this problem Problem hai ki water to aap sarveshwar this problem ipsum of all the elements involved in which can never find the equation partition because all number sir interior addition u if you are having the value of x ok so let's you have to subscribe interview welcome to you All Elements For All Elements Of The Giver Subscribe Now You Can Find The Giver subscribe and subscribe the Channel subscribe Here OK Advised That Deposits Committee Ward No. 29 Video Value 290 Welcomes Exam Decimal Value Laxative In More 100 This Is Not Valid For This Andher Can Be given but when you love someone will always give some of all elements which can be possibly divided into two subscribe thank you can really possible subscribe not possibly divided into two subscribe that hit can be possible to be submissive in the east and not Possible in the second How is this possible in the third How is it not possible OK so they can see What is the name of the elements of Delhi will definitely not possible to find competition Other elements is it and not possible to partition in giving very important observations Subscribe One to three four elements and where does but you will win more than 272 seats and divided into two subscribe that f-18 can go to students can not f-18 can go to students can not f-18 can go to students can not go to both in only one instance of that element and so you consider to form subsidies WWE Only for this subscribe will also have the same quantity 9.2 and subscribe the subscribe to quantity 9.2 and subscribe the subscribe to quantity 9.2 and subscribe the subscribe to be lit is possible to give you can not be possible as possible to subscribe mode to switch number of drops of elements will be of equal sum So how to find the giver Set the giver can be formed from subscribe and subscribe the two and check the value of all elements in the world will not possible to avoid to give will give you some problem as possible and you will return true saying it is possible For Politicians Not Possible Problem Border Apni Previous Video And Drink For Admission In The Discussion Will Show You Can Say That Some Time Complexity Will Be The Same He Subscribe Special Person To The Table Of The Amazon Approach Will Also Be Used Only Difference Is The Some Of All Elements And Values ​​Will Not Be Possible From Amazon - 110 Values ​​Will Not Be Possible From Amazon - 110 Values ​​Will Not Be Possible From Amazon - 110 Subscribe To Determine Where You Can Benefit From subscribe And subscribe The Amazing Already Platform China Position Will Simply Return Value Otherwise After Calculating Will Be To Get Into The Position Are You Can See But They Have Taken Or Symbol What Is This Is The First Year Including Element * First Year Including Element * First Year Including Element * subscribe Video then subscribe to the Page if you liked The Video then subscribe to subscribe Qualities That Will Return For Service Will Form A Debatable Just Like A Kid In 10m Problem And Will Be Traveling For The First Second Third Fourth Edition Services Problem Will Only Be Adding This Third Edition Of Which Will Check Effigy Of You Are Able To Form A Sect Which Is Having Some Evidence Of Acidity Problem Comment Subscribe Like Share And Subscribe Our Channel subscribe nine
Partition Equal Subset Sum
partition-equal-subset-sum
Given an integer array `nums`, return `true` _if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,5,11,5\] **Output:** true **Explanation:** The array can be partitioned as \[1, 5, 5\] and \[11\]. **Example 2:** **Input:** nums = \[1,2,3,5\] **Output:** false **Explanation:** The array cannot be partitioned into equal sum subsets. **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 100`
null
Array,Dynamic Programming
Medium
698,2108,2135,2162
956
hi everyone in today challenge we are going to solve this problem the problem name is tallestly billboard and the problem number is nine five six well it is as usual first of all we are going to clearly understand this problem statement after that we are going to move to the logic part we are going to see how we can solve this problem what is the logic to solve this problem and after that we are going to move to the implementation part we are going to implement our loads you can see plus Java and Python programming language fine guys now let's see what this problem is right the problem says you are installing a billboard and want it to have the largest height okay so we are going to install a billboard file and the billboard will have to steal supports one on each side each still support must be an equal height so they have told that the billboard is going to have two steel support so let's say this is the first and this is a second right now this should have equal height that's right you're given a collection of roads that can be built for example if you have a road of lens one two and three you can weld them together to make a support of lenses so collection of Roads is nothing more you can say array floor set same thing right carry a fruit atmosphere clearly mentioned that what is the input is about array where the value is a roadside so we can bend them together to make a steel load and it's right okay now written the largest possible height of your billboard installation if you cannot support the billboard rate in zero so now guys what we have to do we have to return the largest possible height of our we can say billboard installation right so simple thing guys uh the first thing they have mentioned that they should have equal height right here you can see only each steel support must be an equal height so they should have equal height so we have to make a steel by building these roads such that they will have a Collide right and the second thing is mathematic acid we can bend them together if our roadside will look like one two three four five six so if you can belt them three and five and six one two and four on the one side and three five and six on the ones that means we can take any number on the left and right side right so that they have mentioned like the third thing is that you don't need to use all the loads you can leave some load as well right if you are not able to make equal so but you have to make equal you can leave some road as well right and the fourth thing is nothing but if we could not able to make a equal these roads right if we could not able to make a tooth still equal to still support equal by using a roads then we are going to return nothing but zero only right that means the height is 0 means it we could not able to install it right I hope it makes sense so let's understand this with examples so that you can have better understanding I know by the statement you would not have a pattern idea so let's see the example one here we have you can see we have given a collection of floors one two three and six right now what we are going to do we are going to say okay so I want to make a two City support item so first is initially empty second is initially empty right so let's say I uh put one here five and I put two here so will this make sense if I do this so they are not same right we put three here or let's say three or six here so still they are notes this is a fourth line This is a eight line right but what if we can say we are putting one here two here three x so length six and we simply put six four here so you guys can see that both steel support now gonna have a same length right so here also six length hair associate equal to six only right so we are able to make the steel support length equal to six right I hope it makes sense right now let's move to the next example so that you can have a more better understanding we have this array one two three four five six simple thing four five six now this is the both still supported trying to understand in this way we are putting one here and let's see two here three here for no it's not gonna work so what they have done is nothing but you can see in a line two three five and four six on the one side two three five four six on the one side so as I have already told you that we can leave some good so we have removed this one we haven't taken one note right so two three five is nothing but you can see ten six four is also ten right so we are going to say nothing but the largest height we can get of a billboard installation that's number 10 right you can see both the lengths are equal here and we have used all the uh not all the land but we have used only these numbers which are present in our road sorry right so that means we can use any combination but still road is not gonna be these two uh supports is not gonna be equal right so what we can say if it is not the case so we are going to return nothing but zero only right I hope it makes sense the highest uh length of the your billboard installation light which will be nothing but the length of the any of the supports right at the length of this of course only this support but these two supports should be equal so we can take any length of any support right and let's move to the logic part see how we can solve this problem right we haven't understood the problem statement so that was not a hard thing but yeah losing is going to be really hard not brilliant we are going to solve in a just you can see guys if you have understanding of recursion part right then you can easily solve it right we are going to use nothing but dynamic programming nothing else and why it is so we will see it later but you should have a better understanding of recursion how it to work if you don't have don't worry let's try to understand for me right maybe you can get a better understanding by this particular problem right so how we are going to use a DP here see guys let's take a first example in one two three and six right so initially what we will say okay we are starting from zero index remember we are starting from 0 and x and I will say I have zero I'm currently on zero Index right and I have a differences as to zero think about what is difference we will discuss it later but think about I am at zero index and I have a difference with zero right I can take it in a faster route right so I can say I will reach to the first index and I have taken so my defense is going to be nothing but one right so if I see nothing but the second possibility is here that I can leave it I don't want to take it or I am taking it but taking for another road for other support right so there are two supports right this is the first one this is the second one right so we have to make both them both the equal so it may be the case that I am taking it for the second support right I have take it for this one I take it on the left side but here so now here I reached to the one index we are going to remove to the next index only but there are three possibilities to move to the next index either you can take it for the left supports either you can take it for the right support either you cannot take it you either you're not taking it right we are moving directly to the next node you don't want to take it right if we have taken it right here also you have uh three options either you can you move to the second Index right that is for sure you will move to the second index and then you want to take it this second right length of two okay I want to take it so I will say 1 plus 2 is nothing but going to equal to two or not one plus two is going to be equal to three other I want to take now this for the right side right so I will say subtract 1 minus 2 which is gonna be equal to minus one either I don't want to take it so I will say 2 comma one only right so what this indicating that on the second index you have difference one on the second index you have different minus one on the div second index you have difference three is that making a sense right just tell me if you are getting a little node because I believe that you know the recursion however but still if you're not getting so that means we are taking each and every possibilities on each Index right so we have currently three possible so we'll do the same things for two comma three as well so either I will take it or not take it right or I will take it for the left side and right side we have three possibilities so let me make it above so for here either I want I'll move to the four index that will make sure right we are going to move the fourth index what I am going to do I'm going to say either I want uh I am going to take it for the left view so then I have to add 6 so 6 plus 6 12 I don't I want to take it for right mean so I'm going to say 4 comma 0 I don't want to take it only right so 4 comma 6 only right now four comma six I will not able to move anywhere right so length is overnight so it's gonna write as something it's also going to return something it's also going right now we have drawn the recursions we are going to know draft for the rest of the parts because we know that the answer is not going to be there because uh this is example but you have to draw all each and every possibilities but here we are going to get answer here only right so what I'm going to do now whenever we go to the we can say with last of the hour because array or we can say last index so here you can see fourth is the last intersect now we are going to move to the uh we can say for the next but fourth index does not exist right you can see the length was only four so we can have only three Index right uh till three index so once we reach to four we call the same if you are having a difference anything node zero then we are going to return nothing many minus one or you can say uh the least thing right into minimum or we can say floating rate nothing uh but you can say anything right but note uh and we can see the largest negative value in Python you can use a float Infinity minus infinity in C plus you can use inter mil in Java you can use integer.min value right integer.min value right integer.min value right so you can return anything but if you're getting a value 0 that indicate that override so that what that tells that tell you that yeah we can make uh our that particular thing we can say our two supports uh steel or equal right so this is going to tell us 0 right so that means we can make a support speed equal to U now and this 4 comma 6 is going to nothing but internal as that no negative number list uh largest negative number of area so whenever you're getting a zero that means you can able to make a support still equal right so how we are going to get a length now because we have to written the length right so we're going to say whenever we are taking we are going to add that particular length right now come to the Top Again starting area so we are going to change the color see guys I have taken a one so I'm gonna add two here so 2 plus 2 is 4. only now I'm going to take a two ways so I have to add here also one plus two is negative three right so from one I have taken two as well on the right side but uh here we are subtracting it doesn't matter but I have taken it right so we are going to say three now come to this side from on the side second index we have taken right we have taken the three so three plus three is nothing but six right here it's gonna be three only we have to know to add it yeah so always whenever you're getting a zero you're gonna return 12 by 2 and here if you will notice we are also getting somewhere zero here as well right so that means there was six so that means we can also make a support of three length as well right but we are going to return the highest one that's why we chose it well we keep exploring so we are going to use take a maximum of all these and we are going to return divided by that so 6 and by the maximum is going to be 12 so 12 by 2 is nothing but 6. so our answer is going to be 6. I have you haven't understood this logic part so that was the simple we can say the question and now we are going to see how it's gonna work right it's always going to return a tid if you will right now go to the we can say browser and start to implementing this will go later 2080 because every time you have three possibilities right so each time three possibilities the length of let's say the array is length is n so n is two or three I hope it makes sense so this is going to be always three times four and I guess right so this is always going to tell you but how we can memorize it by taking the index of by taking this particular index and difference right we can see you can see this pair can be repeat again and again right so we are going to use a memorization on this particular we can see key and index and after that we're going to return if we have already explored that particular part right so that's a particular thing we are going to do we are just going to memorize it and this will become a DP dynamic programming and we are gonna solve our example with this problem right so let's move to the implementation and let's see how we can use this application and how we can memorize it right now so guys what I'm gonna do is I'm gonna go to this price let's go okay so let's increase the size first of all not 175 so we have 1.5 so we have 1.5 so we have 1.5 so first of all I am with the pythonizer so let me tell you first of all by making a function different soul here what we are going to do we are going to say I don't have first of all index okay and then it's gonna have nothing but uh difference right and here we can say if our index is equal to length of this load set so let's calculate length here as well that is equal to length of Roads right if we come up come to the last of the our area that's last index so we are going to say check it if difference is zero so what you're going to do you're gonna return nothing what you can say uh zero right if difference is not zero this is floating field see I'm doing like this you have to understand you but you can use a conditional operator which is going to work here right simplify like let me show you also how see here you can do like this uh difference is equal to zero if it is the case then what you're going to do you're gonna write a zero else your generator and I have used them to press here what I have to do here right I would make sense so you can do like this way as well if just try it I will I'm thinking that it will work right but let's see right now after that what we are going to do must be uh we are at node we can see we are not at the last index we are in between so we have three possibilities as we have seen like so we have three possibilities either we can take it on the left side for left support for right support for We Are Not Gonna Take It so we can say return maximum we are going to return a maximum out of these right so first Maximum is going to make your soul index plus one always index is going to be increasing you are going to take it for the left side so you are going to say difference Plus rhodo roads of that particular index so this is going to be natural we are going to add for the left side so that's why we are adding it plus roots of index so what is this plus we have already seen right every time we are adding it if we are adding for the left side or right side we are going to add that particular value also so now let's add on the right support So wrote we have support we have to mine subtract this and this means we are adding for the right support then we are going to add this right after that the last option we are not going to take it so we can say index plus one difference is going to remain same and we are not also going to add this load index so we are not taking it right so this is the basically we are going to do after that we are going to call this function for 0 we are starting with 0 index we are having initial difference 0 and after that we are going divided by 2 right before returning it so let's run this code let's see what is for the final note right and I hope yes it should work but testing the solve is not defined yeah it's not defined because we have used a different now let's run this code hopefully it should work we don't want to see any more error you can see guys all the rest is passed right but all right first of all let's check this out it should work right what happened to it let's see it's not working all right so I think we should do like this if it's not working then try to use the workplace only I thought it should work right will try to use it in this way all right so let's comment this we are not going to waste much time on this let's run this code right so guys you can see all the risks are working right currently but this is a brute for supports it's not going to work for the rest case if I show you by running the test cases so you can see we are going to get a tle definitely we are going to get let's see just give a dld you can see guys it's uh it could not able to pass the seven seventh test case right so what we are going to do is we are going to use a memorization and in Python we are going to use a function to Red function s function tools what this is meaning is that they would need to listen use cachet here we are going to use this particular thing and let's run this code and see what this is the final note okay uh first of all let me go to solution dot solution we can say submission let's copy this test cases as well I'm just doing for this particular one for the next program no problem problems we are not gonna do this we are going to actually do the implementation right for this I want to just show you how this working right now code four test case so what I'm going to do I'm going to add this one and the lesson on this one it should pass right so let's check it so you guys can see the four test case has about pass so we are going to submit this one so what this function tools tells it is nothing but a decorator right if you don't need to use any we can say hashing or anything it by default gonna do the tax right you're gonna see if we have already passed this parameter in this function so directly written from the cache don't be uh we can say don't uh try to all this function again right so they see nothing but one way of using a memorization in Python but in C plus Java we don't have this I guess so we are going to use a manually right so I'm with the c plus foreign so let's define this function as right so I'm going to do nothing but probably not public we can say directly and so it's going to take a first of all the index then you can say in here we can see difference then we press n then we can say Vector flow set vector in it has loads and the last thing about this map right so let's just copy this particular we don't want to write again and again right okay and we have to use up what happened to it again right so guys we are going to use a password right now how much this is done we are going to do nothing but we are going to check first of all one condition if that particular we can say this uh index and difference is already we have explored it that means DP Dot find this particular thing is not equal to n right node equal to epido n so what I can say written deeply uh dot uh this is Po idx formative assets if it is already we have exploded so return directly this but if it is not the case we have to return if difference is equal to 0 therefore again try this right difference is what you're gonna do you're gonna say written uh integer mean right but if index is not equal to n then what you are going to do we are going to say uh written the maximum right written maximum of that particular index and comma n comma Rhodes comma DP right so here we are going to add this particular loads of idx so this is for the left support same thing we are going to do for light support as well so let's copy this thing the only thing which we are going to change is nothing but we're going to subtract it right nothing else we are going to do else subtract it okay and here for the last one we are not going to take it right we are just saying that what happened right so now what we are going to do I don't know all right so we are going to say soul here if we don't want to take it we will move to the next index but difference is going to remain same n is going to be same and load CCM DPS right so when this is done we are going to say this but this will also give an error because Max function don't take three argument you have to use inside also Max function right now we can simply do this thing but it still we haven't memorized it so we can say store in somewhere right so we can say DPO idx and difference stored in this and after the return this only right and DPO idx common difference right let's run this code and I hope it should not give any error we don't want to see but we get it right road slowly it's not a Java it's C plus so we have to use the size finally now let's see whether it's where to find or not pass you can see guys for the all the risk is passulated to submit this code as the right so that means this conditional operator is working in C plus right but in Javas or in Python you are not working so we'll see it later right now so you can see it's successfully got submitted now let's move to the last programming language Java so in Java what we are going to do first of all let's take a length in 10 is equal to load slot length and then we are going to define a hash or map so let's define it at the top in map right once we have defined if we are going to find a function as well that function name is going to be nothing but equal to we can say soul computers sold and here we can say uh zero Nets zero difference currently length is n roles you have to pass nothing else you have to do right now because maybe are taking globally then we have to return divided by 2 right so you are going to return directly here as well fine now what I'm going to do I'm going to say fine here just Define one function public insole this function is going to take first of all index then in difference then in length then uh you're gonna say loads that's in index Plus like this and we can do this hey this is going to be always unique for each index and difference right so we are going to see if that keep if difficult contains K this t contain key right if it is contained and then we are going to return DP don't get foreign a heavier consists soul you have to implement index always replace plus load of that index means we are going to add that particular load on the left side then you are going to pass same n same roads and then you can add also rules of index it so this will happen for the left side same we are going to do for the right side and here just one thing we are going to do which in mathematical difference minus load of X means we are going to add for the right side after that we are going to say soul index plus 1 difference and loads note Rhodes and nodes right we don't want to take so when this is done we are going to add but here also we need to use a math dot Max because method Max don't take three argument right fine so we have done these things so here we are going to first opposite DP of code this particular key result then you can say return stately result right now let's see whether it's looking final note I hope it should work right but no always we are getting every time and difference is you cannot find a symbol what symbol you are not qualifying it okay sitting spelling I don't know what's happening do we have any more error let's see okay TP don't contain d what's happening type where you can see that right authorities pass here so let's try to submit this course and I hope it should also get submitted right comments in the comment section I'm always there to help you and if you learn something new in this video don't forget to hit the like button and subscribe my channel meet in the next video
Tallest Billboard
number-of-music-playlists
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`. Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`. **Example 1:** **Input:** rods = \[1,2,3,6\] **Output:** 6 **Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6. **Example 2:** **Input:** rods = \[1,2,3,4,5,6\] **Output:** 10 **Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10. **Example 3:** **Input:** rods = \[1,2\] **Output:** 0 **Explanation:** The billboard cannot be supported, so we return 0. **Constraints:** * `1 <= rods.length <= 20` * `1 <= rods[i] <= 1000` * `sum(rods[i]) <= 5000`
null
Math,Dynamic Programming,Combinatorics
Hard
null
347
hi everyone let's continue with today lead code problems so today we are going to solve it for problem number 347 that is top K frequent elements so let's go through the column statement first so given an interior array nums and an integer K we need to return the most frequent elements okay most frequent elements and we can return the answer in any order for example let's try to understand this uh column statement using the example that is provided to us so here you can see like we have one array that is given to us and an entire k and within this array we need to return the K most frequent elements okay so here K is 2 so we are going to return two most frequent elements so how we are going to calculate this frequent element so definitely like for each of the elements we would need to count the frequency so for example here one is existing twice not Thrice 2 is existing twice and 3 is existing only one time so what we could do we could return the most frequent element first to most frequent element that is one and two that's why the output is one and two okay hope you understand this for uh example so for the second example we just have one element and we have k equals one okay so we are going to return one if uh for example let's say like k equals to 2 then in that case also we should just return one because we don't have any other element okay so hope you understand the problem statement let's try to come up with some approach to solve this problem efficiently so here so the one way to solve this problem is using sorting okay let's try to understand how can we utilize the Sorting technique and what are the limitation of the Sorting technique okay so if you perform the Sorting then we would get the sorted data okay that I am currently representing here and after that uh what we could do we could start iterating this array and can start counting the frequency okay so for one I will count the frequency and let's say like I'm storing it in map and for two I would count the frequency and I would store it in map and for three also I would count the frequency and I would store it in map okay but this way to calculate the frequency the way we are performing the Sorting is not an optimal one so instead of Performing sorting to calculate the frequency we could do hashing directly and for implementing this hashing technique what we can do we can use a directly use the map so in map like we could use the hashmap implementation so here like for each of the elements first I will check whether the elements are present or not if it is not presented by default of frequency is zero okay and if it is present I will just go ahead and fix the current value and accordingly update it so for a One initial it is not present so it would return Me 0 and after that I added this element so I kept the frequency as well again for the second element so it's not always necessary like data would be sorted let's say like I have some random data one two and three something like this so the next element for two also like with the uh this element is not present so by default we will get the frequency at zero I'm just going to insert this element and I kept the frequency as one now I am going to process the next element that is one I will check in my map whether this element exists or not if it is existing what is the frequency so I see here the frequency is one I will just increment its frequency y1 because uh now I have two instances of one let's continue and process the remaining element for two also like I will switch its current value that is 1 and I will increment its value by over and four three I will just go ahead and insert so now we have our uh map ready okay there we are having key and value okay and in this map like the default ordering what we could do since we are using hashmer so there would be no ordering of tag limit so it could be like first we have this two then we could have this one and then we could have three okay something like this and while returning we need to perform the Sorting on the basis of this value and accordingly we need to return the key okay so let's say like this is the sorted data that we could have and after that we could start returning to one and if when if I return one two there is no issue that is clearly mentioned in the problem statement okay so we understand uh one thing here like to calculate the frequency of each of the element we should not use sorting because it would take n log n so instead of using uh sorting we could go ahead and use hashing the time complexity to perform the hashing operation would be order of n and space complexity would be order of n okay in worst case what could be the scenario like all elements are distinct so in my map I would have something like this okay so we just discussed uh the way to calculate the frequency okay so the step one was or calculate the frequency of each of the element that we have decided to go ahead and do hashing okay now second step is somehow we need to persist this information in such a fashion so that at any point of time I can provide K and I would get the result for example let's say like it is in my map and in the map itself I perform the Sorting and return first K element that we can also do okay so then in such cases what could be the time complexity so we need to perform the Sorting on map and in map the max number of elements in most scenario could we order offense so the time complexity would become author of n login okay and after that at any point of time if someone is asking for K I would go ahead and fix the first K limit and I can simply return that one okay so this solution would work and the final time complexity for hashing the time complexity would be order option so overall time complexity would be order of n login and space complexity would be order of n so this is a working solution it would definitely work but let's say like I have I use cases so I'm just trying to cover One More Concept so that we can extend this approach to solve uh this problem as well as some other type of problem okay so here if you see like we have a static nature of data that is provided to us so this is not changing but what could happen if this data are continuously changing let's say like someone is adding some data into this one okay some more data some streams of data is coming okay and someone is updating this data okay then this K element top K limit will not be static in nature if our data is changing then definitely like this top K element would also get changed so if we apply the same logic here like uh doing hashing and after that sorting sort the man then what would happen let's say like for this state of data I perform the things and I just return the deal and let's select few more elements got into this like four five six then definitely the entire result set has not changed so again like I need to do the hashing for this new elements that I will definitely do but now again I need to sort the entire array element first way I need to do sort then result return result so if you see the challenges here like for it's okay like what we are doing we are first sorting so that will take n long n plus k so this uh would become this gate top K limited all time uh we like have a Time complexity of n log n plus K that is n log n so instead of this like we could use uh some hip data structure and where here we have a use cases of creating the top K element okay so what we could do we could use maxi so what would be the benefit of using maxif here so at any point of time if numerator are getting inserted to this Maxi one this Max ships internally will take care of you will find to itself and at any point of time uh you just need to face the top key element that would be sufficient okay so your kit operation time complexity would be K login okay where n is the total number of node that is present in this hip and you are performing a full operation basically fetching top key element okay and uh the top one always contains the max element so the overall time complexity would be K login so if you see here and compare it with the Sorting technique so from n log n we have reduced the time complexity to K login so that is more optimal so if we use the maxif implementation then we can easily solve the current problem and as well as we are able to take care of the scenario when we are adding or operating our given input okay so that would work in both cases so let's try to implement the solution quickly so first we need to perform like it has to uh things that we need to take care hashing to get the frequency of each element let's do that okay so we have inclusion integer let's say again calling it hashman and now I will simply go ahead and activate this element the array and try to update our hash map okay if I'm calling this theater default method so that if the element are not present in that map instead of returning null it should return me the default value that is zero let's see in this way like we have performed the hashing now what we have to do we have to perform the Sorting so for performing the Sorting either we can go ahead and perform the actual sorting on this map or we could use some data structure like priority queue and there we could have our own implementation of the Sorting logic and that could easily work for this current element and as well as uh the cases like where we are receiving instead of the static data streams or Data Network so let's try to implement this particular attitude we would need a pair type okay because we need key and valuable so then only like we could take care of we could take a call so let's say like on the basis of value we are doing the Sorting okay let me Define this class here I'm just encapsulating the two attributes one let me call it V and the second one let me call it value I am just providing one Constructor here properly create an object of the sphere class and in a slice of the variable status version that is its key and value okay now we have this proper uh Fair class defined we are using this class one and we have our own comparator distance there we are sorting it on the basis of this value okay and we are sorting it in decreasing way first open and after that smaller one now let's try to insert this now we have inserted this element also in our practicing now we just need to return Auto result so let me create a result array of size okay and as soon as like we have a while our parent EQ is not empty and K minus is greater than zero we should continue to the polling okay and what we could do let me create an index here so from index 0 I will go ahead and start inserting the element into this see do we have any other issue no we don't have any other issues I am just fetching the key and inserting it okay let's try to understand so here we would have okay dot key because we have not created the capital method I can directly access okay it should not be a method it's just a variable I'm just directly accessing this okay I'll say scope of here this key that you can see here is required so it would allow me to directly access this key method for this key here you can see like it is getting uh it is working as expected let's try to run for some of the custom inputs let's run it okay good expected K to have value from one to one only okay the answer is not your new okay so maybe like it is guaranteed like the answer is all time unique it is guaranteed that the answer is unique so let me try to ensure that one also so what would happen here so it is showing that one so for this one two three and here one two we could return four one we put it okay let's do one okay let's remove this customer input and let's turn on the given input and let's try to see okay it is working so hope it will work for all the test cases let's try to run network so it is working for all the test cases okay so yeah that's all I have from my end
Top K Frequent Elements
top-k-frequent-elements
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\], k = 2 **Output:** \[1,2\] **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `k` is in the range `[1, the number of unique elements in the array]`. * It is **guaranteed** that the answer is **unique**. **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
null
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
Medium
192,215,451,659,692,1014,1919
204
Hello friends, in my video today, I am going to tell you which prince's blog will be given a number and before that all the prime numbers will tell you their account, if one is then how many prime numbers before 10:00. Numbers are for but how many prime numbers before 10:00. Numbers are for but how many prime numbers before 10:00. Numbers are for but before this there was a problem where I was going to solve it in this video but to say that a little explanation is needed to solve that video for which I was trying to solve it through paint but with evidence. There is a little difference from the tree that some go to school to solve the problem from the tree, so this is the way I explain it or it is a closed loop slow work, so it is like that but on time, before this, you will have to tell me the list means there are many ways for gender also. It is called Singh Dilip Singh Liquid Bleach Circular but basically I will explain it first and then solve this question Verma. Okay, so in today's video, first I will use it on the account of those who fold, if there is a problem then I will solve it on the account. It is by using and there is also an ego thumb inside it, which I am going to tell about, which we use only thanks to your store. The problem is basically, we can call it by roots and methods also but this one needs more or less aloe vera and I will tell you about this problem. It says what it means is account prime, I have created a function and whatever the numbers are, I have only one number for them, so basically the problem with this is that it says that you have a paste of the same size as my number. It should be why in space complexities there is order in it, right and secondly, whatever number is taken on it, like, for all the elements, everyone has one app, everyone has the value of the first prime, everyone has many primes, then their attractors. It does this one by one and removes all of them from the nine numbers and okay, so before that you need the number which is the phone number, the length, if the value of the number is length then return it. Meaning of the transaction is two. If it is done then the return will be number one. In this, we have the second option. If the caller took milk, it means Jayanti, then one came, it may also be closed in 2013, for that matter, you should not have this temptation of leaving it like this, it is also okay, then one. And there was a function but the function is get prize that this is the one who is going to allot the ho by getting friends, whatever account will be there means this is the one who is going to allot them from the number so what to do first is this loot which I had created so in this What is that number, if there is express complexity, then what to do is to take any number downwards, which are prime numbers, which will be say, a, okay, I have added starting in it, emphasis one, we have to pause big, then prime. Number dot up and force, you don't have this number, the number of subscribe on this side, what you have to do, let us put the loop from where to where, four from I mode on two to license which we will do number five, here let's assume the number. Number number so f-18 number so f-18 number so f-18 whatever number it is and if prime numbers are returned then basically apart from this all the numbers in which the accused are there are ok so started 101 index on my phone and started ASI in all the remaining numbers. If there is no need, then I changed it with underscore from here, now what to do after this, like look, yes, I give brother-in-law, do fraction, yes, I give brother-in-law, do fraction, yes, I give brother-in-law, do fraction, four, now what we have to do is put another form 4i, whatever it is, I am a slide. By doing a method Africa, now from where to where do I have to go with you because from number 0 to nine and where to go till n, this is two, neither is two, this means this but following this, do minus one plus one. Is subscribe and the idea is its i key value will be leather end and i plus this means this and in the second how to do we have to check that in2 i flu number not only then why fidget yes that team inside this we are going to tell like There is any number, hit the value of N as 6, so before I see all the numbers, which prime number will they be, then you are doing well. Now see here, I checked that the number Aishwarya is fine, so the number is right here, minute. Checked it, by the way, it is from 2345, here it is found that the number Raees Ahmed is now school number four, small three 9 4 6 is wrong, so not only this, now we have checked inside it, is it necessary to walk inside it? Afan, whatever is the prime number, its key value is prime, meaning if the owner is the place on it is true, that is, we have set it from here, okay, so inside it, move it from one side upwards and that is where the film starts from. It will be started with i, okay, let me tell you that in this way, more numbers and this is also formed, okay, this means like Bluetooth on, so this means it is simple, okay, that's it and above, no I plus. It is Sanjay's values, it is Z plus eye, it is four cloves, its certificate is the sentence, it is not right to share the texture, it is not right to subscribe to chat, it is not right to subscribe, whatever is the two of you, then all these numbers are required inside the two, brute. What is there in the force that I remove this one, look man, responsible from 2345, it runs in the order and time, how for that, take mode of N and I will tell you its time complexity, how much proof and scheme, now put that I have spent the right way value. It will be so much that the person will take 900 so many numbers if the rosary is appointed till then that if Malaviya comes inside it then okay then make prime numbers A plus two part okay then it means it is not a prime number okay this What we have to do is now let's print a sample-sample which is print a sample-sample which is print a sample-sample which is print a prime number ticket from the number, this function was not even needed Jhala [ Jhala [ Jhala and sorry we have to print the present prime numbers and let's call it Gate Primary or whatever it is that we are talking about gate problems and numbers, we will write 6 in this exercise, now let us describe it, then what will be the answer then give whatever number before sixteen so that Ajay can get as many true marks in it. Isn't it whatever you have, those are your prime numbers, they are false meaning 0.005 number one number two 0.005 number one number two 0.005 number one number two Ghaghare 680 10:30 10:30 10:30 basically whatever is next then basically that is the prime number for the other wise otherwise you can use it like this yes let account request 204 Just check those prime numbers by doing status in WhatsApp number, whatever the app status is, if the status is cute then turn off the account value torch and here what you are wearing, below it, print account with above it, now they are liquid. The one who prints the key will print it for the account, otherwise he checks what is the going part. 500 and 1000 are made late. In Vighna and C, they are called constants, so I don't change which language, so I made it a variable, so now it is the account key. The value should go and come because 436 is coming can see what 1234 a pipe inserted 61010 meghwal a play list on the 10th 4012 is 45 to 60 okay so for and this should subscribe school and for this which Also you have subscribe to them by number that one number ki war subscribe that pain in love and ok and brute force ki jo hai n jo log in hai n0 me milk watch here and his jo enroot kar ke liye time If there is complexity then you can do it like this. Now see its time complexity and by the way it is less than this because it is running till login and if I thought I would have written this or I think I would have written this then Login. Used to be and I made it square, so let's go to the time complexity of it till Login, otherwise for gram flour, there is shortage from Britain only and in this one, we used this velvet in this and yes, you can put another check, you can put a check in this that Then the value of the number, if the license is not hands free, then let it be, if the number is two, then the number is 822. If the number is two, if you remove the license from me, then the number of the living person is spent that if the value of the number of cases is three, then from three. If you have removed all of them below then you can return them. Okay till now you need to add some ghee. Number 10 will not sell, so that is the problem. If you liked the video then please like and subscribe.
Count Primes
count-primes
Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`. **Example 1:** **Input:** n = 10 **Output:** 4 **Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7. **Example 2:** **Input:** n = 0 **Output:** 0 **Example 3:** **Input:** n = 1 **Output:** 0 **Constraints:** * `0 <= n <= 5 * 106`
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors: 2 × 6 = 12 3 × 4 = 12 4 × 3 = 12 6 × 2 = 12 As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n. Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach? public int countPrimes(int n) { int count = 0; for (int i = 1; i < n; i++) { if (isPrime(i)) count++; } return count; } private boolean isPrime(int num) { if (num <= 1) return false; // Loop's ending condition is i * i <= num instead of i <= sqrt(num) // to avoid repeatedly calling an expensive function sqrt(). for (int i = 2; i * i <= num; i++) { if (num % i == 0) return false; } return true; } The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple. Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0. We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime. The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia. public int countPrimes(int n) { boolean[] isPrime = new boolean[n]; for (int i = 2; i < n; i++) { isPrime[i] = true; } // Loop's ending condition is i * i < n instead of i < sqrt(n) // to avoid repeatedly calling an expensive function sqrt(). for (int i = 2; i * i < n; i++) { if (!isPrime[i]) continue; for (int j = i * i; j < n; j += i) { isPrime[j] = false; } } int count = 0; for (int i = 2; i < n; i++) { if (isPrime[i]) count++; } return count; }
Array,Math,Enumeration,Number Theory
Medium
263,264,279
516
That Hello friends, welcome to the video, question number 516 loot code longest first intro mixture sequence is a medium level question, the question is the question of DP, you guys will get the internet, it was asked in LinkedIn, let's start the question said give in spring gas, okay one String is given, what is it you have to find the longest first intro mix subsistance, so before continuing further, I would like to tell you this question is 95% I would like to tell you this question is 95% I would like to tell you this question is 95% love, in the code and concept, we had discussed in detail with our long s common sub chicken which is thirty one minutes long. The video was Meena, so we are going to continue from this onwards, if you have not watched the video then you will not be able to do all this. Click on the button in the description. Okay, before starting, let us see some good examples so that we can understand that first. In this Rome, what is the sub sequence? Okay, so let's see the example, you will see that there is a Bluetooth settings, gift class 15 famous website also add, so if I equip random sub sequence in this trick, we can do anything and we are selecting one. So if we select this double cases, now see, I looked from the front, I was looking from the forward direction, I and I got a sub sequence double E K W E but this is such a sequence, if you look at all the back then you will get this one. The sequence will be found in the Delhi actual of double this is the first intro mix subsequent and this is the biggest first Rome in all the sequence in Wally Street so we can say that there was a subject in the long gas cylinders so basically you will see that you see from the front Look from the back, you will get this sequence from both the sides. Double one cases. Okay, to make it a little easier, I can do this. Now I will reverse this trick so that I do not have any problem in seeing, so what I mean to say is that if Kunwar you Reverse it and now if you look, you will see that very easily you can look in one direction. Okay because earlier we had to look from behind, now in both the strings we have reversed and made a watching. Now we can look in one direction. Okay, so now you will look in one direction, now you will see that in these two strings, we are getting our pentro mix subject which is what is our double also cases, so this question basically you can connect with long s common subsequent this time A lion was given, in that question there was a friend drink and the common sub was to be found. If we reverse our string and make another lion then basically I would say that our same code can work for us. If we come to the code then this question. Basically you have to use the same code and first copy the code of the longest mansab sequence that you can copy this chord and what this time is that we are given a single string and what we have extracted We had found out the longest Mansab sequence by using text one and text, so in the calendars we saw that reverse this Samsung and then you have two settings and now you take out the common subsequence, so in this way we took out You can do this but you will be successful in this first intro mix. Now don't worry about how big is the sequence to find out the length. Earlier also we had found out the length so there is nothing to do. This time we will see what is given to us. Now we can take text one and text. If there was two, then text one is considered as S. Just keep it and if text two is not given to us, then if we reverse it and make the text its nature, then how will we reverse it? Let's make a string builder and make an inverter in it. Let's put it and reverse it and use its function. This is a very easy function of Hasting Builder and finally we will have to convert it into string. So what you have done in this way is that you have given a string, revised it and the rest is a text note. It is written that X2 will be the final length, which is our gift line which was 5mm, which was made double of one, it was like this, then you will see here five lengths will be our return and you can use the same code. Have asked, I will twist the question a bit. This time, let's color it once and see if it is being accepted. Let's also see after submitting a code. Our porn is also being submitted. I would like to tell you if you go to the About section of my channel. If you go to I, you will get all the other questions in the video that I have made, you can search directly from this Google Sheet, in the About section you will find this seat, see you again in the next video with the next question. Thank you very much for watching this video.
Longest Palindromic Subsequence
longest-palindromic-subsequence
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`. A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** s = "bbbab " **Output:** 4 **Explanation:** One possible longest palindromic subsequence is "bbbb ". **Example 2:** **Input:** s = "cbbd " **Output:** 2 **Explanation:** One possible longest palindromic subsequence is "bb ". **Constraints:** * `1 <= s.length <= 1000` * `s` consists only of lowercase English letters.
null
String,Dynamic Programming
Medium
5,647,730,1250,1822,1897,2130
50
Jhal which hair serum will use we select bank on express new generation in hatred power function have to keep it use that power com that we have by clicking entrenchment you are and victimization is that power is x squared minus one that a score And minus one times that and minus one times can apply by applying Mata, now we have to do fat sapna sports meet and adopt a military splendor modified to the recommendation and power of common wealth management already knows to do medical aid according to this then I have to power of At adjustment don't be arrested. What should I do with you from Express-One? I have made profit in this. It What should I do with you from Express-One? I have made profit in this. It What should I do with you from Express-One? I have made profit in this. It should be once together and once mixed together. And how will it be done? Who had kept this on Monday? Have you ever spent total time in a bus? That sir, let's try to get the level right for this, so I said one white in express par minus one, according to power com, so this is the power I have given to this, to set this reminder, we need that there is a lot of similarity in the two, this is a tutorial. If you like it, I have made a cut for Eden, you should not do it, you can do it sometime, because now we are closing the settings, so I hope that your level has become such that in every question till the end, the question is not landlord. Let's try this last time to Ajay, if we are getting an option for tubeless husband, then we will feel very good, but somewhere there was a mistake in the line number, so I probably wrote in the restaurant function that 'A 's son' Let's see if 's son' Let's see if 's son' Let's see if Ajay is there then he is getting prosperity. Now we should do it by 1 gram. So let's do it sexually. Okay, so this is what we have. Keep doing this by making the code file stock. Verification will come in a good way. World End. Experienced when in the world, it has passed in both the legs and body bay declared. 13 - Coming out of one and 1, bay declared. 13 - Coming out of one and 1, bay declared. 13 - Coming out of one and 1, then come you were told that if you remove the super, then this line number will be 1091, today she will go to college, above one, this one will pass. And minus one, it will pass. If you catch a cold at the next level and if you go to line number one, then you will pass there. And minus one, if you go to the top, then you will go to line number one, then you will pass there. But in their place, editorial, which is the first When the line started, one was hit and it was passed there. Finally, Bigg Boss, now he has been appointed 10 receivers. Now when line number two burns the liner, one scores and divides it into minus one. Once. If you try and put three or two MP3s in it, what does it do while sitting online, it reduces the access point? Premium skin care level, received it on express at 1431, line number two went on, the pilot of the plane got into it, line number is on. Got that Rishi's access point - we went to line number that Rishi's access point - we went to line number that Rishi's access point - we went to line number two, the product was this is this, we got the access point of Mintu, it's a little thing, of the same type or below it, this point - 1m, point - 1m, point - 1m, that line number two went to product, the job was done. So the return is already here. This video will go to the printer. Friends, if you understand, you must have seen it. See you in the next 9 news room.
Pow(x, n)
powx-n
Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., `xn`). **Example 1:** **Input:** x = 2.00000, n = 10 **Output:** 1024.00000 **Example 2:** **Input:** x = 2.10000, n = 3 **Output:** 9.26100 **Example 3:** **Input:** x = 2.00000, n = -2 **Output:** 0.25000 **Explanation:** 2\-2 = 1/22 = 1/4 = 0.25 **Constraints:** * `-100.0 < x < 100.0` * `-231 <= n <= 231-1` * `n` is an integer. * `-104 <= xn <= 104`
null
Math,Recursion
Medium
69,372
208
hey guys welcome back to another leak code problem solving tutorial and in this tutorial I'm going to be showing you guys how to solve leak code problem 208 which is asking us to implement a data structure called a try or a prefix tree so a prefix tree is basically just a special type of tree which starts at a root node and it can contain only letters Underneath It or Not Just letters but essentially the tree can spell out different prefixes and it can store words using a special format which allows it to easily search for words starting with their prefix so I know that was a bit confusing but let's look at an example so in this example we want to insert Apple into the try well what that basically is we store each letter as a prefix or we store each letter as its own node nesting below individual other nodes so Apple would be stored like this that's a bit small but yeah so this is how Apple would be stored starting from the root node we know the first letter is a then second letter is p and we just go along and spell the whole of Apple like so and you can see if we were searching for prefix like if we were searching for words starting with ap well all you'd have to do is go along to AP and then look at all the different roots from here and that's all the words which this tree contains starting with ap so the idea of this is that we can store multiple words by grouping them together by prefix and separating them when necessary for example if we had something like uh okay so let's have we have apple already but let's say we want to just add apps so apps as in like I don't know applications something like that if you want to add that in well we can see we've already got the AP inside the tree so instead of going L next we can just add an S and that's essentially added the word apps into our tree so now we have apple and apps and one thing you might notice is how do we tell when a word is ended like cuz how do we know we haven't just added a or how do we check that we haven't added AP because right now there's no way of tell it like for example if we added both the word apple and apples well adding the word apples would be equivalent to adding an S at the end of this but now how do we tell that the word apple on its own is in here without Apples because it seems a bit confusing well that's why one thing we can do is add an end character and this can be anything it just needs to you just need to make sure it can't be used by any words so I'm going to use a hashtag and essentially what I can do now is just add a final node onto the end of each word which essentially marks that if we can go apple and then over here to another node then we're searching for just Apple so when we search for words we want to search for the words with the hashtag at the end this just ensures there's always an end C at the end and then we can just search for them like this and we can be sure that the actual word exists and it's not just a substring of another word for example if apples didn't exist then this hashtag wouldn't be here so then when we search for Apple like this we'd get here and notice that there's nothing there so we could conclude that apples doesn't exist Apple doesn't exist that's the basic idea of a try just a big tree and yeah it's called a prefix tree because as you can see it's sorted by prefix if he wants to find all the words beginning with a we just have to go into this node and then select all the words in here nice and simply but yeah now let's see if we can implement this data structure into our programs so into typescript or JavaScript now what I'm going to use to sort of try is actually going to be well I'm just going to use a hashmap um and the reason for that is so you get constant access time so if we call the dummy node to be this or the root node is this then our hash map is going to be well we'd have a and then it's corresponding hashmap and since there's no other letters we're not going to have any other letters but now if we go to here so this is the hash map for a this is going to have a p it's corresponding hashmap and nothing else and then if we go into this hashmap this is now currently here this is going to have another p and this hashmap since we're here these basically represent the next possible route so it's going to have an L its corresponding hashmap or we can have an S with its corresponding hashmap like so and yeah that's basically demonstrating the next possible roots from this p on to next letters and this is just going to be all nested inside of each other and basically we're going to Traverse it like a tree but we're just storing it in hashmaps nice and simply so yeah let's just implement this now so class try let's create a entry and this is just going to be this node here I'll just Define this to be a hashmap so it's going to have a key of string and it's going to map to another hashmap uh I'll just put any since we don't really need to be worrying about all of that but yeah it's going to be of Entry any and when we initialize this we can just do this. entry is empty like so okay so if we insert a word we're going to start at the root node and for each letter in the word we're just going to check whether the root already exists if it does then we'll go into it but if it doesn't exist so let's say we wants to add bus into this well there's no B here so we need to add a b to the hashmap to the list of next possible letters and then we just go from there and then we just continue like that so essentially what this entry hash represent is the next possible letters like that so starting from here and it represents the next possible letters we can take or the next possible path and I'm just going to Loop through the letters for c letter of word just going to leap through this and we want to check if letter is a next possible path from the current node so from here and to do that we can just do something like if next possible letters is not defined well if it is not undefined that means it exists and we want to handle the case if it is undefined so if we're in here it must mean this path doesn't exist yet so let's create it and to create a path pretty simple we just have to start a new hashmap from within it so if we add in B this is equivalent to just creating this B and then just creating an empty hash to represent the next Poss is from there okay and once you've done that now from here we know this letter must exist in next possible paths and we can just increment this next possible Letters by doing uh this so similar to if you in a link list you'll just or tree you'll just go into the next index at that position and then increment in your current pointer like there so there we go nice and simple and one last first thing we need to add our end character which I said was going to be a hashmap all right there we go so here's how we insert a word you can see if we use apple it's just going to keep on going through and well if we imagine this hashmap was empty it's just going to keep adding these in like so and once it gets here it's going to add this hash and then we're going to be end up on this final route like so sorry I shouldn't have scribbled out this hash but you get the idea okay so nothing to do there we've completely finished that now well I'll search for this word but I think it would be a better idea if we implement this starts with function first because once we implementing the starts with function we can simply just add this end character to the word and use the starts with function so what we want to do is same sort of thing we're just going to do let next possible letters equals this. entry starting from the entry point again and we want to check if there's a word starting with this prefix so if we was for example searching for AP or app well we just want to check if a exists then if P exists and then if another P exists from there so for con letter of prefix check if letter is a possible path if not then prefix doesn't exist in the tries so return false like that so we want to check for each letter if it exists as the next possible path if it doesn't we're going to return false so we do if next possible letters letter is undefined then this path doesn't exist like let's say we were searching for APB we'd get to a we get to P but then we check for B and it doesn't exist so we return false because this prefix doesn't exist and then we're just going to Inc next possible letters to go to the next step like that all right there we go if you don't understand this line it's essentially so if we start here we check for a it exists so we get past this but then this the next possible letters is currently on this hashmap here and we just want to it's this hashmap and we want to go here so we now want to be inside of this hashmap like so we just set this to be equal to that and that basically increments it nice and simply if we get through the entire word and all the letters are there then that must mean the prefix exist so return true like that and now all we have to do is this we've implemented this starts with prefix so now if we want to search for specific word well that means we're searching for the whole word and we need to check whether it exists with the hashtag in it because this marks the end character so we can just return this do starts with and word plus hashtag search for entire word with end character like so cuz if we were just searching for the word then if we were searching for apple and we hadn't actually added Apple but we' added actually added Apple but we' added actually added Apple but we' added apples then starts with would return true since the Apple prefect exists but if we add this end character now it's going to look for apple and then this end character which is going to check if a whole word exists so there we go that's how we Implement a try in JavaScript did this all using hash Maps so no classes although if you were to implement it you would likely want to use classes just so it's a bit cleaner but yeah this was the triy implementation let's submit this and see what we get all right there we go so yeah like I said I'm pretty sure this hashmap implementation is actually a lot faster compared with a class implementation just because hash Maps just optimized as well as the fact that we're using this end character rather than using specific attributes on a class but yeah that was pretty good getting to the 90th percent ho so that was how we solve leak code question 208 going us to implement a prefix tree see you guys in future tutorial bye
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
1,706
Hello friends, today we will discuss the solution of leadcoat's daily problem 1706 Where will the ball fall, so let's see the problem statement, the statement of this problem will be. And we have to take this hypothetical man that the problem ball will be given and you can move it diagonally from any index position of this given green matrix, meaning either you can move the given one from this position to the bottom right or by doing WhatsApp down mode. And the green in it can have only two different values, it will be for the case, let's say there is a van on it, then it can be timed, you can do only and only bottom right movement from the position of this grid. For skills, you can use this Water can move left from the position of the given grid and in this problem we will have two N number of columns. From the top of those columns, if you drop one ball each in this given grid and for each ball you have to find this. Whether he knows how to come out of this given grid and if he comes out, then he knows from which column he knows that he has to make a further answer put for the ball and if this ball gets stuck inside this green, then for him You get mines van. To understand these things in a concise way, let us look at the example first. Here you can see its value in this way. If you look at the value of this index, then there is van here because this index. The van is pointing to means that from this position you can write most, which you can see here. The path for writing bottom is given to us in this pictorial and for each index, you can easily see here and We can understand from which position we can move, if you ball one ball for each column here, in this green, you can see that only v0 ball comes out from our first column, that is why. Meanwhile, for zero, we have written one 'are' in the output. For we have written one 'are' in the output. For we have written one 'are' in the output. For zero, van has been returned and for the rest, minus van has been done. If this ball column had come out from tu, then tu would have been written here, then similarly we would have got this problem. We have to do something for this problem. If you look at the constants, then the maximum value of M and N is given to us as 100, which is indicating that we can easily solve this problem through Fruit Force approach, so let's take it and If our ball gets accepted then we do not need to discuss any logic for it. We will simply write a DFS recursive pants for one of our balls and see if it comes out and if it comes out then from which column it comes out. First we will discuss the medicine code here we have to complete the find ball function, in this we have an answer named grid of zero dot, what is the length of clear, that is, if cross M is migrated, then we have cleared the size and We have returned this answer last and to fill each value of this answer, we have made a blueprint which will divide the answer dot length from zero and for each input we are running a BF function which is We are told that if he comes out of the ball, if he does n't come out then -1 will come and if he comes n't come out then -1 will come and if he comes n't come out then -1 will come and if he comes out then let's see here. Our DFS function will work in this way. Here we have entered a green value and in this green we have entered which position. But it is in the IK that we are delving, so ours will run in this direction, this will mine in this direction and in the starting, the value of our I will be zero, which means the ball is also falling, I take this ball, if it is the ball then its Starting in next, what will happen if you earn zero, for this our I will be zero and K will be you and as soon as we enter this function, first of all we will check whether our I is index i.e. index I has not gone out of our grade i.e. index I has not gone out of our grade i.e. index I has not gone out of our grade and call it case. In this, our ball will go out of this given green and the value of our K at that time will be our answer because in that condition we have crossed the green, hence the column is also presented and then we will check the condition. Are we wondering whether we do not have any boundary condition, meaning that the eye is not going behind us because it will not go, it does not matter whether we have written this condition or not, if we have written it then anyway it will not make any difference after that. Then we are seeing that it is not going negative, what can be done is that we take the man in this direction, at this position, if your movement in this direction was possible, then in that case, you can go here, then we will check for the same. We are checking whether it is going negative and then we will check that it is not going in this direction, that is, the opinion which is not bigger than the breed of eye dot length, if any of these three conditions occurs then it is considered a case. In this we will return -1 which means our ball has gone will return -1 which means our ball has gone will return -1 which means our ball has gone inside this grill, no problem for us and after that we will again see what is the value of our grid, then we can make a bottom right movement in the case and make a bottom right movement. For this, we will also have to see whether our case of this type is not being made, that is, the case of V Shop is not being made, in that we will make movement in this sale but beyond this, we cannot make the next value for that. We have to see that means plus van, this value has to be seen whether this value is not our van, that is, it is not of this type, if it is of this type, we will be able to move ahead, respect vice, then this is also a shop here, that is, here. -1 will be present. is also a shop here, that is, here. -1 will be present. is also a shop here, that is, here. -1 will be present. If present is followed by -1, then in this case If present is followed by -1, then in this case If present is followed by -1, then in this case we will not get any way to move ahead, hence we will return -1 here, otherwise return -1 here, otherwise return -1 here, otherwise if there is a case with van, then we can move ahead and J. We have also increased the number which can be seen here and returned it only. If there is a case of mines van then we will check it in the case also to see if we can go back and if we cannot go back then the one with mines van in the case. So it is not a case, similarly, the B that we are checking here is not being formed. If B is being formed then we will return -1. Otherwise we will return -1. Otherwise we will return -1. Otherwise we will call DFS by doing I + 1 and doing K minus one call DFS by doing I + 1 and doing K minus one call DFS by doing I + 1 and doing K minus one because it will point to the bottom. After this function will be completed and the answer that comes from here will be stored in the rectangle value and in the end, if we return this answer, then submit this code and see that it runs. You can see here. This code is our best out of the best. Now let's go and see the C Plus code. You can also see the C Plus code. We have written in SIM Milne, the logic will be similar. Here also we have written a vector of answer. What is clear about this? Today it will be my turn and for each column, we have written DFS function similar, which you can see here, we have called it and whatever comes from there, we will back it in the answer, so we will also submit this code. Let's see how much percentage is faster in this language. Our code in this language can be seen here. Our code in this language is 19% memory efficient. So I hope you can understand the is 19% memory efficient. So I hope you can understand the is 19% memory efficient. So I hope you can understand the code and logic of these two differences, not only simple but also simple. Let's meet again with the next video. Let's keep recording and we will provide the codes of both these different languages in the empty description box, so you can check from there and you must give your feedback in the comment section that in this video. What is the article? So we will improve the video accordingly. Thank you for watching this video.
Where Will the Ball Fall
min-cost-to-connect-all-points
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Array,Union Find,Minimum Spanning Tree
Medium
2287
456
Hello Everyone Welcome To Krishna Buddha Osho Hindi Speech Will See The Question 56232 Pattern Solid Is The Most Electrification In Terms Of Vikas Ki Maz Par Question And Also Like Question And See The President Even A Leaf Integers Numbers The Name Of Are 132 Pattern Subsequent To This And Subsequent Stage Chief Continues Set Can Be Like R Elements In Relative Positions Like And 12345 124 You Can Skip Element In Between Brother In This Is This That Synthesis More Than 300 120 Miles 193 In The Sub Screen Needle's Senior 1382 Pattern In Sub Sequence Of Three Enters Its Members I Am Children The Truth Of These Numbers Selection Change Behind This Decision Good Village School's End The Element Added To Any Specific Bullet Price Place A Number Of Cases Of This Place A Number Of Versus Not As A President Someone It Is Not Like who is first man to all this and secondary school noida authority plate dixit 1328 min first model third element and third elements from danger law student all the best all elements min middle element is the maximum of all and the first element is the volume of but iron Elementary someone returns to this sharp storis pattern in the number wise return forms and follower of this day people to start with Ashtami protest will be optimized for the lion and off and so let's see foreign currency in December-2012 and can force vacancy strong December-2012 and can force vacancy strong December-2012 and can force vacancy strong sunshine possible prayer Witch Forms 1323 Someone Speed ​​One Who Guarantees Kickrator Health Speed ​​One Who Guarantees Kickrator Health Speed ​​One Who Guarantees Kickrator Health Certificate One Third Suite Solves All The Small Wooden Key In Districts PNB No Position Because She Got Stuck Returns The Amazing Se 0.5 Inch Islam Returns The Amazing Se 0.5 Inch Islam Returns The Amazing Se 0.5 Inch Islam Prithvi 1420 One Such Are Effective Chess Patience Solution Possible Because If Bill Check Z2 Tijan Sanjay And Left Actress Aishwarya Rai Is Less Than Most Sources Of Pollution For Best Wishes Way Between One To Shyam Plus Ka Show It's Difficult Waste Questions And Cases Can Be Appointed To Loot See Haq Hair Faster This Question In Interview For The Complex And After BCA And Position And Discussed With This Question So Let's See How We Can Do That Why Do You Know Me To Front Additional Superintendent Of Police Condition Of It Took Place In Your GTA Beneficial Placement Of Middle Element To Depot Element And Not Celebrate The First Look Soft Wind Ministerial Sundha Three For Lips For Him Simply Nested Call Us Aka I Will Run From Which Sentences Are Twisting And Evidence From Depression Due Course Admission For You Need You To Please Him Measurement So Come Most Important Thing Pet Connected F I And Nishumbh Character Of Traffic Police And I Will Turn On Little This Point's Basis Points Which Of Course After Disappointed - 2 And - 250 15819 Difficult Disappointed - 2 And - 250 15819 Difficult Disappointed - 2 And - 250 15819 Difficult Scooter Icon To Invest Scars And Share And Will Not Have Any Specific Conditions Will Not Be Broken Turn On Years - 2nd Not Be Broken Turn On Years - 2nd Not Be Broken Turn On Years - 2nd T20 - One Vikas Can Be Taken As A Corrupt T20 - One Vikas Can Be Taken As A Corrupt T20 - One Vikas Can Be Taken As A Corrupt Elements Class Element And Editing Notification Ruby Simple Note Wishes For Hussain Will Keep Checking The Condition Behind The Village Tube Jain And Fairs In Patti Par Off Elements For Vashikaran And Vaikuntha Rush Play List 2 Otherwise use it at high speed and in the morning that shampoo returns for that is the most recent edition will take off a good time for several years in this forest produce any space contacted just over four decades and what should in this way simplification entered into force to delete Services That Day I Will Tell You How To Optimize Father I Can See Her Pieriyu Singh And Difficult Attitude And Square Feet Tak Suzy Registration For Using The Increase The Telegraph CT To Improve Into The Specialty Of Candidates Who Is All This Mod On The Great Element And Kids Element Tubelight Mis Behave To Take Minimum Elements And Its Quite True Colors In Cases Question Dum Suryavanshi K Dues Patrolling Only From This And Active One Intact And Will Start From G Plus One And Will Spoil Simplified Collect Minimum On For Every Element From Everywhere Else Will Find Its Left Minimum Element Is Left Maximum and Minimum Element Stree Sui Dana Value Melbourne Test Scores Festivals and Activities of Elements with the Meaning of But Sir Flicks Like Three Is Chekhov Jis One and Disputes Notification Will Not Two Wickets This Thing Is I Seven Is Not Target -1 Stationary 10 Greater Is Not Target -1 Stationary 10 Greater Is Not Target -1 Stationary 10 Greater Noida and Educational Institute 9 2012 University Improvement J to the Intex Reddy Amused and the will be at this point no is serum minimum thing left nomo will be updated with the system will be given and three fennel the problems victim prevent election Now minimum is vansh that is a guy attraction casei is of birth to baby that i am now me a point and kid will see you for and talk show person whose great and lakshmi edifice and its all songs its which cigarette deendayal bhavan tiffin this is eliminated in This Condition A Gift For All Who Is Running From One To One In This Life But Most Taken And Sister In Law Sex Addict Can Go To Search Then Unique Will Not Have Any Element Of Developed Internship President And Drop Collection Of More Statement Witch And Uric Acid Aversion on petition and sugar compares him officer left minimum is cigarette central enter clear and morning simply app tablet minutes ago is loop control actress and is element and advocate elements for wearing a call on Casio Xavier Institute for KVS running staff and hindi condition of every element How is laptop minimum so amid such pressures sexual k&amp;u that amid such pressures sexual k&amp;u that amid such pressures sexual k&amp;u that this lesson person tiffin service important form alphase him thrust sequence house for smoking and simply liberty kinjal left in sediment and lakshmi amazed to find subscribe scars and witnesses form continues to president Also 3420 Shift Valid Source Updated By Example A Gross Like It Is A Gift For Example Justin Chairman CP Thakur Minimum One Hand And Appear At This Point I Can See This Food Okay This Point Harold In This Condition Unit Certificate 1482 Will Uniform Threats To Forget This Will Help You Keep Account Of Tamil Eelam Elements Minimum Element Bun Hair Tips Simply Several Left Minimum The Element S1 Dainik Ki Vriddha And Is Jiske At This Point And Key Certification Easier For Its Good To Take Element And Even Is Model Key Verification Sukh Kaisi Or Indian School Certificate Simply Demon Power First Day of Years in Father Phase Element to White Elementary School Dress Minimum of both will simply set up to the human value of the ladder To element from this element will set I to the mean of the left most favorite subject wise And Akram Have Enough Time Complexity To Of School Staff And You Should Be Done In The Distic After This Edition In The Interview Setting Situation Optimized For 2nd Year And Species By A Billion Looted Using Simple Rough Simply Amazing At 91 From Here Land Acquired Optimization Techniques Can See The And Moving Toward Optimism Luti Strongest Finish Yes Candidate Will Be Will Have To All Will Have To And Power From Active The Official Calendar East Cities Optimizing A Mixing Software Date Will Have To Tourism Palaces Possible Final Blackmail Events For Everyone The Amazing Left Her mother of variable and news edit for improvement wake up against it 012 wishes left me 0513 because service rule student protest and then you can see the election will be laptop for black minimal i - puberty and infidelity the for black minimal i - puberty and infidelity the for black minimal i - puberty and infidelity the meaning of but i can see A tool which one should prepare left menu more to edit such problems distic 1 lakh amazon.sg mohe apni point out amazon.sg mohe apni point out amazon.sg mohe apni point out minimum of all the three elements of defense of India is element wires left here you can select My Surya Forms Are The Electrons Advantage Minimum Of All Elements Tree Selection For Finding Z Middle Of Banal For Right Side Back To Back Side Classes Okay Subha Do From The Objectives Of Reverse And Furious He Send Will Help You Find Any One Variable Classification Romantic Specific Cases Under forward such only and press the president notifications which ₹1 will press the president notifications which ₹1 will press the president notifications which ₹1 will run from this point to can see her will not be deployed s vic acid ad k doctor j recruitment admit development view effigy of as soon as get it g is pime z person final political Among the elements satisfied were conditioned to procrastinate from this zoom enter button for pages pe is food but just for this great essentials element which took to that was destroyed with Sachin for student bf taxes and chief such effects from z f mez pe jis stree ke toilet element This lineage that is this can be possible to make sure that one is mode on free and fair to find set the element of the given city with the cleanliness of this is not bring to front whiteness of you can see and Twitter maximum Level of abstraction Taxpayer Sector-49 Professionals Hadn't Only Sector-49 Professionals Hadn't Only Sector-49 Professionals Hadn't Only Ultimate Win You Certificate Assistant Professor Maximum Element The Maximum Element Which Is Great Dane Other Invented Distillation Hee Subah To Front Element Co Element Isse Zoom Date Of Words Fiction Special Issue But When Doesn't Change Obscene This Video Subscribe Scent For Every Difficulty Acid Subscribe Button More Expense That He Use Status Certificate Element's Judgment Be Great And I But He Will Just Chill Statement Has Not Released Its Benefit From This Trek And Will Only Give The Shadow Elements Which Was Released Before Condition Pure War Academic Problems Earth Developed Display Where Is And Will Start From Rate Reverse 1582 Left Frequency Specific Is Any Left And You Can Set Your Will Run From NH20 Acted S Per College 12345 International - 110 S Per College 12345 International - 110 S Per College 12345 International - 110 Vacancy For Every For It's A Good Acid Ki Apr 8th It Tongue Tower PNB Only To Is This Chale Is Greater Diversification Of Life In A Basket Just For This Purpose Emphasis Note Book PDF Office Call Go In The Morning Message Send Report More Than Condition Is Difficult Element 2018 Minimum Select Month Of The School Building Or Tissue Election Element Witch Will Be Mode On This Element Vs Element President Rang Day International Subscribe To President And Subscribe To This Is 0 And Baby Doll Is This Element Vikas Defeating Is Alloted A Not Smoking Element Skip B Grade Dirty The Index Of Cases Witch Can Not Have Any Care Center For Sea Mystery At This Point To Sacrifice Of Cases Food Civil 84 Sunao Available Digit Only 16 To Go To Definition Of Similar Music Hafiz Saeed To Spirit And Left Minimal Objects Which Is To That Is Waveform A Particular Dresses For this chest to and fry effective work is ment to know where to find by arranging funding tell how is your health but of limits for this great and as quick as air port of spain west is the great scientist apply biscuit patna on effect is the Popstar 14 Is Great And I Don't U But Its Place Sanjay Technology Someone Stop This A Best Practice Notes Chief Minister Curved Not To Cases Can And Also President Elementary Dew Pure Greater Noida Is Dynasty Increase Apps Elements Canopy And Pollution ₹15 Apps Elements Canopy And Pollution ₹15 Apps Elements Canopy And Pollution ₹15 Destination And Sleep Imported Cassie Description Activist Certificate Not Attempted For Example Wearing Dresses Tag 921 Simply Amazing 2018 1109 Condition Will Not Be Satisfied With Square With Smaller Than Is One Is More Cigarette 102 Defense Of Nations Not Specifically Added In Just 120 Cause 2019 Possible Of Cancers This Is Not Possible Benefits Will Be Observed At My Real Sacrifice And You Can See This Wide The Value Of Interest An Unless All The Best Qualification Tech Cement Key Point In Papaya Name APN - Hair Tips Again Lesnar Name APN - Hair Tips Again Lesnar Name APN - Hair Tips Again Lesnar Swift This All Well Wishes Organization Side Effects clipart end Will be left with values ​​which can be written is values ​​which can be written is values ​​which can be written is disconnected 9f left agroforestry then someone executive check hairstyles notification note anti-hindu circulation notification note anti-hindu circulation notification note anti-hindu circulation nothing happened for the sake of it's a greater noida extension superstition of whiskey with water meters which has enough toe element Which Is Written EP 150 Check Extract Official Of Track Is Less Than Your Fit That Means Egg Its Value Sports' Value Is Its Value Sports' Value Is Its Value Sports' Value Is For It's Not Edison G Value Points Greater Than 40 Percent Afternoon On Scanner Was Divine Secretary Sacrifice Of Sacrifice Most Backward This Is Not Possible 108 That Tweet Amazon Observable Computers Points 58 I Gym Pradesh Part No Same thing Pages And True Ironing Agni Inches Greater Noida To Lucknow Look This Way Intact Were Most Developed In This Particular Difficult Indices Close Spoon Uric Acid Like This Things Greater Than 150 140 Increases Neurological Strength Will Have Increase Wave The Chief Officer Entertainment Bieber All Saints Waft Video Shiv Vidment Amazon To The Sentence Shifted Airport Element Hotspot Of Management Appear Different Tooth Listen Brothers Tag End Nau He Zee News Stree Land IS One 9 Work Liye BCA First Rank They Will Run Special Cases Of Electronics But Will Of Elements Is Particular Element In National High They Can See Is Closed Spoon When Condition Satisfactory Don't Open Element From This Award An Element Is Possible Son Sachin For Us But You Will Complete His Devotion Should be taken for which will be taken for a bfi unqualified person educated chair respect is obc return to subir which state is phase key element ok and use this jail pistol user friendly by superintendent of police elements every year for making a sample of that can see JOB ELEMENTS 2ND YEAR IN THIS ELEMENT 3 INCH AND ITS GRATITUDE AND TODAY THIS GIFT POSSIBILITY PER VACANCY AND 80 POSSIBILITY HOW OK IS THAT HAVE TO AND JIS 300 BRIGHTNESS K IS MODEL HAI NA TUJHE PER THER DEFICIENCY IS GREAT E REQUEST TO ALL SAUTAN K Examination Satisfactory Se Quilling C Jis Question Video Set Below The Number 90 Number Of Cases In K Number Wise One And Key Students Isthi Suresh Places In Such Cases But From It's Quite Well This Point To Surya Forms 132 Pattern Tuition Audio Of Inspiration And 110 PRODUCT UP SEND MESSAGE ON ELECTION REFORM MAX TV BUTTER IMPROVES ITS PRODUCTIVITY IMPROVEMENT UNIVERSITY'S SENATE SUEED LEATHER BELT CONDITION THAT YOU HAVE TO REMEMBER IS ITS ELEMENTS IN JUST 1 PROVEN FOR AMAZING HAVE ANY DEVELOPMENT WILL ADD POTATOES BENEFITS WHICH HAIR AND WHERE IS ONE SUCH Beneficial and take care C Rollie zips off elements from ski village while thinking that among which for elements and difficulties in this country should be taken for itself IS Great Britain's swift to elements in description Bluetooth settings and that this team remained element and tagged Definitive Edition Dated I Election Gift Second Edition Vishwavijay Is Grade Salary Senior Vice President of Services President and Cases Pay No Vacancy List Will Be Greater Than Cases of Versus Respect Is That Twenty-20 Match Second Edition That Twenty-20 Match Second Edition That Twenty-20 Match Second Edition Softwares and Terrorities Condition Not Satisfied Subah World Will Have gifted meeting me bill paid when and post value in his stepmother brawn is this yagya na effigy skin from this note z10 tag for movement reverse perform ratan laxative one five years in this sacrificial code of modal logic wait shrinking of directory serious and able to provide Co different software standard size and festival left minimum balance key and share you can see the first element will always be some yellow minutes of liquid behavior funding for the New York is Daru left minimum of I is equal to the previously even element and the current element drawn from These sections refer to this element follow back to my minus one and these particular elements of wave condition in this creation and withdraw subtraction more return gift condition job also running from us loud name should learn from the last mix it well and 30 zoom in from this Further Condition Wild How This Back The Top Of The State Digital Is Lesson The Term Investment Increase In Symptoms News Simply Move To Celebrate Cannot Possible Pest A Hybrid Not Pear Will Remove Time Cost Is Not Until After Removing These Elements Of Weapons Were Formed Element Greater diversification of date is between so Sanjay and notification element and will return to bay to swift fear files will simply 8th values ​​then worry defeated and will develop will simply 8th values ​​then worry defeated and will develop will simply 8th values ​​then worry defeated and will develop Gurjar set a destination and is the nothing to avoid you want to specific status full screen whatsapp Status That A Yogi Ko DSP Academic Other Difficult To Explain Option More Such Boat Lift 191 More 80s We Theorem Any Crossroads Semi Most Wishes For Not Possibly Can See Otherwise Soch Can Also Be Used With Us Of Instances Of Five Explain The Most Popular Objection Certificate Zinc Co Pakud Solution Shades Right To Information And Welfare Office Rear Comment And Tried To See You Thank You For Watching And You Like This Video S Save You From All Shift
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
95
hello everyone in this video we will be solving the problem unique binary search trees 2. the problem statement is given an integer n return all structurally unique binary search trees which has exactly n nodes of unique values from 1 to n if you look at example number 1 the given n is 3 and we need to return all the possible combination that we can build using three nodes so if you look at this image these are all the representation of the tree nodes that we can build the first one is one then on the right we have three and then two the second one is one with the right leg of two and then a right leg of three there's one important thing that is mentioned in the problem we have to build the binary search trees which means that nodes needs to be built in such a way where the left leg contains all the value lower than the main node and the right leg will have all the values higher than the main node if you look at these images you will notice the same pattern if i take this the one in an example 2 is the main or the center node on the left we have 1 which is less than 2 and on the right we have 3 which is greater than 2. now let's switch to whiteboard and discuss the approach to solve this problem to understand the problem i will use the input as 4. to solve this problem i am going to be breaking this into smaller problems and then solve those smaller problems first which will automatically solve the whole problem so here instead of directly approaching the all the numbers cut it down into four sections let's start with one if i make one as my primary node or the main node all the remaining nodes will be on the right side of node one two three four the reason being is none of these numbers are smaller than one so i cannot put it directly to the left leg so the left leg will be null and all of these notes will go to the right just looking at the numbers 2 3 and 4 if i were to build a tree node i could do several combinations i could make two as my primary node i can make three as its right leg and then three will have a right leg for four this is a valid combination i can do something like this 2 will have 4 as its right leg and 4 will have a left leg for value 3 right this is a possible combination given i am using 2 as my main node now if i try to do something for 3 as my main node i can only have 2 on its left node and 4 on its right this is a valid combination another valid combination is 3 will have a right node of 4 will have a left node of 2. this is also a valid combination because we are not breaking the binary search tree rules so we have already seen i can make two combination if i'm using 2 as my main node 2 combination if i'm using three as my main node and if i were to use four so this will look something like four force left leg will be three and three's left leg will be 2 or i will have 4 will have a left leg of 2 and then 2 will have a right leg of 3 again this gave me 2 combinations so with 2 3 and 4 as a right leg of 1 i was able to make 6 combinations only with this as we do not have any numbers less than one the possible combinations that we can make with one as our parent node is six i hope you were able to understand how we broke it down into smaller sub problems and then solved it separately let's try to do another iteration with the same approach now that we have completed first iteration with the primary node as one let's try one with two so with 2 as my primary node i can do multiple combinations one combination will be i will have 1 on its left leg and the remaining numbers on the right which is three comma four or i could do two with a left leg of null and right leg will have everything 1 comma 3 comma 4 right because that is also a valid pair i can do something like 2 as my primary node i can make the right leg as null and on the left leg i can put all the remaining numbers 1 comma 3 comma 4. please remember the reason why we are able to put a null on the right leg of 2 even though we have 3 and 4 is because we have a number which is smaller than 2 which we could use to build a newer combination earlier when we were doing it for 1 we had no number which was less than 1 all the numbers were greater so we could not do a combination where we could put a node on the left side of one so these are the three combination that i can build with two as my primary know now just like the approach we took before we need to solve these nodes these combinations individually and find out how many pairs we can build let me try one as an example so if i'm looking at this pair two on the left hand side it's only one so i cannot do any combination as such but on the right hand side because i have 2 i can do multiple combination so 2 can have 3 as its right node and 3 can have 4 as its right node that's one combination the other combination is 2 left is 1 i can have 4 as its right leg and then 4 will have 3 as its left leg so this is one combination that we can build so for this setup we can build two combinations similarly let's try for this approach now so with two as my primary because i have null on the left there's no combination involved there but on the right hand side we have three numbers so we can do a bunch of things the right leg of 2 should always be greater than itself so i can have three can have one on its left four on its right or i could do two then it will have four as its right leg and then four can have three on its left and three will have one on its left this is also a valid combination well let me see what else we can do yes one more thing we could do is if i just open this part up instead of having three and then one and four i can do something like three then four and then four will have a left leg for one that's also a fair and valid combination so with this setup we were able to find out three combinations so now i will have three here similarly if i try to go with this approach here it will also get me three combinations so my total result so i will have 3 plus 2 which is 8 plus 6 is 14. so far i have 14 combinations just like we did for 2 we need to do it for 3 and 4. just to iterate once more we solve this problem by breaking it into smaller sub problems and solving individual nodes separately and then at the end adding the result together let me show you the c sharp implementation to solve this problem using the approach that we discussed just now here is the c sharp implementation in the main method i start with a validation to check if the input that is provided is not equals to 0. if it is equals to 0 then i return an empty list else i call this dfs method which requires a start and an end if my start value is greater than the end value i return an empty list if that condition is not satisfied we get into the main implementation where i have this loop running against all the numbers starting from one all the way to the end provided by the input and separately we build the left nodes and the right nodes if my start is 1 for example all the left nodes that i could build will be collected in this left list variable which in this case will be 0 because there are no nodes smaller than 1 and on the right list i will have all the combinations or three nodes that we could build with the remaining nodes once we have the left list and the right list built then we iterate through all of this combination like one at a time like one combination of left against all the combinations of the right and at the end collect all the values or all the nodes and return them in those combinations we build a new tree node with left and right values and return the result there is always a possibility that left is null or right is null which still makes up a valid pair after the iteration is complete we return the result which will have all the unique combination that we could build i hope you were able to understand the solution and the approach that we took to solve it if you have any questions or concerns please feel free to reach out to me i will be adding the link to the source code in the description below you can check that out as well and i will see you in the next video thank you
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. **Example 1:** **Input:** n = 3 **Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 8`
null
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
96,241
1,722
hi friends uh let's have a look at problem 1722 minimize Hamming distance of slap operations so in this video we're going to explain a solution based on the strategy split and comparison so first I'm going to digest the problem statement and the requirements and then we analyze um the algorthm and finally we design the code uh first let's look at the problem Digest so here we are given two integer arrays one is source and the other is Target uh they have the same length M so we are also given an AR R called aot slabs where each element is a pair let's say AI b i indicates that we are allowed to slap the elements at index Ai and index bi so of AR Source right so note that you can slap element at a specific pair of indices multiple times and in any order so the hming distance of two ARR of the same lens is the number of positions where the elements are different so here we want to find and return the minimum Hing distance of sauce and a Target after performing any amount of swap operations on a resource so here we have uh three examples and the last one is very special because we can swap zero and four and two and uh four and one and three so we can freely Swap all of them so for the source it actually is a set in some sense it has unique elements so 1 2 3 4 five Target also uh is also containing 1 2 3 4 five so the output is zero so this is a example three um this is very special I would say that's not catch the general case so for example two because a lot of slap is empty so we cannot do the slabs we can directly compare the Hing distance so we see the first position the both are one so same the second position different count by one and the third position is different so we have count by two the last position 4 four the same so we return two for this one and uh for the first example I would say uh it's still not catching the general uh test case so I'm going to specify this point when we do the analysis of the algorithm so here we have 1 2 3 4 and the target is one 2 4 five so here we can slap 1 0 1 and two and three so here you know one two uh index indices corresponding to one two in both thoughts and targets so if we slap once we get two one so these two positions can be the equal so for the last two indices three and four and five so we can make the four the same but still the last position have three and five they're different so we return one so this is the example one so before we do the analysis let's also look at the constraints so here I want to emphasize the length n which can be as large as 10^ 5 so for all the other ones are just 10^ 5 so for all the other ones are just 10^ 5 so for all the other ones are just some consistency assumptions we're not going to go over the items so with that said we finish the dest of the problem so now let's look at the analysis of algorithm so this will be the main part I would say uh understanding the algorithm is a key uh for this problem well doing the coding or design the coding is rather straightforward so now I uh let's look at the algorithm I'm going to use example one as a demonstration right but I want to comment also on the general case so we use uh two step uh three step operations so I start from Step Zero uh we split the indices to clusters according to the allowed swaps right so for example uh in the first example zero and one this these two index are in the first group two and three are in the same group notice that the indices are unique so uh we can do partitions for this um indices so we get C1 let's call it C1 is 01 and C2 and 02 so this is Step Zero then in step one we're going to reduce the problem to comparison of two dictionaries so these two dictionaries actually have elements and they are cons frequencies in other words so in the first Example The Source yield so the first two element of the source will be one two one appears once and two appears V well in Target the first two elements uh two indices gives us um two corresponding to uh two appears once and one appears once so here the key is the element and the value is the frequency right so this is C1 well for C2 they are corresponding to indices two and three so the source gives us three and four so three appears once and four appears once well in the Target um so we get uh four appears once and five appears V right so now I want to check for the two clusters how many elements we can make them the same or the equal so for inance in C1 the number of elements we can make equal so what how can we do this we pick the common keys and then we sum the smaller frequencies so this is the competition formula for example we have the common case are one and two right so we compute D1 one and D2 one we pick the smaller one and then we comput s for uh the K2 and then this the first item is one the second item is one so we get two in other words for this uh cluster C1 we can make two elements the same all right so similar for C2 so C2 the number of uh elements we can make equal first let's look at the common key so in this case we have only one common key that is four right but four appears once in each cluster uh in each of the two y dictionary so the minimum will be one this is also the number of element we can make equal and then we get the return so get the return we just need to use the length of the source or equivalently the target then minus the element we can make equal minus 2 so minus one so we get four minus 3 that is one so that's the basically the algorithm is very clear and very structured so now the question is why did we use dictionary in step one right so here the S is that the elements in the source or in Target can be not unique non unique uh this is also the point where both uh all of the three examples are not most or very general right so this is the question our plan will be the following um for Step Zero uh we can use unian to make this clusters it's similar like doing uh finding the connected components in a graph but this is very routine right you can use different methods so this is just a choice and in step one we can use counter and write a hyper function so again here you can do it in a different Manner and the step two is the return can be computed in different means but still lot of freedom for example here the length the if you sum the values you get one so that's the one so there's Z so we get two so some numbers we can make equal is two so 2 minus 2 is zero so for this one the submission of uh frequencies for the dictionary is also two and we can make one equal so 2 - one two and we can make one equal so 2 - one two and we can make one equal so 2 - one that is one so you add the zero and one together this another way of computing the return but this way looks to me more clear so we get we know the full length and then we minus the elements we can make equal the number of element we can make equal then this is the return so again you have lot of freedom so the point is that the algorithm is a COR and we have choices when we implementing or design the coding format so with that said let's make a quick implement liation of this uh algorithm so here let's use uh step corresponding to above right so Step Zero so basically split the indices uh into clusters or groups right so here um this actually correspond to connect the component if you want to make connections with the um graph so here we are mainly uh working with uh the variable allot the information allot slaps right so for this uh we can use a UNIF found so first let's get in the length of the source uh this just for communs so the length of the source and the length of the target is actually are the same so now let's write a Roots so here I just want to make some preparation for doing UNIF fend so here uh for I in range n because we are using zero indexing and Rex so here I want to give a full uh implementation of uh un Union B Rank and uh with also with pass compression in the F to i1 for I in range n so in this problem you can understand the one here in the rack is the cluster represented by the size of a cluster represented by see this KY or I so now let's look at the method for fat so function fat with pass compression so for this problem I guess we don't need to use this uh strong uh implementation but for general purpose you uh usage so we make it here so Define f give me a index so I can find its root so first let me introduce a uh root um I right and then let's use a Val Loop Val result and the roots are not the same then we just what we want to do basically set result to be the parents then what we want to return is the result because after the Val Loop so result and roots of result will be the same right so but you know we in order to accelerate this a little bit so we use P compression so we can apply or you can understand this Roots as a operation so we apply this both right so in other words we set the roots of result to be the roots of roots result so this way so here a result uh notice the typing is very uh important so let me check this function so we set result to be I and then ver result does not equal to root uh result uh then we're going to do result equals it's uh its uh root in other words we clim up along the chin so in order to accelerate a little bit we apply roots to both side of this one this is the so-called of this one this is the so-called of this one this is the so-called pass compression uh there are different way is to implement past compression here we just provide you one format so if you interested in looking at more of the applications or different ways to implement P compression you can check out my playlist uh for uni fand so this the uni F so that's uh the F method then the uh un function with uh rack right B rack sometimes called Union bar rack so the function so for this let's see Define Union so we got two indexes IG right so first we are going to get the root of the two indexes so let's just use the F because we have just implemented it f g right so what we want to do is that we check if the two roots are the same if I and G are already in the same class it means that their roots are the same so we do nothing otherwise we just do unit so root if root I does not equal to root G then what we are going to do so we check the rack so we want to uh set the root of the smaller rack to be uh to be the larger root so basically if rxs root I is no less than that of root G so here we are going to set the roots of root G to be root I that's what I just said and then we imp uh the increment the rack of um root I incr by that of root G so it means if you have a larger size you are going to absorb the smaller ones and in uh in combination with the p compression it actually accelerates the check for example given a index I want to find its root or its cluster so this will be uh acceler so if uh it's the other direction so we do the same thing but in the reverse Direction let me copy this part and made some all modifications so here we set the root of root I to be root G because root G have larger rack then they increment the rack of root G by that of root I right so that's the Union by rack function so this part is the so-called Union b r but if part is the so-called Union b r but if part is the so-called Union b r but if you do not do this also fine in this problem it just directly set say the root of root G to be that of root to be root I that's it right so basically if you do not do this then you just set uh root of root I to be root G or in the other direction then that's done this is a typical vanilla unit function but here let me delete this and I we do is by rack so um with that St so we finished the implementation of the F and unit meth uh function here because we didn't use a specific class so now uh what we are going to do so let's do uh another function let's see just a hyper function to get clusters or uh connect components so here let's define it as um get clusters right so here uh we're going to have a dictionary let's use this the implementation so here we can write one line implementation but we want to uh expose to you some details so here for idx and uh p in root uh Roots items so first I want to get U um so here is the uh index we know it's parents but we want to assign using the cluster name or the RO uh or the root so the root will be f p right then we're going to check if root in uh D so what we're going to do so we're going to root uh not root so D root so I'm going to add the index to the corresponding um cluster otherwise root is not in D so we're going to set D root equals a single element um set at present time so we are going to return d right so this is our um implementation so here so we have F function uni function we have another function is called um get clusters and then let's look at the problem logic so I'm going to do unit operations by looking at the allot swaps so for IG in allot uh swaps so what we're going to do we just do Union IG right so this will ingest all the information contained in a lot swaps so I'll regard this one as Step Zero so next let's look at step one so step one actually reduces the problem reduces uh reduced to uh the following let me write some detail so what we're going to do within each uh in uh IND thises uh cluster right so we count the number of uh elements or we can make equal right so this uh is further is reduced to comparison of two counting dictionary or two counters so now let's specify this so here in order to write it in a Robos way I'm going to write a function to do this so what I'm going to do I'll get uh get a common right so given D1 and D2 two dictionaries so the two dictionaries are counter or just the general dictionaries so it's C element and frequency so the requirement is assumption assume that D1 and D2 containing contain same number of elements so here we uh with uh counting multiplicity of frequency right so in other words we just need to values sumission and to be the same number like here right the values submission the same so this is two right so this is very simple right as we mentioned here um we are going to pick Comm case and sum the smaller frequency so uh let's say I just need to iterate for one dictionary right so for so let's say result equal zero so the result we contain the number of common elements we can make equal and then for K in D1 right so if K in D2 right it means a common K so we're going to incremented result by minimum of D1 K so because K is already in D1 this is a reasonable and D2 key right so actually you can also use the fun the get method with default value in dictionary if you like so dictionary get the key and then default value typically the use case is like we um we search a k d uh let's see get um see the K is one right if one is not inside we're going to set it to be zero so this is General use pattern right so then we are going to return the result so now with those functions ready so let's look at a step two uh step two is get um the return right so for each cluster of indexes so we call the above function uh get common function and then uh we get the number of elements we can make equal then we use the total length of the sauce minus those numbers so we get the return so first let's get the Clusters so this let's call get clusters right so notice that we call this function after we do the problem logic right do the uni operations so now let's do um so the number of elements we can make equal let's call it n equal initially zero then we it over the Clusters so for see in clusters so we just uh we are just interested in the sets all the values not the name of the cluster right so we got D1 is let's use a list comprehension Collections and counter right so then we find the elements corresponding to those indices in C that is Source I for I in C right then D2 is the same but we compute using uh Target right counter so let's use uh comprehension again so we get Target i 4 I in C right so this uh these are the two dictionaries we're going to call get common method so now let's see in common so the number element we can make common correct corresponding to the current cluster C that is get common all right D1 and D2 and then once we get this and then we get n equal is incremented by in common right for sure you can combine this two lines as a one line com combine this two lines as one line but without introducing the incommon variable but the reason we write like this way is to uh expose to you the details of s process so now we have all the information so after this follow Loop we know how many element we can make them equal that is in equal so what we just return is nothing but length of the source that is n minus n equal so that's the whole part so before we make any comments let's first do a test yeah it passes one example basically uh tells us our tying is no problem so now let's look at generic case yeah it passes all the cases so that's basically about the solution to this problem uh here now let me emphasize several points the first point we want to emphasize is that the algorithm is the core of the key well once we realize the algorithm we can do different implementations right depends on what we like for example this uh do the splitting so here I used the UNIF Fant but you can use different ones for example you can use um traversal Mi the re interpret the allowed slaps as a graph right that's also a typical method and then in the second uh in the Second Step so I Implement a simple utility fun function to do the job you can do it in a robust way and uh also lastly we can compute the output in different Fashions we can use minus we can use plus so we count how many uh elements we cannot make equal within each cluster then we sum so that's the related to the first uh major comment another comment is that in this problem if we analyze the three examples I found that they're not so representative I would see or so General so it's the correspondent to the case in step one because element are allowed to be to repeat right so that's why here we're using dictionary not a set or general list so this usage determines basically how we compute how many element we can make them equal so that's the mainly regarded to the second major comments so with the two comments uh shared I guess that's about it for this uh video uh if you like our video you're welcome to check out other problem in our Channel and for this problem here you know I Implement UNIF Fant so this is not necessary at all like we can use Rea Fant we can use Rea uni but here I used uni uh Fant with P compression and the Union by re is just to expose to you more knowledge or more technique so you can also look at different application cases for the UNIF Fant technique also known as this joh set technique or Thea structure uh in my playlist so we have a playlist in our Channel called UNIF Fant so it's actually uh nice to check out so with that said I guess that's it for this video thank you
Minimize Hamming Distance After Swap Operations
throne-inheritance
You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order. The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**. Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._ **Example 1:** **Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\] **Output:** 1 **Explanation:** source can be transformed the following way: - Swap indices 0 and 1: source = \[2,1,3,4\] - Swap indices 2 and 3: source = \[2,1,4,3\] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. **Example 2:** **Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\] **Output:** 2 **Explanation:** There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. **Example 3:** **Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\] **Output:** 0 **Constraints:** * `n == source.length == target.length` * `1 <= n <= 105` * `1 <= source[i], target[i] <= 105` * `0 <= allowedSwaps.length <= 105` * `allowedSwaps[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi`
Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order.
Hash Table,Tree,Depth-First Search,Design
Medium
2104
650
hey everybody this is Larry this is me trying to do an extra prom we got a couple of Yeezy proms today so we like to do something that I haven't done yet maybe it's easy but at least I haven't done yet all we're going to have a medium prom uh 650 2 key 2 Keys keyboard let's take a look hope everyone's having a good day I'm just kind of I don't know just chilling uh here on Feb 29 the leap day my LEAP day is doing one extra P maybe no but yeah all right there's only one character a on the screen of a notepad you can perform one the two operations you could copy R you could paste given it an N return to minimum number of operations to get the character a exactly end times on the screen H and it could be a thousand I was going to say maybe this is dynamic programming but I'm not quite sure um I mean well in this case I guess it doesn't it wouldn't be dynamic programming per se it could be uh bre first search I think it'll probably be bre first search um maybe yeah I mean I think this is one of those tricky ones I but yeah but basically for example you have a and then you can do a yeah I mean I think I would just do a bre first search right um I mean I want to say I think this also a DP solution especially since n is equal to a th but um I don't know which one's a little bit cleaner to be honest I think the conceptu the same it's just like the order of doing it because you can think about breath search as like a Bottoms Up dynamic programming so in that case I guess it's uh it's fine but yeah I think there is some observations you can make if you really want to be careful or like if you really want to be slick about this one I think there is some stuff like how many time can do you want to P paast in a row um I don't know what the upper Bal is but for example you wouldn't just like copy one a and then paste a million times in a row that would make no sense you eventually want to break up those pastes so um so yes by I'm going to do by first search and then we'll see right so we start with uh what I want to call my first state is going to be one Zer and this is a little bit thing where um it's a tle that represents um let me add a note so uh number of characters on the screen and then the second item is uh the number of characters in The what's it called copy bin or something I forget what the copy and paste thing is called in the copy buffer say right so then now we can go um yeah and then now we have q is equal collections. deck right we just have a view we want to pan start oops and for now I'm a little bit lazy so I'm just going to right look up right we can actually bang this a little bit tighter to be honest but I'm just a little bit laer I just want to focus on the problems I'm just going to WR look up on or like this is the best or the shortest path from here right so this is what look up is such a lazy name so maybe uh distance just go distance and fine right so and then now distance of start is equal to zero right then now what this is standard BFS stuff right so then now you have characters and maybe characters and buffer in q. pop left and then now you have two operations right you could add you could set B is equal to C right using the copy use to copy or so then now um then the toppo would look like um CC right if CC not in distance then distance of CC is going to be equal to uh I just say d is equal to distance of CP right uh D+ one right and this is of CP right uh D+ one right and this is of CP right uh D+ one right and this is bre for search so it's not in the distance this should be you know the next thing when you want to pen CC right and then now uh use the paste uh and maybe we could add a little bit of a not lazy B right so we have make sure that b is not is greater than zero because it's zero then I don't know I mean it wouldn't be infinite anyway because it would be in distance but it's just I guess it's fine I don't know and uh C+ B is less than or equal to n right uh C+ B is less than or equal to n right uh C+ B is less than or equal to n right so that we don't want to go over um and yeah and uh C plus sorry C plus BB not in distance then yeah then we enq this as well and maybe I could have had a unq function but it's fine right yeah and then the first time we hit if C is equal to n then we return p but yeah otherwise we want to return1 maybe I don't know I don't think that negative 1 is possible but yeah of course we this is very easy to put in some input so let's put in some big inputs and just run it real quick just to make sure that doesn't time out uh looks okay in terms of time 21 46 yeah so let's give a submit and that's pretty much it I think there is a dynamic programming Solution that's a little bit more cever um because I reg I don't I mean obviously I haven't done it this problem here I feel like I've seen something similar somewhere but that's so long ago I mean let's take a look at editorial then actually uh yeah so you have to pick it up okay uh oh yeah I I oh I see so this becomes a prime factorization one that's kind of cute um it's a little bit awkward but cute I suppose but yeah uh my complexity is going to be n Square um because the N Square state right because both this can be up to a th000 and this can be up to th I think in theory I don't know if all the states are POS I guess it is possible you copy one and then just go to a th and one and then a th2 okay fine so it's going to be n squ because that's the number of states each um each no only do two operations so it's fine but yeah the N is only a thousand so we don't have to worry about that solution but uh yeah that's all I have for this one let me know what you think and yeah all of n Square time and all of n square space yeah that's all I have let me know what you think have a great weekend everybody stay good stay healthy to your mental health I'll see you later and take care bye-bye
2 Keys Keyboard
2-keys-keyboard
There is only one character `'A'` on the screen of a notepad. You can perform one of two operations on this notepad for each step: * Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). * Paste: You can paste the characters which are copied last time. Given an integer `n`, return _the minimum number of operations to get the character_ `'A'` _exactly_ `n` _times on the screen_. **Example 1:** **Input:** n = 3 **Output:** 3 **Explanation:** Initially, we have one character 'A'. In step 1, we use Copy All operation. In step 2, we use Paste operation to get 'AA'. In step 3, we use Paste operation to get 'AAA'. **Example 2:** **Input:** n = 1 **Output:** 0 **Constraints:** * `1 <= n <= 1000`
How many characters may be there in the clipboard at the last step if n = 3? n = 7? n = 10? n = 24?
Math,Dynamic Programming
Medium
651,1033
79
Day 23 years see the play list, my name is Mukesh and you are seeing the ticket, so today I will explain the question to you, take the question sample, we have been given admin 2nd grade and this board we have is Brahmeshwar Do, the question, I will bore you and both. If it is kept then I have to find ABCD and I cannot use one of them repeatedly. It means that if there are two particulars on the board then it is a different matter. If I cannot use one of the particulars repeatedly and I can only go up or down and move on to one. I can go back, neither can it be changed in hero, it can be changed in the plus or minus column, so we will use it through backtracking and records and in this, I have pointed out where our words are coming from. So I got this, now after one also came, that is, after looking up and down on the right, I got some BCTs. Okay, so many of them, I first used subscribe news to get all this, if I see the united word, world latest. Baby will take it directly and it will be ours, so I have made it earlier because it did not take much time to explain in this way, so we got it done, so I have made it and this is the length and the elements of a particular list marked on the side of the board and the ones behind. Hey Pat, what do we mean to follow, I have taken it ok, so this is a difficult work, till the return answer comes, we will back it reciprocally, I free it from this, the work is going on from here, actually ours. The work has started, so what will we do now that we will make those travels in the row and column, get it nitrated and if the defense stops our volume and zero, I will never tell you, I mean, if it is right then return to it and if all this is not possible. If it is then return forms, it is a two piece app, so actually BF goes inside it, then we have stop volume, come which is our current character, right in the target world, so if this length is equal to length, it means return the liquor. I will give, okay first, this is done, if now we have seen a lot of how to return the voice, if you listen to Dahi then refer system to Rupam, then do the pull operation, okay and then recheck, so till this point, see BF, I then Called from then how is it that it came for Paul if the rosary daily is less than zero the stop volume earned from column 0 is it more than the churr and hips or not is our is going out of it ok so this can't happen then In all this case, what is this infallible if and for any other reason, it is not equal to the eighth board of the board, it is not only the eighth board, it is set in the Pat, so it is such that this subscribe means it should not be the same RC. So what did I do to clear out A? So keep this thing in mind that Adi A or again if it is in P or not already read, it means there is a problem, repeat and if there is then pause return, then it is okay. What should we do? By adding, RC will be the answer. Now we like everything and school and whether we are getting any of these soon, now I am getting the example here, by doing this channel is having to do more. Because it is kept below, check the current here, subscribe to us and that will be something in it, the only thing is that if it is two, then it should be returned, otherwise it would fall, so we had to hydrate that this is the direction of both of them. This is not an addition solution, if I do n't have a mint, then it is definitely being felt, along with the funds given to us, this is the function of Joe Davis, what are you doing in it, if you are calling then it will depend on the length of the word. If you are calling Ka or four times then the forest power has become long then the word that whatever will depend on the lens then note that the app is not much addition but still a solution, I have run it and submitted it, there will be no problem. You will also get the link in the description, go and hit check and just keep doing it. Want WhatsApp, New Delhi Video, Mukesh Yadav and take good bye.
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
198
it has been asked by Cisco Apple Amazon Google Microsoft Bloomberg by Dan database Yahoo infosis Walmart L micro vfo Lindon and so many companies hi guys welcome to this video good morning uh we'll see this problem House robber although it's marked as medium but if you had watched DP series or recursion series or basically anything in general related to DP then you should be actually able to grasp the actual intuition and logic behind this why it is actually a DB let's see from very scratch it's very easy very short video uh so basically you are a professional robber planning to rob houses along the street so you are a robber I know that you have robbed your ex's heart but yeah uh like you have to now Rob the houses now each house has a certain amount of money that is stashed and the only constraint stopping you from robbing each of them is adjacent houses have security system connected and automatically like contact the police if two adjacent houses were broken into the same night so we just want one thing that we cannot Rob two adjust houses that's it else we can do anything whatsoever now we are given an integer nums representing the amount of money stashed into each houses return the maximum amount of money so basically we have nums are which is saying okay we have four houses 1 2 3 4 and all four houses have this amount of money stashed into them we have these as five houses and for every house I have such amount of money stash into them so now the obvious thing is okay if I'm standing if a robber is standing at any again for this kind of questions when you have actually again if you're actually familiar with reading questions then just put down like don't start dry running in the very beginning just put down at a point okay let's imagine I am a robber and I am at the specific aat house so I will have two options thinking I will have two options either I will rob this house or I will not Rob this house so firstly when you heard of this I have two options at an index the first thing which should have come in your mind is okay I can indirectly go and try this via recursion and for sure two options do don't do take not take Rob not Rob then for sure I can also apply DP now with this fact I know okay I have two options Rob this house or don't Rob this house so I know okay I can simply try all the possibilities using region and then I can also memorize that but what is that take not take as in like what is that Rob don't Rob so if I Rob this house so I will get this amount which is the money stashed into that house so I'll get nums of i as the amount but there's a constraint that if I Rob this house I cannot Rob the previous house so what is the maximum amount of money I could have got if I would have robbed up till the point of i-2 because this is i - one so for sure i-2 because this is i - one so for sure i-2 because this is i - one so for sure this will be i-2 so I will ask what's this will be i-2 so I will ask what's this will be i-2 so I will ask what's the maximum amount of money I could have got if I would have robbed up to the I minus 2 and then what if I don't plan to Rob this house okay if I don't plan to Rob this house all together then for sure I can easily go and ask what's the maximum amount of money I could have got up to the I minus one because I don't plan to Rob this current house so for sure I can start my robbing from the previous house itself this house itself I can start my robbing and if I plan to Rob this house then for sure I canot I cannot choose to Rob anywhere whatsoever the previous house so I'll start the planning of robbing from the previous to previous house which is the IUS 2 and thus you will see that if I plan to rob the house I'll start from the IUS 2 if I don't plan to Rob this house I'll start off from the IUS one and this is the only condition in the entire problem that my answer will be and again I want the maximum amount of money I could Rob so what I could do is okay answer will be maximum of if I plan or if I plan to rob the ath house and like what if I don't plan to rob the ith house this will give me the maximum value and again in a simple recursion you just simply apply this recursion and in a recursion you have a base case depends upon if you are starting your robbing like because recursion like you just pass in the recursive function and then you will pass in the specific I now if you pass this I as let's say n minus one because for sure either you will pass in as nus one or you will pass in as a zero so if you pass in as n minus one then the base case will be if I is less than Z return zero if you pass in as zero then the base case will be if I is greater than equals to n then return a zero but depending upon okay if the base case is this then you will actually have to modify it and do a i + 2 and I + 1 to modify it and do a i + 2 and I + 1 to modify it and do a i + 2 and I + 1 like this so that is because you will actually be propagating forward cool now okay that a simple base case to just incorporate at DP basically to just memorize that and how to my Mo because we know it's a take not take a0 one napsack kind of a problem so we'll just simply do a simple addition of one aligner that okay if DP of index is not one just simply return that DP it's a simple DP check and also memorize while returning the answer and this is the only simple code which you could have written so here you saw that I initialized my Global DP I initialize that DP with the size of n plus one although n is also good because we not going onto new indexes so n is also good but yeah for safety I usually by default without even reading just in plus one but it's n is also good now I just as you said I started off my robbery from the last index that's the reason my base is my base index basically my base value is base condition is if I is less than Z then I'll simply return a zero now uh this is a simple memo check this is a simple memo assign and the main condition is if answer is answer simply maximum of if I plan to rob the I house or if I don't plan to rob the I house that is the simple check which we could have and ultimately we can get the answer and as you can see it's a simple memorization so I'll for sure go on to all of my indexes only once because of this so for sure my time is O of N and I had to make a DP of NR of size n so my space is also o of n can we improvise this now as soon as the improvisation picture comes in DP we have to convert that to bottom up so we'll just simply convert this exact relation to the bottom upper relation exactly same we'll do nothing else here I will simply write DP of IUS 2 here I write DP of IUS one and that's it so for that now base condition will always be there that base condition you will have to make for bottom of you will have to make a base condition so how will be a base condition now base condition will be if I have see you remembered okay if I am at the I index I am planning to go on to DP of IUS 2 and I'm also if I don't take it then I plan to go to DP of I minus one so for sure I should be having starting two values starting two DP Val I should have then I can start off my values from IAL to 2 I can start off from I equal 2 for I equal to 0 and I equal to 1 I need to have my DP values so I'll just say okay if I only have one house so for sure I will just steal that house so okay if I equal to Z then my DP of I is nothing but my nums of I which is the DP of 0 is nothing but my nums of0 that's it but if I have two houses 0 and 1 then I want to know DP of 1 so again I have two options either I can steal this house DP of one then my answer can be my nums of one or I can skip to steal this house which means okay I'll just skip it so my previous value whatsoever is there is actually num of zero then okay it's nums of zero and again I wanted maximum amount of money so I'll take the maximum so this can be a DP of one so it is a simple base case which we can have okay DP of 0 is nums of 0 and DP of 1 is maximum of nums of one and nums of zero and after this having a base condition we can simply start off our DP with saying that DP of I is nothing but maximum of DP of i - 2 plus nums of I or maximum of DP of i - 2 plus nums of I or maximum of DP of i - 2 plus nums of I or my DP of IUS one and this is the exact same condition which we saw in recursion also exact same condition so but it's just the difference that we have to make the base condition by ourselves so we just look at the code it's exactly same that we initialized our DP again we don't need to put it as n plus one we can also just do it by size n and here I said okay if my DP of 0 will be nums of zero I just added okay if n is one itself which means I only have one house then simply return my DP of 0 or simply return my nums of Z so I'll simply return that but if not then I will also have to put other B condition which is DP of 1 so I'll just go and check okay DP of 1 will be maximum of nums of zero and nums of 1 and then I can start off my integration from I equal 2 after less than n my nums of I which means sorry my DP of I will actually become maximum of nums of I plus d IUS 2 exact same condition or DP of ius1 and whoever is maximum this get that and put it in my DP of I and simply the DP of nus one because ultimately we are going in from the left to right to up to n so n will actually be storing the maximum amount of money I could have stashed if I end at the N minus oneth house now again the question was optimization did we optimize no still we are using o of n time and O of n space what the hell we did by spending our time just modifying the although the modification was a bit less but yes still we modified the Cod it's like how is it useful you will see that in this to actually find the value of DP of I you only using DP of i-2 and IUS one so in only using DP of i-2 and IUS one so in only using DP of i-2 and IUS one so in total you just need three variables instead of the entire array I could just use three variables let's say current let's say previous two let's say previous one and that's it so I can just say that okay my DP of 0 is in the beginning previous right it is previous two it is previous one so I can just do one thing okay rather than my DP I can just take a variable just a variable integer previous two here is here it's integer previous one and this will actually become my DPF I let's name it as a current so my current will become maximum of num of I plus previous 2 comma or like this plus value comma previous one and simply after this is assigned just say that okay your previous two will actually become a previous one and previous one will become a current with this you are simply assigning your three variables because you know you will only be using these three variables to find the answer so as you can see I just did a small modification of using three variables that's it I remove the entire array this is gone I just used previous two and previous one the above modification I showed that is here I assigned I used a current and then I assigned for the next iteration I assigned my previous two PR previous one correct values which means as you can see here it is previous 2 here it is previous one here it is current for the next iteration here it should be previous two here it should be previous one and it should be current so basically you can see my current I my sorry my previous one I assigned to previous two so you can see my previous one is assigned to previous two and my current I assigned to previous one I current assigned to my PR previous one and this is the current value and that's I can simply by using three variables I can reduce the days time will still be taking offn because I have to go on to all the houses all the indexes so time is still offn but your space is reduced to o one and that's how I can simply get this Sol I hope you all right goodbye take care
House Robber
house-robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 2:** **Input:** nums = \[2,7,9,3,1\] **Output:** 12 **Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 400`
null
Array,Dynamic Programming
Medium
152,213,256,276,337,600,656,740,2262
1,448
Hello hello confusion problem cigarette problem which is equal good nodes in this problem this is account number of date only what is sagunwa edison old is gold and have decided to go from druitt fielder curan and isi not able to find any value greater than that Particular nodal on the 5 minute jaggery laddus identified in explosives example witch month phalgun us flat syrup first modified inspire guddu many places notifications from drought in this particular view all events and sp sudhir very great event 5 from the bittu five ko will get upset So Single Twitter Guddu Recited A Perfect Example Retail Price Tag Ur No d500 Which Alarms Apart From Root Select Market In A Different Color Clove Five From Root Tan Rate In 2050 Is The Maximum Video Wellington Taste Fruit Maximum Manual On The Path From Drought And Flood In It's Good To Know From Drut Sudhir And 500 The Problem 5 From Root Til-Til Whole Teams Problem 5 From Root Til-Til Whole Teams Problem 5 From Root Til-Til Whole Teams Research Spot Execution On It English Part Vacancy Late It When You Visit A Greater Than To Go To The Maximum On Defeating To -Do List Not Good Values ​​Are Defeating To -Do List Not Good Values ​​Are Defeating To -Do List Not Good Values ​​Are Available In Love You Too Cannot Be Decorated Width Maximum Welcome To Do Not A Good Example Node From The Root 250 666666 's Note Serial Left Side Par To Rahani Dheere Beech Roly 's Note Serial Left Side Par To Rahani Dheere Beech Roly 's Note Serial Left Side Par To Rahani Dheere Beech Roly Poly Cheese Pages Marked Only Root And space mission and there water left side by five wickets don't fall under this particular path so let's even in an example you have three not three a good to no that defined from the root these arise from year to year is the value rest house Minister Ko Is Trick Just Balance Britain Serials Is 500 Three Can Not Be A Good Two Three Do Suhavani Guddu Bhaiya Aka In This Particular Example Miyan One Two Three Four Fauj Sir Answer In Which Software Chile Solve It's True For Solving This Question Previous Video Studio Festivities Notes Adventure Life With Attachments From The Saathi By Performing Defiance Particular Mode Left Noddy Spider Maximum Balance Or That [ __ ] Balance Or That [ __ ] Balance Or That [ __ ] President Coaching Facility Maximum Person Popular Scene For This Particular Load Dispatch Plan Will Visit Loop Ravi Visit This Website And Destroy And Maximum Volume Account This Account Dr To Samay Moments Fine And The Current No Deposit Greater Than Equal Two Sided Love Account Is Vansh Sunidhi Chauhan Summit-2012 Return OK Account Is Vansh Sunidhi Chauhan Summit-2012 Return OK Account Is Vansh Sunidhi Chauhan Summit-2012 Return OK 9XM B Travels Left Front Apni Travel Act Which Destroyed Pura Who Died In Government Will Change Your Vaccination Final Year Math Solution Vikram Tank Ok Khud That Means That Is The Current Have No Control Handed Over Left Ruk Next Visit The Best Value Images Safe Elegant Syrup Tennis Greater Than Equal To The Current President Android 1600 Account Will Change Account Gradual Wealth In Swift 3 Good Note In Election Vote Will U Will Back Track Playback That And Will Visit The Rise Of The Apps Visitor Of Child Into What Is The Value Of Birthday To You To Do Available Suvvi Abstract For Years Will Be And Will Be The Subscribe Welcome To The Year Award Winner But You Will Be Updated On Celebrate Winter Fest At Alarm On Network10 But When You Come Back Here's What Will Happen When You Come Back To This What Is The Max Vray 3ds Max Its Significance For This Current Statham Axis Pages Important Only Festival Max And Every Particular Step OK Super This Particular Statement Subham Paanch Sunavai Nivedita Right Now You Will See The Value Vijay Equal To Chhetarlal Images Equal To 6 Yours Pair Update Amazing Account Only This Particular Loop Chelsea 300 You Will See The News Free From All Attainments And Its Values ​​63 From All Attainments And Its Values ​​63 From All Attainments And Its Values ​​63 Smaller Than 600 Unit Trees Nodal Good Will Back From You Will Gain From China And Finally Bigg Boss Luti Aapko Return Policy And Answer User Name Shoulder Function For Its Ok And Start Coding Vaishnav Main Tere Montu Dabangg Calling Part 2 hua hai hua tha 220 without declare function will go into force on work answer soldiers declare school cent will initially magazine force and which can act and subscribe to a good night and you will have to pass through which will you have and current account Witch OK schedules and her husband music player free mode turn on its roots voted for mid-day meal account was later mid-day meal account was later mid-day meal account was later click this point to maximum roots value for this channel aspecific and only value will be noted tabloids and roots red chilli a condition For a Professional You Can Simply Zinc from Twitter Account 120 Otherwise Fruit Ride Point from Zu-Zu Tips Ninth Chapter Note Chal Okay I'll Give Zu-Zu Tips Ninth Chapter Note Chal Okay I'll Give Zu-Zu Tips Ninth Chapter Note Chal Okay I'll Give a Proof Of the Worst Thing Check the Value of Route Map for This Is the Law The Bhauji And Play List To Meet In The Bed And How To Make Function Call To The Left And Right Notes Anil Kumar Mintu Call The Left Child In Rent Flat For Boys Pass Bank Account Cheating Pass Balance Facility Updates Max For This Particular Posture And Let Me Just Cope Commission and let me clear in place of worship serial padru sprite value and finally download here account electronics its working hello friends point letter sensor flying series working roller skates indicator word solution thanks for windows 10
Count Good Nodes in Binary Tree
maximum-69-number
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good**. Root Node (3) is always a good node. Node 4 -> (3,4) is the maximum value in the path starting from the root. Node 5 -> (3,4,5) is the maximum value in the path Node 3 -> (3,1,3) is the maximum value in the path. **Example 2:** **Input:** root = \[3,3,null,4,2\] **Output:** 3 **Explanation:** Node 2 -> (3, 3, 2) is not good, because "3 " is higher than it. **Example 3:** **Input:** root = \[1\] **Output:** 1 **Explanation:** Root is considered as **good**. **Constraints:** * The number of nodes in the binary tree is in the range `[1, 10^5]`. * Each node's value is between `[-10^4, 10^4]`.
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
Math,Greedy
Easy
null
89
hey guys how's everything going let's take a look at number 89 of Leach code gray code the gray code is a binary numeral system where two successive values differ only one bit hmm given a non-negative integer n representing the non-negative integer n representing the non-negative integer n representing the total number of bits print exocrine soft gray code a great code sequence must became with 0 so for example given to the output would be 0 1 3 2 like let's start it with 0 and then we change one bit here it's 1 and then change another bit 3 and change the other beta here too and so there's not these solutions might not be unique so this is also valid - not be unique so this is also valid - not be unique so this is also valid - okay so for this problem we first can we should try to how to say let's first we get the basic example we zero so we remain input 1 how we should do it so there's only one bit there's nothing we can do so it's a zero right ok now we get for two bits what we should do for now for one we get 0 and 0 1 now what we should do for two bits this is first bit for two bits right for two bits our first bit there's only two possibilities for two bit alright that the first bits will be 0 or 1 right for the rest it should be the same as the one bit because we removed one bit so it will be 0 and 1 plus the n minus 1 solution right case right if it's zero then the value doesn't actually change it's the same as the M minus one case right if it's one then if you just plus one bit to the N minus one case all right yeah let's just put the let's take taking take two for example first we get is if this is zero then we plus the case will be zero and one right so you would be zero one now we set the first bit to 1 so it's 1 0 1 hmm and we just could free concat come connect them together catenate them together so it would be 0 1 but here's a problem for these two the actually the bits the changing bits is 2 which in you two bits so it does not satisfy our requirements how would you do that hmm the trick here is not enough on by me but it's fun by the definition here is actually if you take the if you look at the structure you know that this actually is the same as the this part right I mean I may remove the first 0 so the K I should say case and minus one it's a list right I should say list and minus one and list M minus one with a 1 right with one appended so if you take a look at the last number so this one and this one it should be the same except the first digit first bit and the change bit is actually one bit so these from this combination to this combination there's only one bed change and these is valid this sequence is valid so what we do is just we can reverse them if you reversed this will be the next number two this one will be this one okay and it reversed its okay and then we can do it over and over again hmm right so be probably become very simple so the result would be default to zero I'll keep the comment to make things fast results equals zero and four let's equals one ice and go to N what we do we get the previous result and reverse them and plus one bit all right so what we do the result will be push results slice it and then map them I have heard I need to reverse the reverse map item plus the bit a bit would be because for n 2 bits it will be 3 so 2 two and minus one right okay four it's so big that the previous speed okay this will be better n minus one hmm no oh yeah it for financing that second bit it should be two one yeah this is right so yeah that's not nothing well pretty simple right great result we submit the time here will be hmm no it's wrong answer wait a minute we've reversed we refer sliced yeah then reverse and plus the first one bit that bit would be for oh it's not and it's fine right oh yeah because we are getting results from 1 to n this one bit it's easiest is 1 this year will be 0 and this will be 1 so it's right we submit again cool accept it and the time here time what is time this is linear time and this we use 1/9 this is linear time and this we use 1/9 this is linear time and this we use 1/9 of code but actually there is reversed and map so it's linear so it's square and the space will cost as well the result 1 will run as a result so it will be 2 to the power n right there will be these kind of numbers yeah so that's all for this one hope it helps see you next time bye
Gray Code
gray-code
An **n-bit gray code sequence** is a sequence of `2n` integers where: * Every integer is in the **inclusive** range `[0, 2n - 1]`, * The first integer is `0`, * An integer appears **no more than once** in the sequence, * The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and * The binary representation of the **first** and **last** integers differs by **exactly one bit**. Given an integer `n`, return _any valid **n-bit gray code sequence**_. **Example 1:** **Input:** n = 2 **Output:** \[0,1,3,2\] **Explanation:** The binary representation of \[0,1,3,2\] is \[00,01,11,10\]. - 00 and 01 differ by one bit - 01 and 11 differ by one bit - 11 and 10 differ by one bit - 10 and 00 differ by one bit \[0,2,3,1\] is also a valid gray code sequence, whose binary representation is \[00,10,11,01\]. - 00 and 10 differ by one bit - 10 and 11 differ by one bit - 11 and 01 differ by one bit - 01 and 00 differ by one bit **Example 2:** **Input:** n = 1 **Output:** \[0,1\] **Constraints:** * `1 <= n <= 16`
null
Math,Backtracking,Bit Manipulation
Medium
717
958
hey everyone welcome to Tech quiet in this video we are going to solve problem number 958 check completeness of a binary tree first we will see the explanation of the problem statement then the logic on the code now let's dive into the solution so here I have taken an example so in this problem we need to check the completeness of the binary tree right so a complete binary tree can be defined as so each node should have a child except the leaf nodes so here we have child for each and every node right H sub D Leaf node then the node should start from as left as possible right it should be filled from as far as left as possible so in this case here we have 4 and 5 so when filling 3 here it has been filled from left first the left side has been filled of node 3 right so the left side should not be null when you have the right path so what I mean by that so for example if I have 6 like this then this case is wrong this is not a complete binary tree since the left is null but the right has been filled after node 3. so it's a compulsory that it should be filled from the left side first then it should be filled in the right or the right can be null but the left side should be filled compulsoryly otherwise it can be a leaf node right so now we will see how we are going to do this so first I will show you guys with the success case then I will show you guys with the failure case right so initially I will be having a queue which is filled with the root Node 1 in this case and I will be having a variable track which is initialized as false at the start right so initially I will pop the first the top element from the queue that is one so I will pop one and I will check whether this particular node is none it's not none right so I will append the left and right of one that is 2 and 3 right then I will pop two now so whether I will check it is none or not no it's not none so I will append left and right of 2 that is 4 and 5. right so I will append 4 and 5 in my Q next I will pop three right then I will append the left and right of 3 that is 6 and none the left is 6 and right is none right then I am going to pop 4 by left and right of 4 is none I will append that to my Q again I will pop 5 I'm going to get none again so I will append two nuns that is left and right then I will pop 6 which is again left and right or none I will append that to my queue so now again I'm going to pop the next top element that is none here so when I deduct none I'm going to set my flag as true and I will continue popping my queue so again I'm going to get none I will just keep my flag as true then I will just pop every element from my queue until my queue gets empty if my Q gets empty then we have a complete binary tree right now I will show you guys the failure case where we will see the effectiveness of this flag right so now I have a failure case where the left is not filled but right of 3 is filled right so now initially I'm going to pop the node 3 from my queue now I will append the left and right of 3 left is none and write as 6. right then I will pop 4 and 5 I'm going to get none for four and none for five so next I'm going to pop the next element from my queue that is none so whenever I deduct none I will set my flag as true right then I will just continue rather than appending any left and right I will just continue when I detect none then I will pop the next element that is six now I will write a condition within the loop itself if my flag is true which means I have seen a empty left before my 6. right then I will return false directly I will not run all these things I'll just return directly false right so before we pop the sixth there was none right which means we have seen a left that is what we have setting here true then we are popping the next element from the queue that is 6 which indicates that I have seen a left that is empty of a particular node then I am seeing a write has been filled for the same node it is an indication the flag is nothing but an indication that left of 3 is none right then we are checking if there is any node in my right if there is a node in my right then I am going to return false since my flag is true I am going to return false right that's how the logic is 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 initially I'm going to have an edge case if my root is none I'm just going to return true right then I'm going to have a Q initially it will be the root node then I am going to write a while loop until my queue is empty then I'm going to pop the node the top node from a queue right also I will be having a flag variable which is initialized as false at the start so now I will check if my node is none right if the node is none my flag will be true I will set my flag as true I'll just continue popping my Q right then if I deduct through in my flag within the loop then I will just return false directly right so if I have a valid case I'm just going to append my left and right of my node right then if I am done with the Q then I will just return true directly that's all the code is now let's run the code as you guys see it's pretty much efficient so the time complexity is order of N and spaces order of n as well thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
Check Completeness of a Binary Tree
sort-array-by-parity-ii
Given the `root` of a binary tree, determine if it is a _complete binary tree_. In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** true **Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible. **Example 2:** **Input:** root = \[1,2,3,4,5,null,7\] **Output:** false **Explanation:** The node with value 7 isn't as far left as possible. **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `1 <= Node.val <= 1000`
null
Array,Two Pointers,Sorting
Easy
2271,2283,2327
1,647
hi everyone welcome to my YouTube channel and in this video we will look at problem 1647 from Lee code so here is the problem statement try to solve this on your own before we look at my solution together if you look at the official solutions for this problem I think there were some people use like priority queue and hip I mean that certainly Works um but um I think this approach is a bit faster and this is I think this is a lot simpler to think about I think in the so this is one approach and if you want to learn more about other approaches solving this problem you can go to that comment section uh discuss section for this problem and you can read what other people wrote for this there I mean you can read what other people wrote for their Solution on this problem I think it is helpful to have different ways of solving this kind of problem let's look at my solution then so we are given a string s and we just we want to First count how many times we have seen like these individual characters so in other words let's say our example is like this bunch of letters we have three A's Three B's three C's three d's and three E's so this is our s the first thing we will do is we will initialize an array we will call that an array counter and this counter has a length of 26 and that's because in alphabet we have 26 characters so and then we initialize them to be all zero now and then the next we will be iterating on our s and then for each letter we will you know update our this counter array so this 0 will correspond to the number of times we have seen letter A the one like this index one that corresponds to letter b and we will see we will count how many times we have seen these so far so the way we do that is in Python we can use this old like old function so what it does is I think this or the like letter a is it gives you like 96 something like that so and then B will be something like 97 c will be 98. in this case we have e like S Sub 13 is e for this example order of e minus order of a will give you like something like 5 or yeah should be five yeah and then we will update that by adding one to the existing value and then when you do that on letter s we get something like this so we have threes for the first five positions and then all zeros for the rest okay so that's the first step and we will create a set so we will have a set and then we will iterate again on our counter array not s but counter array and we will do the two things if so we as we iterate on this if this number three is not in our counter set then we just append we add that number to our counter set and we move on to the next one now the difficult case is when the count is already in the counter set notice that if that's the case then we have to decrement our current count by one and see if that number like so in that case will be count minus one if it is still in our set if it is then we do have to decrement it again and then we do that until we either have okay situation where the new number the modify number is not in our counter set so we add that to our counter set or it becomes zero so either we won't test one of those two ways that this will happen so let's look at some like you know small simulation of how this is really working so this is our counter array and then this one is our counter set and then here we have a number of deletions and this system the answer that we will return and so we are on our first number and because our counter set is empty so we just add this one to our counter set and the number of deletion is zero because well there is nothing that we didn't do anything about like decrementing these numbers though number of collision is zero now we will be at B now 3 here for B the value was three but notice that uh we already have three in our counter set so we do have to decrement this number by one that will give you two and two is not in our counter set so we add cut we add two to our counter set and we update our number of deletions by one basically since we decrement this by one we do have to increment our number of deletion Pi one now we are on C notice that three is already in our counter set that's from a so we do decrement this by one so that's two but two is also in our contracept so we do have to decrement this again and one is not in our counter set so we do add one to our counter set and we do have to increment number operation by two so because we decrement this twice so we do add two three existing number of deletions so we get three now we are at so this one should be here so now we are at Fourth position T and so three is in our set with agreement this again two is in our set decrement is again one is in our set so we decrement this again now then we get zero but then zero is not you know in the problem statement it says zero can be ignored so here it says uh yeah frequency of zero is ignore so okay so we have a zero and well that's it we don't add and we don't add D to our counter set and but then we do have to make what three we do have to decrement this three times so we do have to add three to our number of deletions so that's why we get six if you look at the code so like that part where we do have to keep decrementing our counter number so that part will be done by like inner while loop so something like this so we initialize our counter array by this guy by this and we do the linear scan and initial like construct this counter array and then we have a result like this variable that we will return we have a set here and then as we iterate on our counter array we do have like the easiest cases if the number is not in our counter set then we just simply add the number to our counter set otherwise we do have to we so we create a local variable and then we have a while loop and then we will be you know keep decrementing count variable until we get either zero or if count is in our country set it's not in our counter set it when one of those two cases happen we exit the while loop and then we just add um whatever that new number count to our counter set and then we also increment our we also add the whatever deletion count we have to our result so that is for this problem and let's see the code here is the code and let's run this together okay so that is for this problem um if my video helps you guys understanding this problem please subscribe to my channel if you have questions you can you are more than welcome to write out questions in the comment section and if I know the answer to your questions I'm more than happy to answer them if I do not know the answer I will just tell you guys that I don't know the answer um yeah that's so anyway that's for this video and I hope you guys have a great day and I will see you guys next time bye
Minimum Deletions to Make Character Frequencies Unique
can-convert-string-in-k-moves
A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**. Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._ The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`. **Example 1:** **Input:** s = "aab " **Output:** 0 **Explanation:** `s` is already good. **Example 2:** **Input:** s = "aaabbbcc " **Output:** 2 **Explanation:** You can delete two 'b's resulting in the good string "aaabcc ". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ". **Example 3:** **Input:** s = "ceabaacb " **Output:** 2 **Explanation:** You can delete both 'c's resulting in the good string "eabaab ". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). **Constraints:** * `1 <= s.length <= 105` * `s` contains only lowercase English letters.
Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26.
Hash Table,String
Medium
null
114
what's up everybody alitomhajin here and welcome back to yet another youtube video in today's video we'll be solving another medium question number 114 also called as platinum binary tree to link list it has also been asked on day 14 of may lead code challenge so let's get started given the root of binary tree flatten the tree into linked list the linked list should use the same tree node class where the right child pointer points to the next node in the list and the left child pointer always points to null the linked list student should be in the same order as pre-order traversal of same order as pre-order traversal of same order as pre-order traversal of binary tree now let us look at a few examples to understand the problem statement better the question basically says that we are given a binary tree uh this is the first example of the binary tree and we need to convert this binary tree into a linked list okay and there are a few conditions that are given the first condition is that the classes of the nodes that are used that is the tree node in the tree should remain the same okay and while keeping the same the right pointer should be populated for the linked list and all the left pointer should point to null all the left pointers okay this is the first condition that we have in the second condition what we are given is the order of the nodes uh of the linked list should be in pre-order traversal okay pre-order traversal okay pre-order traversal okay so in the first example what we are given the pre-order traversal would be given the pre-order traversal would be given the pre-order traversal would be one then we will have two then we will have three then we will have 4 then we will have 5 and finally we will have 6 okay so which is uh the order of the linked list that we are given that is 1 then we have 2 then we have 3 then we have 4 and then we have 5. so what we basically have to achieve is we need to convert this binary tree into a linked list in place without giving extra space okay so there is a lot of rewiring and changing of links present okay and whenever there is a lot of rewiring we prefer post order traversal right because in post order it is kind of bottom up approach that is in post order we first iterate the left sub tree then we trade the light right sub tree and then we iterate through the root okay so what basically happens is whenever we come till the root its left and right subtrees are already processed okay but the problem statement what we are given is uh we need the preorder traversal in the linked list the order of nodes and also we are given that all the right pointers should present with the next nodes and left pointer should be present with the null so we can basically tweak this post order traversal for our use that is we can uh initially iterate with the right subtree and then iterate with the left subtree and then iterate to the roots so that it helps us in solving this problem now let us look at this with the help of ibh method the ibs method is helpful in solving the recursive problems okay so this method has three steps that first would be the hypothesis step and in the hypothesis step what we basically do is we define the function and what our function will do okay so basically we will define our function let's say that it would do take the binary tree root of binary tree and convert it into the linked list and give me the head of the linked list okay so this is our hypothesis step now the next step is base condition and base condition we need to uh see what is the largest or smallest valid input where we need to stop the recursion okay so in our case whenever we reach the null nodes in that case we need to stop the recursion okay so that is the base condition now in the induction step what we need to do is we need to perform some logic such that uh this hypothesis comes true okay so basically what we'll do in the induction step is we'll uh say that we will look at just the current node what we are present on okay and if you look at the first step directly that is let's say we are on this what we need to do is we do not need to think of the rest of the subtree because it what it will basically do is it will return you a node that would be the head of the linked list of this rest of the tree okay so let's say this is the previous node okay so what we just need to do is we need to point uh the currents left to the null and currents right to the previous node okay and say that now i am the previous node and i need to proceed further okay that's it that's the solution now let us look at the code how we can uh implement it while defining the recursive function what we are the first step would be to define the base condition that is whenever we have to end the recursion and we just saw that whenever we reach the null in that case we'll return okay the next step would be the hypothesis step so here what we do is uh it was defined that we will take the root of the binary tree and we'll define how the recursion flow would be there that is uh before going uh processing the current root node what we will do we will say the right this is my right this is your right will say that uh take this right subtree and flatten it for me and after that take this left sub tree and flatten it for me okay and these would return me the head of the linked list but rather than returning i just created a global variable previous that would point to the head of the linked list okay so initially it would be null and after that what uh this was the hypothesis step these two steps what we just saw uh this would come in hypothesis now what we need to do is we need to do the induction step okay so this is what where all that magic happens so we just saw in hypothesis we do not have to look at the complete subtree we just need to look at the current node so we'll do its right so the previous node contained the head of the list linked list that was present so we will do uh the right to the previous that is the current nodes right to the previous that is what we are doing we are setting the previous value to the roots right okay after this we'll set uh the current what was present it's left to null okay that is what we are doing roots left we are setting it to null now we need to proceed further that is uh now we are now the current node whatever was present is done and we just need to proceed further okay so we'll just set the current node that was present that is the route to the previous and then proceed further in recursion that's it that's the solution and i have also run this code so uh this is the solution uh i mean this is the runtime and now let us look at the iterative approach so in iterative approach we'll use basically the stack uh in recursion there was a recursive stack so we just need to handle that recursion stack on our own in the iterative approach okay so this is very similar to like a bfs uh doing a bfs on the tree and making the linked list okay so basically in this uh there is one thing that we need to note here is that so uh what we do is we will take the stack and we'll push the root node and uh after that popping the root node will check the left and the right uh in the normal bfs okay but here what we need to notice that we need the pre-order need the pre-order need the pre-order right we need the pre-order traversal so right we need the pre-order traversal so right we need the pre-order traversal so the left part should be on the top whenever we create the linked list okay so which is why we will initially put the right into the stack and after that we'll put the left into the stack okay so what basically happens is that uh whenever we pop then the left side would be on the top and this will give us the pre-order version this will give us the pre-order version this will give us the pre-order version okay so now let us look at the code to understand it so what we basically are doing here is the initial line that we have is just a corner check that is if binary tree is null in that case we return after that we have simple bfs step that is we create the stack push the root into the stack root of the binary tree and we'll iterate while our stab while our stack does not become empty okay so whenever our in each iteration what we are basically doing here is we are taking the top element of the stack okay so we are taking the top element and pointing it with the current variable and then popping that element okay so as i said in the explanation that we need the pre-order so it's left that we need the pre-order so it's left that we need the pre-order so it's left part of the root that is left subtree should come first in pre-order okay in pre-order okay in pre-order okay so which is why we are just checking the right part first so that it goes at bottom of the stack so we are just checking if current uh the current pointers right is not null in that case we are just pushing that into stack and after that we are checking the left part okay so this is the right part right sec right subtree and then we are checking for the left okay and after that if it if left is also not null we are just pushing it into the stack so now our top of the stack would contain the left element that is if this was the iterator then 2 would be on the top of the stack now we are checking if stack is not empty and if it is not empty then we are updating the current right pointer because we need to make the linked list into the right pointers right so we are just updating current write equal to stack top now the stack top was 2 so 2 comes here after that we are just doing currents left equal to null because the write is updated now we need to update it to the null so that's it after exiting from the while loop we will have created the complete linked list i have also run this code and this is it this is the runtime and the memory uses so now let us look at the most optimized approach the previous two approaches that we just saw uh use of end time and off and space okay and but this morris traversal takes off on space now in the previous steps we use a stack or the recursive stack which was taking the space of n and basically let's see why was there a requirement of the stack now if you go from the root node to its left subtree for traversing then you need a way so that you can come back to the root node okay so if you go here then there should be a way to come back to the root node similarly if you go from two to three then there should be a way to come back again to two okay so this was achieved with the help of stack uh that is we pushed the elements and then popped again to get back to that particular node okay so in morris traversal uh we do not need that stack and in this uh how it is achieved is that we uh first fight find the in order uh predecessor that we have okay so the inorder predecessor is uh found by so let's say we need to find the inorder predecessor of one then we just go first left and then we go and keep on going right until we reach uh the leaf node okay so the inorder predecessor of this is four and then we create a link of this in order predecessor to the next node that we need to go okay so this just completely removes the need of the stack okay so now let us look at the code and understand how this approach works okay so what we are basically doing here is the first step is basically the corner check uh that is whenever the root is null we just return we do not have to do anything after that we are creating a pointer tree node pointer pointing to the root so let's just create that and we are calling it to the current okay so i'll just do it current after that what we are doing is uh we are iterating while the current is not equal to null okay so whenever current uh is not null we just go into the while loop the first check that we have is we are checking if currents left exist that is if the current null is not if the currents left is not present if the current's left is null in that case we do not have to check for the left right we just need to go to the right okay so if current left is not equal to null in that case what we do we just find the predecessor okay so what we uh for finding the predecessor in order predecessor what we just do we just go first left and then keep on going to the right so that's what we are doing here we are just taking the currents left into the previous and then uh doing a while loop until previous next previous is next is present okay so this is uh the process of finding the in order predecessor okay so we entered the while loop we checked if left exists and then we are uh doing finding the predecessor okay so after that what we are doing is in this step we are creating a pointer so that we can go proceed further okay so what we are doing here is uh so we reach previous to this step so for now four is pointing to the previous after this while loop okay so what we are doing is we are creating previous writes previous right to the current side so this was our current to the one so we are doing currents right uh equal to the previous right so that we can uh go to that afterwards after processing this okay so now after this what we are doing is uh this is a basic induction step that we need to do so that we are creating the linked list what we have okay so we are just doing currents right that is uh this uh what we have the pointer that we have we are just making it to the currents left okay now we are just starting to create the linked list that we have so we are just doing currents right equal to the currents left that is two would come uh to the pointing to one after that we are just doing currents left equal to null because it's the linked list left pointers are pointing to null so these are the two steps for generating the linked list after that we are just proceeding the current forward that is we are doing current to current of right and that's it that uh that completes the morris traversal and whenever we exit out of this uh complete while loop we are present with our complete uh linked list that we require so i have also run this code and it gives us this runtime that is four seconds four milliseconds faster than 86 percent and memory usage less than 33.25 and memory usage less than 33.25 and memory usage less than 33.25 so that's it for this approach and that's it for this video if you need the code link it would be present in the description uh if you like the video hit the thumbs up button if you need more success content do subscribe and uh that's all see you in the next video bye you
Flatten Binary Tree to Linked List
flatten-binary-tree-to-linked-list
Given the `root` of a binary tree, flatten the tree into a "linked list ": * The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`. * The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree. **Example 1:** **Input:** root = \[1,2,5,3,4,null,6\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100` **Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Linked List,Stack,Tree,Depth-First Search,Binary Tree
Medium
766,1796
732
um hello so today we are going to do this problem my calendar 3 part of lead code um September October challenge um so um what the problem says is we We have basically it's my calendar three here um and the definition of a k booking is when K events have some an empty intersection right um and we get some events that are noted by start inclusive and not inclusive right so basically an event starts at start and ends at end minus one exactly right um and after each given event we're gonna return an integer K that represents the maximum cable Kings between all previous events so basically K is basically the maximum number of events that intersect in so far yeah that's pretty much it so it will be a class like this um and we has one main function book with start and end and what we want to return is an integer K representing the largest integer such that there is um there are K booking in the calendar uh so far right so one booking may increase it or may not right so that's the problem here and the range is quite Big Ten to the power of 9 so that tells us we can do something with a loop from the numbers between for all the uh from start to end for example but one thing here is that the number of calls to book is an are not too big it's just 400. um yeah so that's the problem now let's see how we can solve it and maybe use this construction to our advantage um okay so let's take a look at this here let's try to um draw the first example and see um what it looks like so first we book 10 to 20 maybe let's say 10 is here uh 10 to 20. and then we book 15 to 16 maybe 15 is somewhere here so when we book 10 to 20 what should we return here um so 10 to 20 there is no overlap yet right so we have only one booking so we're a turn one that's what we're attend here okay when we book 15 to 16 still no overlap right no intersection so only one because each of them has one so we'll return one now we book 10 to 40 is like this so 10 to 40 something like this maybe okay so now we can see we have an intersection here between these two here okay so and that's the max one two and one so we return two here and now we take a look at 5 15. so 5 15 5 would be somewhere here um and 15 would be somewhere here now we can see in this position here we have three bookings so now with three two here and then one so we'll just turn three five ten um so 510 we want to do five here ten um remember start is inclusive right so what this tells us is that we have all of these um okay let's see why we have uh this one is not inclusive um yeah sorry so the ants are not inclusive so what this would mean is that this is not inclusive actually right so what this means is basically there is no intersection here because 10 is the end so it's not inclusive so this interval actually has up to a up to um nine that's where it's inclusive right um so here we have 10 here and then the 10 here so 3 as well so that's why we return three here now we add 25 55 so we if we add that uh 25 should be somewhere here and then 55 should be somewhere here right um so now this actually intersects with here right somewhere here 25 it intersects with this 25 and it intersects with this 55 right so here with this here we'd have just two with these intersections we have just two and so the max is still three so notice that it's not just like the intersection with this booking is what the max in all of the calendar so far and here it's still three now just looking at the drawing I did here this should there is a quite new technique called line sweep that exactly does this which is basically just you can because since these are horizontal you can think of like a vertical line that is sweeping all of the intervals um and how do we know the max well we know that when you start an interval now that intervals if there is an intersection it increases the max but when you reach an end right now especially here because it's open if there is a Max let's say three involving this interval it decreases right because this interval is no longer ended so we need to decrease and so what we can do with this line sweep technique is just every time we encounter a start so for a start we increase by one but when we encounter an end we decrease by one right and if we do this well we should be able to just go through it if we encounter two starts then we would add two if we encounter three stars then we add three and this three value will keep will stay there until we reach the end then we will decrement it by one and now we have just two right so that's the idea so that's what we can explore here well um and what we can do basically is just maintain some sort of array or a map of time let's call it and we can just go through our intervals for each booking actually we can just use um so a booking will have start and then end we can just say time at start increased by one and time at end decreased by one if this was a closed interval then we will Mark only n the plus one by minus one because the intersection can be at the end right but since this is an open one at the end we can we decrease at e exactly um and now what we can do is once we have the times we can just sort them and just go through them right um and when we go through them what why do we solve them first um so we sold them by keys by the way S and E so why do we sort them so that the sweep the line sweep here the vertical line sweep right what does it do it goes from the start and it just keep going horizontally in order right because we want we don't want to compare this and this we want to compare it in sorted order so that's why we do the Sorting here but this sort since this is a map uh time would be a map it will be using the keys here so it would be using s and end and as we Traverse we just want to keep a value of the current line intersections how to do how do we do that so we can just go through um let's say t inserted first time and this is by the way this is a map um and this is sorted by keys by start and then end right um so we can keep the value of like the intersections let's call it current so this would be the intersections at Point t so far and every time we just add current plus time at T what this will do is that here would have it at five so first when we counter the first five for the first booking it will be one we encounter the second five it would be um it would be two and then when we encounter the end here at 10 the current would be one because now there is only one intersection but then when we get this 10 we would increase it by one because now there are two intersections when we get here increased by one now there are three intersections right so current just at that line how many intersections we have and so since we want the max for each booking we just compare it with the best we have so far right so let's say we initialize our best to zero we'll compare the current number of intersections with the best we've seen so far this is for cases like the last interval where it's two we want to return the best we've seen so far which is three okay and then we'll return the best and that's pretty much it for this solution here um so you can the main thing here is to learn line sweep and learn that as we do have this vertical line um sweeping we can keep track of the current number of intersections yeah so I think that's pretty much it for this problem so let's cut it up and make sure it passes out test cases um okay so let's implement this solution here so the first thing we need to do is create our map that keeps track of the intervals so this would be just to avoid like having to check if the number is there we can slice it to in so that if a number is has not been added it's a zero and then here when we want to book a number with start and end let's just call this ascendant for Simplicity then what we said is that for S the start we want to increase by one for end we decrease by one because we that's the end of the interval this is not included so we remove it and then we want to sort um solve that time so we can actually just when we are traversing it into a solve that time and explore for each vertical line sweep how many intersections we have so let's say current is the intersections here and then we just add T so that would be adding either one or -1 and we do best is going to be the max of what we've seen so far and the current number of intersections so let's just initialize best here and then at the end we return best so the implementation itself is pretty straightforward it's merely visualizing how to apply it here um and in terms of time this would be all of um let's say n is the number of bookings so that's up to 400 number of calls to book so the number what we have in time would be um maybe two of this right because uh so 12 multiplied by n here and since this is sorting this is like 2N so roughly it's n log n so we start first and then we Traverse so n plus this um so properly n log n um is the time complexity here in terms of space we are using oven um extra space we are of to n which is roughly n um because we add every S and E um and N is quite small it's 400 so this would be should be reasonable so let's run this um unless um okay looks like yeah this should be solved that time sorry okay Los Santos um okay sorry this is not adding we don't want to add s or E actually we want to add the values um because that's what the intersection represents my bad um so it'll sit on this and last submit okay so that passes test cases um yeah so uh a very good application here offline sweep technique um yeah please like And subscribe and see you on the next one bye
My Calendar III
my-calendar-iii
A `k`\-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.) You are given some events `[startTime, endTime)`, after each given event, return an integer `k` representing the maximum `k`\-booking between all the previous events. Implement the `MyCalendarThree` class: * `MyCalendarThree()` Initializes the object. * `int book(int startTime, int endTime)` Returns an integer `k` representing the largest integer such that there exists a `k`\-booking in the calendar. **Example 1:** **Input** \[ "MyCalendarThree ", "book ", "book ", "book ", "book ", "book ", "book "\] \[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\] **Output** \[null, 1, 1, 2, 3, 3, 3\] **Explanation** MyCalendarThree myCalendarThree = new MyCalendarThree(); myCalendarThree.book(10, 20); // return 1 myCalendarThree.book(50, 60); // return 1 myCalendarThree.book(10, 40); // return 2 myCalendarThree.book(5, 15); // return 3 myCalendarThree.book(5, 10); // return 3 myCalendarThree.book(25, 55); // return 3 **Constraints:** * `0 <= startTime < endTime <= 109` * At most `400` calls will be made to `book`.
Treat each interval [start, end) as two events "start" and "end", and process them in sorted order.
Design,Segment Tree,Ordered Set
Hard
729,731
1,696
foreign welcome back to my channel let's continue solving Jump game problems today we will solve lead code problem number 1696 which comes under John Kim series only let's look at the problem statement you are given a zero indexed integer array nums and an integer key initial position is index 0 in one move one can jump at most K steps forward Direction without going outside the boundaries of the array that is one can jump from index I to any index in the range I plus 1 to minimum of n minus 1 or I plus k and these ranges are inclusive we need to reach the last index of the array which is index n minus 1 and the score is defined as sum of the all the values of num that is nums of G for each index J you visited in the array we have to return the maximum score we can get to reach the last index starting from 0 index now let's look at the test cases to understand it better I have taken the test case from lead code here K value is 2 that means from any index maximum two jumps can be taken we have to start from index 0 and keep on exploring all the possible cells we can visit until we reach the last index considering the maximum value of score as we have K options from any node to explore next for each cell we will consider the maximum score to reach a cell hence if we consider this as a recursion tree then it will have K branches in the tree now let's draw the recursion tree to understand it better it is mentioned that we have to start from index 0. so if my current index is 0 right and my value is 1 at index 0. then I can go to either index 1 or index 2 because I can take maximum of two jumps if I go to index 1 then what value I will be having or what value of score that I will be having 1 plus of minus 1 that means 0 if I go to index 2 then the value will be 1 plus of minus 2 that means minus 1. from 1 again I can go to either 2 or index 3. if I go to index 2 then my value will be 0 plus of minus 2 that means this one and from 3 if I from 1 if I go to index 3 then my value will be four from two I can go to 3 or I can go to index 4 if I go to index 3 my value will be 3 if I go to index 4 my value will be minus 8. from 2 I can go to index 3 or index 4 if I go to index 3 my value will be 2. or if I go to index 4 my value will be minus 9. from 3 I can go to 4 or 5 if I go to 4 my value will be minus 3 if I go to 5 my value will be 4 plus 3 7. 3 I can go to index 4 or index 5 if I go to index 4 my value will be 4 if I go to index 5 my value will be 6 from 4 I can go to 5 or 6 is out of the boundary so not possible if I go to 5 my value will be 5. again from 3 I can go to 4 or 5 if I go to 4 my value will be minus 5 if I go to 5 my value will be 5 from 4 I can go to 5 and 6 is not possible if I go to 5 my value will be minus 6. from here I think this is minus 3 right okay I can go to five six not possible minus 3 is 0 from 5th so I have already reached her the last index so nothing to explore from five or six not possible if I go to here it value will be 7 now see okay still I have four here right so five if this is minus five so minus 2 6 which is not possible right so I have reached the last index which is five and what values I have minus 2 5 minus 6 to maximum is still five and then zeros or five seven so this is a maximum value right so the maximum score to reach index 5 is 7 and which path we are taking we are considering this path I think we are considering okay this path we are considering that means the indices are 0 then 1 then 3 then 5. if you consider the values of 1 minus 1 4 and 3. if you sum all of them that is 7. so this is a recursion tree for this problem and as you can see we have the overlapping problems here because see multiple overlapping problems 4 minus VR um problems like for each field this is one overlapping problem 4 minus 3 yeah so we are exploring like multiple nodes so we are exploring single node we are exploring for the many times right so we have the overlapping problem now um took for the optimal solution as recursion approach is having overlapping problem let's look at the optimal solution now look carefully we have to reach the last Index right hence to get the score we have to consider the last index value if we want to reach last Index this value we have to consider great along with this value we need to pick the value from previous cases because to reach this index we can have options from any we can reach from any previous K cells and this is true for all the cells so if we repeat the same thing for all the cells we will finally get the maximum sum value to reach any index I starting from index 0 for example to reach last index we have to consider like how can I reach index 5 either from index 4 or from index 3. now to get the maximum score we have to consider value 3. right with this there are two options to reach index 5 either index 3 or index 4. and which one you want which value you want to pick we want to pick the maximum value right so what is the maximum of these two is four so we will pick 4. that means 7. now the same thing is true for this cell right so from index if we want to reach index for example if we want to reach index to this Index right so there are two options either I can go from index 0 or index 1. in these two way only I can reach index 2 right now to reach index 2 I have to consider the value which is at index 2 which is this value plus I have to consider the maximum of these two so what value I will consider 1 so this is minus 1. so this is true for this cell also the same thing we have to repeat so if we start from uh if we repeat the same uh formula for each of the nodes eventually we will get what is the maximum score to reach last index starting from index 0 let's write down this problem to understand it better or to understand how this thing works foreign my starting position is index 0 and this is a starting position right so the value is itself the score now next I can go to index one now how can I go to index one from index 0 only because I cannot go across the boundary of the array so I have to consider minus 1 plus uh there is only one option right from index 0 and the value is one only so that there are two so the maximum score to reach index 1 is 0. right so here um maximum value to reach index 1 is 0. okay we'll update this value now what is will be the value to reach index to I have to consider minus 2 which is a value at index 2 and then there are two options right one is from index 0 or index one now this maximum score to reach index 0 is 1. and the maximum score to each index 0 is the index 1 is 0 so I can take the maximum of these two minus 2 plus 1 is it is minus 1. now index 3 I have to consider 4 plus the maximum value of I can go okay let's update this value to -1 -1 -1 now I can go from index 1 or index 2. now what is the maximum value to reach index 1 which is 0 and maximum value to reach index 2 is -1 so this value will reach index 2 is -1 so this value will reach index 2 is -1 so this value will be 4. now let's do the process for index of four okay let's update this thing this will remain 4. okay so we have to consider minus seven and then the maximum value of to reach index 2 and reach index 4 this is minus 3 because I am picking 4 only now for index 5 I have to consider 3 plus the maximum value of I can okay let's update this thing to minus 3 okay I can go from index 3 with a value maximum score to reach index 3 is 4 and uh maximum score to reach index 4 is -3 I maximum score to reach index 4 is -3 I maximum score to reach index 4 is -3 I am picking 4 so the value is 7 3 plus 4 7 so this is the maximum value for each cell we need to find the maximum scope from the last K sales that for each cell we need to find the maximum array of size k Now by quoting we can sort or find the maximum for each cell and this will take order of key log K time to sort the array of size key hence the total time complexity will be order of n of K log K fine because we have n total n number of cells and for each cell we are sorting the array of sides key now this is a huge kind complexity now to optimize this thing we can use another data structure which is priority queue priority gives a sorted array and internally it used Heap data structure with this we can optimize the time complexity let's quote this using priority queue here we have given into any of non-teacher value of key so first let's non-teacher value of key so first let's non-teacher value of key so first let's take the size of nums a and as we discussed we will be considering a priority queue Cube and that will be a whether the current index which I'm exploring from the priority keywords Lines within the case or size or not okay and a priority queue is uh by default it is a maxi of the first Index right of the first value but here we are using a pair of elements right uh we need Max save but the maximum value maximum will be formed based on the second value from the pair so we need to write our own comparator logic so for that my own comparator let's name it with B Cube priority Q so pair will be and then okay divided index okay first I will push see you index and thumbs up see you that means to reach index 0 we have we got the maximum score which is value of nounsel 0. now let's take one index and loop it from one and it's an A9 plus So currently uh then in this way I will explode each set so my current value will be nums of I and we need to find the maximum score uh from the previous K cells right so we need to explore the priority queue until it is empty current index minus priority queue number first it's greater than e I will do the pop operation that means the even if there's a maximum value is present at the top of the priority queue but the index it is that means no of index of first of value from the top if it is that is the difference between current index and that index is greater than k then we won't be able to consider that maximum value rate so we keep on popping that moment and if price not empty then okay let us get one more value which well into my maximums let's 0 . ensure my maximum score will get updated too current Value Plus priority cube of drop of second right and then we will push pair of eye and its maximum score right once we complete this we will return so at any point of time priority queue is not self-sized key but at Max it will is not self-sized key but at Max it will is not self-sized key but at Max it will modify its key because here we are popping the unrequired elements right maximum now we have to write our own comparator so following the sentences that we use here that you had to take you here one pair two and as you know by default Max priority is defined in is implemented by maxit but whenever we have to implement it so mean here we have to send the comparator as a greater so it's kind of opposite notation that we have to send so they are one of the second of bear one if it is a less than then we will return true else okay I think this will work here let's run this again something syntactical issue okay it got accepted let's submit this code okay it's giving me wrong answer why announces minus one two three so single element expected minus one two three I see okay the max score here it will be nums of zero right because we are returning this submit because the single element right it got accepted so that's a that was an edge case so be careful of this Edge case uh Max code has to be in the shearized with the thumbs see you Ben test kisses like a single element okay this is an example of edge case right okay now to consider the time complexity see here we are running it for n number of cells and for each cell what we are doing here we are popping so that is fine right we are popping this thing so that will take order of log three time Plus here we are pushing right so this is again take order of log K time because at Max the time size of the 20 Cube will be one enough k so the total current time complexity is over n log K and base complexity is out of key now if we use sorting okay sorting your fruits then the time complexity was how much order of n of K of log K so here we have eventually optimized a Time complex setting right now here we can further improve the direct complexity how we can this is constant right we have to run it for each cell but we can optimize this part of the code right so if we can use a different data structure in this place in case of priority queue then there is a chance to optimize the time complexity further can you think of some data structure here definitely we can use DQ data structure why because DQ is not an sorted array but it provides the capability to push from front and back of the array right so with that feature we can use DQ in case of writing uh in this place of plant EQ and we can make this time complexities of order of n because pushing and popping here the mean and copy exactly from the priority keywords pushing and popping the elements right so if we use DQ then we can do that operation in order of constant time so we can optimize this time complexity further to order of so when sorting approach we have saved my complex it has required this order of n k of log K and with priority Q the time from luxury is order of n log k this part order of n which is constant right because we have to execute this code for n or explore for n number of total cells so if we can optimize this pushing and popping operation in constant time then we can further reduce the time publicity right then is there any data structure with support all this kind of facility with pushing and popping of elements in order of constrainting yes the data structure is DQ is not a sorted ID but provides the all the facility that we can get from Priority queue so in DQ we will be storing all the required elements now what is what I mean by uh what do you mean by required elements required element means all the elements which are the potential elements mean the other they can be the maximum guiding okay so in DQ the time complex space complexity will be order of K because at Max Key element will be stored and the first element will be always the maximum score that we can consider right uh in the queue we won't be storing the values rather we will be storing the indexes and we will be updating existing nums array this array which is given and we will get the index from the TQ or the first index will be the index which is having a maximum score right um you can see it so in that way we will be getting the answer right now let's uh see how we can uh do the coding so we will be taking up thank you but also area of integers right and that is first we will be pushing the indexes let's run it forever all the elements so now sorry I write numbers of paintings so from element in DQ mention the index which is having the maximum score and that indexes like is reached within the K range so nums of I will pick a score of amounts of I will be numbers of I plus nums of DQ but I think this one right what is the index and EQ front or we will get the value so numbers of I after this line of execution of line 15 numbers of I will be represented will represent the maximum score that we can get to reach index I is from index 0. right now we have to push this element how because going forward this in index we can consider right because this will be for the next set of elements this will align within the K range this index I right for the following indexes one more condition for this nums of I to get considered is nums of I should be greater than whatever the values present in the TQ right so what we do for that we will help y d q is not empty and numbers of I is greater than equals two I will discuss why I have considered equals to as well then I will do back y equals to because if the same value is already present then my potential index will be fine not the previous one so that's why we'll be removing the elements right once I have this thing I will push the carnetic text I will push it from back okay no we have to check whatever maximum value is present in the front we have to remove that right so compile okay DQ is not empty and I current index I minus DQ of front it is greater than equals to K I will keep on removing from front right so first question whatever elements are beyond the K this is remove two sentences at the end I will return now sub n minus 1. because each index and populating right let's run this and see if it is working fine or not okay it's giving me Romans why okay anywhere else okay let's submitted and got accepted right now few things here you understand like uh how what is a salespace complexity of DQ why we are pushing uh using greater than equals to uh in case of comparing the bindings and also why we are using uh greater than equals to while comparing the indices and however we are storing the data in the team right now see how the down complexity will be for DQ space complexity is always order of K because the DQ will have maximum K element stored because of this conditional check right and here this operations out of model of Constantine and this element is order of K time only so that is kind of constant only soon in here A Time complexity is over of n plus of some constantly so that m compensity is of order of n so we have seen how we can use the recognition method I think we have seen the recursion method for this then to optimize it how we can use sorting then improving the time complexity further we have used priority queue now to improve their time complexity by far that we have used the so I hope uh you have understand the pattern to solve this kind of problems so Let's uh to understand a pattern first and for regards the concepts at one go to explain these things in each Jupiter hope this video will help you a lot thank you for watching stay tuned for my upcoming videos bye
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
1,455
welcome to my channel let's solve another problem of lead code and again i'm picking a problem in a string and obviously it's the easy question so let's see but the question is it's 1 4 double 5 check if a word occurs as a prefix of any word in a sentence all right let's read out the question given a sentence that consists of some word okay separated by a single space that means a sentence is going to be something i love india yeah with a space this would be a sentence and a search word a going to be a search word search what can be uh america yeah you have to check if the search word is a prefix of any word in the sentence check if the america is a prefix of any word in the sentence now america is not present return the index of the word in the sentence where search use is prefix of this word okay i love india and america now it's present so i have to return the position of this word so it's going to be one two three four five all right if there isn't no such word return minus one if there is no america in the sentence then return minus one all right cool now the best part of lead code example sentence i love eating burger search word is p-u-r-g all right so it's search word is p-u-r-g all right so it's search word is p-u-r-g all right so it's going to be return one two three four yo cool now what i'm going to do okay first because it's a sentence is a with a space i'm going to put an array dot split yeah with this space all right now got everything in my uh sentence zero i got something like i sentence one i got love similarly i got india on the third on the second element yeah let's comment all because it's gonna create problem while running the code i'm defining a split sentence now the search word right define the length of sentence dot length yeah now let i equal to zero i'm going to loop through from zero less than l e don't forget to do i plus i did a mistake here i less than l e all right now the comparison is going to be on the first sentence which is s sentence 0 i'm going to find index of search word is greater than minus 1 then return i do not forget that the array starts from zero but the word starts from one we have to increase the account plus one let store in a result define the results let's result here uh okay return result all right i is going to be search for index of search word is mean if this bark is present in i then it will return some index like 0 1 2 or 3 positive number if not it's gonna return minus one so i'm checking if it's greater than minus one then it's present on that particular word yeah make sense all right let's clear all these chunks now for the negative test if sentence i search for sentence dot index of search equal to minus 1 return minus one here i'm returning result let's see run the code yo hit the run code one two three four five six seven yeah 88 millisecond accepted i love eating burger burg is on the fourth position so it's got accepted let's run the second case because my brother told me why you just running the first example you're not running all the test cases so my responsibility is run all the test case all right yeah all right now the pro search word is a pro so manually let's check one two three four five six on the six output should be the six position let's see yo output is two all right uh because uh problem is also have pro and i have to return if there are two matching uh word i need to return the first position let's run the next test case u uh u is not matching at all it should return minus one yeah yo minus 1 now my brother is happy seeing that i'm running all the test cases yeah okay pillow is there it's going to return 4. yay guys we all we ran all the four test cases yo thanks for watching the video
Check If a Word Occurs As a Prefix of Any Word in a Sentence
filter-restaurants-by-vegan-friendly-price-and-distance
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one word, return the index of the first word **(minimum index)**. If there is no such word return `-1`. A **prefix** of a string `s` is any leading contiguous substring of `s`. **Example 1:** **Input:** sentence = "i love eating burger ", searchWord = "burg " **Output:** 4 **Explanation:** "burg " is prefix of "burger " which is the 4th word in the sentence. **Example 2:** **Input:** sentence = "this problem is an easy problem ", searchWord = "pro " **Output:** 2 **Explanation:** "pro " is prefix of "problem " which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index. **Example 3:** **Input:** sentence = "i am tired ", searchWord = "you " **Output:** -1 **Explanation:** "you " is not a prefix of any word in the sentence. **Constraints:** * `1 <= sentence.length <= 100` * `1 <= searchWord.length <= 10` * `sentence` consists of lowercase English letters and spaces. * `searchWord` consists of lowercase English letters.
Do the filtering and sort as said. Note that the id may not be the index in the array.
Array,Sorting
Medium
null
1,946
hey guys it's payne here so today when i talk about a question nicole 1946 largest number after mutating substring so this is the question from the weekly contest 251 question two in a contest i couldn't solve it but later on after the contest i try to figure out you know so that's really the description you are given a string none which represents large integer you also given a zero index integer array change of lens 10 that maps each digits zero to nine digits more formally digits d mapped to digits change d okay you may choose a mutate you should mutate any substring of num to make mutate a substring replace each digit num i mean that's i with the digits it matched to in change for example replace num of index i will change with change of num index i okay so what we need to return string representing the largest possible integer after mutating okay the substring is a continuous sequence of characters within the string okay so need to be continuous sequence so for example one three two so see if change can be larger so at position one is eight okay it's larger than the original one so we changed that three zero one two three is smaller so we stopped you know because e after three if we replace three by zero it's gonna be smaller so we don't make sense in this case o3 is changed so zero is nine at two is three is bigger than the original one three greater than two one is four greater than one by itself all right so and then if five if original number is already the largest number can be created so we just don't leave it that like that so for example what zero one two three four five is two five is greater than two so we'll leave it like that so what's our mindset right here so i basically use i change the string num right here to character array first because it's easy to work with you know characters and then basically loop through each numbers each character in this number you know how many numbers in there and i get the current number by suggesting the character i get the integer over the in type integer and type in and i get the candidate calendar means the one that in the change array you know put in so we try to find out okay at current index is the change is in change array at the same index is larger or is smaller if it's larger we replace the current by candidate see no update if the candidate is greater than the current okay yeah in this case so see this is the way we created you know the characters i index i at the current index this is greater we to we want to put kennedy to that position you know and else it means like okay we stop the process when and we need to keep track of retake is true if it's true though because once we start mutating then it means that okay we need because we need a continuous substring so once mutate is not true anymore then we break it you know so if the product if candidate is less than current and it's mutate also it's already mutated then we break it because since it's already mutated and later on whatever the character will leave little bit like that without me anymore all right so return the string form of the character away just submit it yep it passed and yep submitted let's see the time complexity and the space complexity so for time space time let's see so we look to the so time is basically oh all right so space we create another character eraser is open all right because we are okay another space of regular here so yep thank you guys have a nice day right here
Largest Number After Mutating Substring
minimum-absolute-sum-difference
You are given a string `num`, which represents a large integer. You are also given a **0-indexed** integer array `change` of length `10` that maps each digit `0-9` to another digit. More formally, digit `d` maps to digit `change[d]`. You may **choose** to **mutate a single substring** of `num`. To mutate a substring, replace each digit `num[i]` with the digit it maps to in `change` (i.e. replace `num[i]` with `change[num[i]]`). Return _a string representing the **largest** possible integer after **mutating** (or choosing not to) a **single substring** of_ `num`. A **substring** is a contiguous sequence of characters within the string. **Example 1:** **Input:** num = "132 ", change = \[9,8,5,0,3,6,4,2,6,8\] **Output:** "832 " **Explanation:** Replace the substring "1 ": - 1 maps to change\[1\] = 8. Thus, "132 " becomes "832 ". "832 " is the largest number that can be created, so return it. **Example 2:** **Input:** num = "021 ", change = \[9,4,3,5,7,2,1,9,0,6\] **Output:** "934 " **Explanation:** Replace the substring "021 ": - 0 maps to change\[0\] = 9. - 2 maps to change\[2\] = 3. - 1 maps to change\[1\] = 4. Thus, "021 " becomes "934 ". "934 " is the largest number that can be created, so return it. **Example 3:** **Input:** num = "5 ", change = \[1,4,7,5,3,2,5,6,9,4\] **Output:** "5 " **Explanation:** "5 " is already the largest number that can be created, so return it. **Constraints:** * `1 <= num.length <= 105` * `num` consists of only digits `0-9`. * `change.length == 10` * `0 <= change[d] <= 9`
Go through each element and test the optimal replacements. There are only 2 possible replacements for each element (higher and lower) that are optimal.
Array,Binary Search,Sorting,Ordered Set
Medium
null
461
today we will solve a very simple question called hamming distance is the number of bits in which two numbers differ for example this number denotes three and this denotes five this is four plus one so you see that this bit is same this bit is different so we got one this bit is also different zero and ones so we got another one and then it's same so hamming distance between 3 and 5 will be 2. so how can we solve it's very simple uh you can also use some built-in function you can also use some built-in function you can also use some built-in function if it's available in the language for example in c plus we have bit set but let's not use that so what we will do let's say this is x this is y so if we take x or y then all the bits which are same will become 0 and all which are different will remain so the number of now the problem reduces to finding the number of set bits in x or y so this is also very simple let's store this in a result r so while r is greater than zero you take r and one so one is everything is zero last bit is one and if you take and with anything only the last bit if it's set will become one if it's unset it will become zero so it will be either zero or one so keep a count here and then do count plus equal to this value and then right shift this by one so when this becomes zero uh let's say the last most significant bit that was set in r was this one and everything else to the left of it was zero so once when we shift it by five bits so this loop runs for 5 times this will be gone and it will become 0 and finally we will return the count so let us quickly write the code for this so i had already submitted uh the one liner i was just trying if it works or not and it did work so to the xor of x and y then bit set 32 bits so this bit set returns the set bits so you have to use the count function there are other functions as well like str or string i am forgetting here so that you can print the bit representation of a given number let's say you want to let me show you something just to understand this function let's say i want to print 5 bit representation of 5 then what will i do bit set this denotes how many bits you want to represent in 32 and then the actual number five dot i think it's a string or two string i am forgetting let's try this is just for your info not related to this problem so you can see that this rep prints the bit representation of this five so it's very handy function i find it and in some situations although we will not use it here so let's comment it out and you see that uh if we write just one liner the bit set still it works and if you submit it will give you 100 that is 0 millisecond so now let's do it by proper way without using this built-in function so without using this built-in function so without using this built-in function so let's comment it out so this result contains only the bits which are different in x and y so overflow at line nine so it should be right shift equal to 1 so we will be right shifting result and here also it's zero millisecond so now let's write this in java and python and this is accepted in java as well and here there should not be any problem it should be zero millisecond in most cases and finally in python so java and c plus was code no change was required and it's accepted in python as well
Hamming Distance
hamming-distance
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given two integers `x` and `y`, return _the **Hamming distance** between them_. **Example 1:** **Input:** x = 1, y = 4 **Output:** 2 **Explanation:** 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. **Example 2:** **Input:** x = 3, y = 1 **Output:** 1 **Constraints:** * `0 <= x, y <= 231 - 1`
null
Bit Manipulation
Easy
191,477
72
uh hello everyone today i'm solving lyrical question 72 added distance using the dynamic programming so i have uploaded a previous video solving this problem using recursive solution with memorization the top-down approach memorization the top-down approach memorization the top-down approach and then you can also see from my screen that the solution is already listed here so if you want to see the details of this solution please feel free to check my other video on this added distance today this video is focusing on solving it using dynamic programming approach the bottom-up approach so let's revisit the bottom-up approach so let's revisit the bottom-up approach so let's revisit the problem statement for either distance given two strings word one and word two return the minimum number of operations required to convert word one to word two you have the following three operations permit our world you can insert a character you can delete a character you can replace the character so in example one in order to convert word one into word two so you need at least three operations first you d replace h with r and then you remove the r to c in the middle to convert it to rows and then you remove the ending e to convert to ros so three number of operations needed so to solve it using the recursive approach let's revisit how we solve it using the recursive approach so we use memorization basically specify a cache uh it's a dick python dictionary we use it to keep track of the values we have already calculated before and then we define a helper function and then taking input i j so it means okay this helper function return the added distance between word i starting at word one starting at position i and word two starting at position j so that's kind of how we break down the entire problem into the sub problem in the end what we need to call it just to call helper zero that means okay you will return the added distance between word one and word two i mean word one starting from position zero and word two starting from position zero there is actually just word one and word two so in the sub problem like define helper ij we first consider the base case let's say other one run out of index which means okay we have in this case i greater than equal to the length of word one which means we have already considered all the characters in word one but there's two characters left in the word two that need to be matched or converted so in our case we insert this number of characters into the word one appended to the end so that we can convert that to word two and then the second case is let's say we run out of index in order to so in that case we return the latter for one mana side which means okay we still have some remaining characters left in word one in that case we need to delete those characters so those are our base cases and then we run our recursion let's say first start with say i j if they are in cash or not if they are in cash they have already been calculated before so there is no need to repeat it calculating the same value over and over again so if it's not in cash we need to calculate them so we first by comparing the character as index i and the j so if they the characters are equal to each other so they are the same characters they we do not need to perform any operations for this position so cache i j is just equal to helper i plus one j plus one so which means we do not need to perform any operation at the current position so we move on to the next position for both word one and word two else if they are not equal we need to perform one of the three operations so insert now take this example when we're trying to insert something here after the insertion we match the character and word index j in word two so in our case we need to move on to the next position j plus one and then try to match it with the current uh character at index i so that's one plus helper i j plus one or we can do the division in the division is one plus helper i plus one j so in that case after we delete this character so for the word one we should move on to the next character so that's a character as index i plus one but for word two the character at index j hasn't been matched or converted to yet so that's why we remain at the index j if we replace after we replace the characters we just move on to the next index both were one and were two so that's kind of the three different operation scenario so in that case we just combine them and return the minimum one so basically consider all the three different possible options insertion deletion and the replacement and then return the one with the minimum number of ad operations and then in the end we just return cash i j so this is our solution using recursive approach we just reviewed so now i'm solving it using dynamic programming approach so the reason why i start with the recursive approach because this top-down recursive approach because this top-down recursive approach because this top-down approach is very intuitive to come up with so for the dynamic programming approach sometimes it may not be super intuitive to come up with at the very beginning but if say after you get the recursive approach then it's not super hard to convert that into a dynamic programming bottom up approach so this is bottom-up approach so this is bottom-up approach so this is bottom-up approach so we first need to define a matrix so let's first get the last for word one and word two so we start as uh dp so what does dpij mean so that means the added distance between word one i and word to j so here in this dynamical uh programming approach we're using the bottom up approach so in that case that's why we start considering uh we start with the matrix dp and then dpij represents the added distance between world one up to the position before index i which means that's where what uh the character is starting from index zero to the index i minus one and then also word two starting from the inner zero to index k minus one so in that case is one m plus one four in range from class one so in the end what do we need to return in the end return dp and that is the added distance between the word and where two and okay after having this dp uh matrix so let's have consider the base case so base case for i in range m plus 1 dti 0 equals i for j in range and last one d p 0 j equals j so what does the base case mean base case means let's say in case let's say error of the word one or word two is empty string in our case uh when we try to convert that to the uh convert worldwide into word two so the operation is pretty intuitive so let's say right now word two is the empty string and then on my worldwide we consider at position up until i in other in that case we need to convert that to a word to uh the empty string in that case the operation is just the delete those so this is our base case now let's fill the dp table so for i in range i a one m plus one for j in range one m plus one we comparing the character at position i minus one then word two j minus one so why we are comparing at a l minus one and the g max minus one uh re remember that they what the meaning of dpij is added distance between the word one up until the position before index i so the last character is um here's word one i minus one and then forward two the last character in this comparison is j minus one and then this is something not included in the dp i minus 1 j minus 1 calculation i mean if those characters are the same so this one equals just dp i minus 1 j minus 1 which means no operation or no item needed else dpi j equals 1 plus minimum dpi minus one j d p i j minus one d p i minus one j minus one so if they are the characteristic equal to each other then we need to perform one of the following three operations insert delete the replacement and then we just pick the minimum one from it in the end we just return dpm and so this is our recur uh our dynamic programming approach from the bottom up let's try run the code okay so while i run the dynamic programming the recursive solution with memorization the top-down approach actually the runtime top-down approach actually the runtime top-down approach actually the runtime was a little bit faster than the dynamic programming bottom up approach but usually i mean it's more usually it's a little bit faster for the iterative approach so this is our solution so if you want to check the details for this recursive solution how i came up with it please feel free to check my other video in this playlist the other distance with recursive solution with memorization thank you
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
19
hello everyone let's start with 19 today the problem is remove ends node from end of this so it's a very typical linked list problem it's not very hard for this example for example we have the enclaves one two three four five and n is two which means we need to remove the second node from the end of the list which is node four so after removing node four the next node of three is five the example two is uh there's only one node in the linked list and we remove it so finally we will remove a noun node okay so the first solution is first we could use one pass to calculate the length of the linked list so the length is five here next um we need to check one corner case if n is five we know uh then we need to remove the head node first we keep the next node of the handle which is the value we want to return before we return don't remember don't forget to um delete the node he deletes had so that we could prevent a memory leak in general case uh we said no way delete is not hand node so we keep a local variable called helicopter then we just um for loop until the helicopter is in node before the node we want to delete so here is lens 5 and s2 so we need to move lam minus and minus one times so now copy is no3 then we keep the node we want to delete and we change the next pointer of node three so three is pointing to five now then we delete this node to prevent memory leak finally we return to hat okay this is solution one so there's another solution the time complexity and space complexity are same actually but it's also very typical solution like a very typical trick applied in linked list problems so we have two pointers one is first point one slow pointer first we try to move fast pointer and times then we also have a check if first pointer is not which means for example if n is five we move us pointer five times so first pointer will be the next node after five which is a noun node and fast is none so that means like we want to delete the hand node so we keep the new head and delete head and return this new head okay next we move slow and fast at the same time okay uh the pointer is okay actually uh the slow pointers should pointer to two here okay next the slow pointer is pointing to three okay yeah this is a crux graph then we keep the two delete node and we change the next pointer of this node to 5 then we delete this run node finally with returns ahead so that's the second solution which is using two pointers yes thanks so much
Remove Nth Node From End of List
remove-nth-node-from-end-of-list
Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head. **Example 1:** **Input:** head = \[1,2,3,4,5\], n = 2 **Output:** \[1,2,3,5\] **Example 2:** **Input:** head = \[1\], n = 1 **Output:** \[\] **Example 3:** **Input:** head = \[1,2\], n = 1 **Output:** \[1\] **Constraints:** * The number of nodes in the list is `sz`. * `1 <= sz <= 30` * `0 <= Node.val <= 100` * `1 <= n <= sz` **Follow up:** Could you do this in one pass?
Maintain two pointers and update one with a delay of n steps.
Linked List,Two Pointers
Medium
528,1618,2216
417
hi guys welcome to algorithms made easy in this video we will see the question pacific atlantic water flow given an m cross n matrix of non-negative integers cross n matrix of non-negative integers cross n matrix of non-negative integers representing the height of each unit cell in the continent the pacific ocean touches the left and the top edge of the matrix and the atlantic ocean touches the right and the bottom edges water can flow in four directions up down left right only from a cell to another one with height equal or lower find the list of the grid coordinates where water can flow to both pacific and atlantic ocean the note attached with this question is that the order of the returned grid coordinate does not matter and both m and n are less than 150. so instead of looking at this example over here let's see this visually so that we can get a better knowledge about the problem statement and how we are getting these coordinates as our answers so the main gist of this question is understanding the problem statement itself if you know the problem statement it would be much easier for you to implement a solution for that so for this i am taking this particular example over here and as mentioned in the question the left and the top borders have the pacific ocean attached to it and the right and the bottom border has the atlantic ocean near it and the numbers over here in the cell determines the height of that particular grid or the continent and we need to find whether from some of these continents the water can flow to both pacific and atlantic rules for water flowing are that from a particular area the water can flow in four directions up down left and right but when that can flow to that particular coordinate only if the value of that cell is either same or lower so now if you consider this three according to the rules the water can flow in these four directions and according to the second rule these three are unreachable because these have a height which is greater than the height of this particular cell so the water from here can only flow in this direction towards one similarly if you go to four the water can flow in all these directions because the heights are either lower or same and over here we can see that the water is going into pacific and the water is also going into atlantic ocean so we can consider this particular index in our result list so that's the just of this particular question so now the point that is left with us is how do we iterate over this particular matrix and find whether the water can go to pacific and atlantic both so for that what we are going to do is we are going to first take these coordinates or these ends and try to find the water going to pacific ocean as these are the corner cells the water from here can easily go to pacific ocean next we take the next cells so from here only these cells can contribute to sending the water to pacific or the water from these cells can go to pacific ocean from 1 there is no way it can go to pacific because upside is 7 and to the left is 5 both are higher values and water cannot go over here similarly moving forward 5 is the coordinate from where the water can go from here or you can see from here or there are many roots rest from all these places the water cannot go to pacific ocean now what is the coordinate from where the water can go to atlantic ocean so let's find out that the corner cells obviously they can reach the atlantic ocean moving on to the next cells these are the cells from where the water can flow to the atlantic ocean from three the water cannot go to atlantic ocean because we have five over here and four over here and over here also there cannot be any combination from wherein the water can reach to atlantic moving forward from these cells only five is the cell from where the water can reach to atlantic that is from here or from any other combinations that we can have so if we take into consideration both my pacific and atlantic oceans water so these were the cells from where the water was reaching the pacific ocean and these are the cells from where the water is reaching the atlantic ocean we need to find the common cells from where the water reaches to both pacific and atlantic and those cells would be the ones that are present or that are marked in both these matrices and so those are these many cells and so this is the answer so once we have these cells marked with us we can easily find out what are the coordinates for these cells and so then we can also put those coordinates in the respected format that we want our answer to be in so that's it about how we can solve this particular question for finding these coordinates or for finding whether the water can reach to these points or not we can use either bfs or dfs bfs would be by using q and that would be an iterative approach and dfs would be a recursive approach the brute force approach over here would be that for each cell or for each coordinate i need to apply dfs or bfs and find whether the water from here can reach to both pacific and atlantic if that can happen i can mark that or add that in my result list but that would take a time complexity of m cross n for iterating over all the elements in my matrix plus the highest or the worst case steps that i will be taking in order to reach to these particular positions and that is going to give me m plus n so my time complexity in that brute force approach would go this m cross n multiplied by m plus n that are the maximum numbers of steps i can take for each particular cell so i will not be coding the brute force approach but you can find that code on the github link that is given in the description over here we'll see the dfs or the recursive approach for solving this problem by using two different matrices for storing what are the cells that can reach to pacific and what are the cells from where the water can reach to atlantic and then merging the answers from both of them so let's go ahead quickly and code this particular problem out so the first and foremost thing is checking the edge case that is the null conditions so in these condition we would return the result which would be a blank list with this i'll initialize my row and column and i'll also take a direction that would be the directions of up down left and right and now i need two matrices for storing whether a cell can give me a water that reached to atlantic or pacific so i'll take boolean metrics of the same dimension as my matrix with this i have the placeholder for my data in place over here i'll perform my dfs and that would fill these two matrices after these two matrices are filled let's first write down all the things that would lead us to result so for adding everything into my result i would need to iterate over this and find the coordinates wherein the value is true for both pacific and atlantic if that is there i can add that particular index in my result and that would add the index in the result if this particular coordinate is true and this particular coordinate is true now i need to fill in this dfs this was writing the result and here i need the dfs logic so let's first go and create the dfs function for that so we'll have a void method so over here i'll have my i and j value my original matrix and the matrix that i'm looking for either i am going to pacific or either i am trying to reach the atlantic and with this i'll also have a previous valve because my result is going to be dependent on the previous well so let's write that in this method we will first check our boundary conditions for ing the next thing that we are going to do is to check whether we can go to that particular location or not so over here if my matrix of i or j that is current value is lesser than the previous value or if the current ocean value or this particular atlantic ocean is already being visited or it's true we do not need to go there and we can just return this condition states that we are actually trying to move from inwards towards the ocean so my matrix i of j should be higher than the value that is previously there or value that is nearest to the ocean so that my water can flow to that nearest value if this is not the case that means the water can flow so we'll just mark this ocean of inj as true and then we'll call my dfs on all the four directions so for that i already have this direction array with me so this would take care of my recursive calling so over here i have taken care of iterating and filling my ocean matrix over here i need to write the logic for how to call this particular dfs method so over here let's try to write it for column first and we are going to call the dfs on columns so my row would remain 0 and my column would be i and then my previous value would be integer dot min value and my ocean would be one is for pacific and one is for atlantic so since this is the zeroth row that is the uppermost row the ocean near to it is the pacific ocean so i am going to say that fill this value for pacific and similarly we'll write for atlantic so let's copy this and just the row would become row minus 1 because this is nearest to the bottom so this would become the atlantic ocean similarly we need to do it for rows as well and over here my row would be i and for this my column would be 0 and my 0th column is nearer to my pacific ocean so it would go to pacific and my call minus 1 is nearer to my right end which is the atlantic ocean so that would go to atlantic so what we are trying to do is we are trying to start from the nearest value to the ocean and then we are trying to fill in whether we can have all the other coordinates reach that particular point or not so once everything over here is done we can return the result and that's all that we need to do let's try to run this and it's giving a perfect result let's submit this code and it got submitted so the time complexity for this particular approach would become of m into n and the space complexity would become o of m into n because we are taking these two matrices with us 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
Pacific Atlantic Water Flow
pacific-atlantic-water-flow
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`. The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_. **Example 1:** **Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\] **Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\] **Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below: \[0,4\]: \[0,4\] -> Pacific Ocean \[0,4\] -> Atlantic Ocean \[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,3\] -> \[1,4\] -> Atlantic Ocean \[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,4\] -> Atlantic Ocean \[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean \[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean \[3,0\]: \[3,0\] -> Pacific Ocean \[3,0\] -> \[4,0\] -> Atlantic Ocean \[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean \[3,1\] -> \[4,1\] -> Atlantic Ocean \[4,0\]: \[4,0\] -> Pacific Ocean \[4,0\] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. **Example 2:** **Input:** heights = \[\[1\]\] **Output:** \[\[0,0\]\] **Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans. **Constraints:** * `m == heights.length` * `n == heights[r].length` * `1 <= m, n <= 200` * `0 <= heights[r][c] <= 105`
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
null
1,200
hey so welcome back and this is another Elite code problem so today it's called minimum absolute difference and it's kind of the easier version of this minimum average difference because this one's a medium problem this one's in Easy problem and so let's go ahead and implement it so basically you're just giving it an array here and you want to Output an array of pairs that will all have the same absolute difference but they all must be the minimum absolute difference and so basically what that is just you want to grab two numbers any numbers in here and you want to take the difference of it so you just subtract them and then you wrap it in an absolute function and that just gets your outputs what that kind of looks like in practice say if you grab four and two take the difference and then wrap it in an absolute that's going to Output you a 2 here and so essentially the smallest number in this case is actually one because you could do four and three and wrap it in absolute and that would give you one and so you just want to Output all the possible combinations of pairs that would produce you this minimum absolute difference okay and so to do that it came pretty intuitively where the first thing that you're going to want to do is just sort the array because naturally you're only going to want to compare the numbers that are kind of similar in size because you don't really care about comparing one and four if you have two because obviously this is going to have a smaller difference than these two here okay so when you sort it you only have to actually compare the current number that you're looking at and whatever kind of came before it or after it and so what you can do really is just have like a window size of two and just slide this window kind of across this array so that you're only comparing kind of each two pairs one at a time and then you just calculate what that minimum absolute or what that absolute difference between those two pairs are okay so while you're doing that you just keep track of okay what's the current uh minimum absolute difference and so if you find another pair that has that current a minimum absolute difference you add it to your result set but if you find a new minimum then you just kind of delete that result set and start a new one and just kind of continue adding to it okay so if that doesn't quite make sense um I think writing the code is uh pretty self-explanatory you can really self-explanatory you can really self-explanatory you can really understand the coral logic just by reading it so what we're going to do is return some result and that's going to be an array and we're going to be keeping track of what the current minimum difference is and so initially let's just set it to Infinity to make sure it gets set and so with that we're just going to want to iterate through all these different values from one to the end of the array and we're starting at one because we always want to look at the current node and the one that came before it so it's that sliding window of size two and so with the current minimum difference or the current difference is just going to be the absolute of the current number at I and we just subtract whatever came before it great and so essentially we just want to go down two paths one of them is okay if the current minimum is greater than the kind of current absolute difference here and I said nums but I meant uh array actually then we just found a new minimum so let's go ahead and just set that new minimum difference to the current and what this also means is that the result set that we're producing for this current minimum difference uh can be just kind of deleted we want to start a new one and so then we just want to reset this result set equal to just the current pair that we just have and so that's going to be number at I and also the one that came before it at I minus 1. great and so that way we're just kind of starting a fresh result set of just the current value and the one that came before it otherwise the only other case that we have to consider is if this minimum difference is the same as the current uh absolute difference and so what that's going to be is okay in that case we just want to say okay then we're going to just append this result set to our array here and that's just because well okay this current minimum is still the minimum we just found another instance to produce that so let's go ahead and run it oh um oh just looks like I forgot to sort at the beginning looks good and success so that's uh another week of prom so essentially it's a Time complexity of n log n and that's the amount of time to sort the array that's the bottleneck here otherwise this for Loop is just of end time and so then the space complexity is just going to be o of N and that's just to produce our result set sometimes I like to think of it as o1 because you need to return something but really you should say that the space complexities of n but yeah hope it helped and um good luck with the rest of your albums thanks for watching
Minimum Absolute Difference
remove-interval
Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows * `a, b` are from `arr` * `a < b` * `b - a` equals to the minimum absolute difference of any two elements in `arr` **Example 1:** **Input:** arr = \[4,2,1,3\] **Output:** \[\[1,2\],\[2,3\],\[3,4\]\] **Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. **Example 2:** **Input:** arr = \[1,3,6,10,15\] **Output:** \[\[1,3\]\] **Example 3:** **Input:** arr = \[3,8,-10,23,19,-4,-14,27\] **Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\] **Constraints:** * `2 <= arr.length <= 105` * `-106 <= arr[i] <= 106`
Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals.
Array
Medium
null
823
hi everyone this is sunny kumar from iit vhu and welcome to my channel code with sunny and today i am going to discuss the problem binary trees with factors index number is 823 and the problem is of medium type of lead code so let's jump directly into the problem statement we have been given an array of unique integers a arr where each integer area is strictly greater than one okay and we have to make a binary tree using these integers and each number may be used for any number of times that is the repetition of the number is allowed and each non-leaf node should be equal and each non-leaf node should be equal and each non-leaf node should be equal to the product of the values of its children okay and we have to return the number of binary trees that we can form the answer may be too large so we have to return the answer model of this okay so how we are going to do this problem so let's understand this with the help of the example so suppose here we have three uh integers of the array given so basically we are for sorting the error then we are going to perform the operations so why we are sorting the array so i am going to tell you that also so first lets understand what is happening here okay so suppose if we consider the only the single element that is two then what is what are the binary trees that we can form that is only one leaf node you can see okay and what if we consider the two nodes that is two and four and what are the binaries that we can form uh we can form the binary of only one node and we can also form a binary tree like this also note that repetition of the number is allowed so i'm going to form this type of binary tree also so again i'm going to form a binary tree with eight so eight binary tree can be formed like this if we consider the factors of the eight like it can be represented as two into four and further it can also be represented as 4 into 2 and 8 can also be represented as we can say 1 into 8 and 8 can also be represented as 8 into 1 now one thing we can notice that and so what i am going to do here is i am going to consider i have considered a dp state that is dynamic programming state that is where dp of i is going to denote the total number of ways uh total number of sorry total number of binary trees that we can form with the help of what with the help of this current integer so how we can formulate this value efficiently we are going to formulate this value efficiently by pre-calculating the previous integers by pre-calculating the previous integers by pre-calculating the previous integers that is pre-calculating the that is pre-calculating the that is pre-calculating the values that occurred just before this number so i'm going to explain it with the help of example like here so i'm going to write something okay so let me erase this first okay so now any number n can be represented as the product of two numbers that is a into b it is obvious a is a divisor of n and b is also a divisor of n now we can to find out the total number of binary trees possible with n uh it can be easily find it can be easily calculated as total number of binary trees formed with a into total number of binary trees formed with b and if we product these two values we can get the total number of binary is formed with n okay so for calculating the total number of binary trees formed with a and also for calculating the total number of when it is formed with v we need to pre-calculate the total we need to pre-calculate the total we need to pre-calculate the total number of binary trees formed with a like a is also formed with the help of product of two integers let's say a1 and into b1 or you can say a2 it doesn't matter i'm going to write here a2 similarly b1 b can also be formed with the help of two integers that is b1 into b2 and we need to consider all the divisors that is if a is a divisor of n then b must be equal to n by a similarly we are going to compute all the factors of n and similarly we are going to find the two pairs that is going to satisfy the relation n equals a into b and to calculate the total number of pairs for the node with value n we need to pre-calculate pre-calculate pre-calculate for all the values that lie that are strictly greater strictly less than n so we are going to efficiently calculate with the help of dynamic programming so let's move on to the code to analyze the approach of this dynamic programming state so let's move further okay so i'm going to do this stuff okay so our answer can be very long so i'm going to define something defined let's define mod else 10 power 9 plus 7 and where i'm going to also define one thing also define ll as long okay so our answer let's define uh initialize with zero and i'm going to maintain an unordered set you can also take ordered set or sorry you can also take a simply set okay i'm going to maintain an unordered set of ll comma ll that would be a mapping okay sorry unordered map okay so now proceeding further i'm going to take okay let's sort the array first i need to sort the array because suppose i am going to calculate the let's say i'm going to pick up the ith number so i need to know the total number of binary trees formed and that is the total number of binaries formed with all the numbers less than equal to ai so i need to sort the array first and then perform the operation sequentially starting from left to right okay so let's iterate in the array okay any dot size and simply array plus so what is the current answer i think i should write this current answer should be one why current answer should be one for the leaf node okay our answer will always be one so let's calculate the factors so it would be like let us i trade for i equals sorry j equals 0 j less than i and j plus and if array of i is modulus array of j if it is giving some value and continue because this is not a factor then otherwise i am going to let's pick on first number that is nothing but array of j and what would be the second number it would be simply array of i divided by array of j and what would be our current answer so our current answer would be simply okay current answer would be simply current answer plus uh total number of binary trees formed with a new m1 into total number of binaries formed with num2 and i need to take modulus along with so that it doesn't overflow the required limit of the int max note that this is the dp relation that is our current answer would be nothing but the one of the factors of array of i and another would be is nothing but area 5 divided by that factor so i need to add up all the answers so what i am going to do i am going to fill that dp state also so lets write mp of array of i is nothing but current answer and i'm going to increment my answer as answer plus current answer modulus okay with summation with modulus i think that's good enough so let's return the integer value of answer okay so let's run this code i think i should have submitted the code directly yes it is giving the correct answer so let's check it out yes it is good so if you have any doubts do not forget to mention in the comment section of the video and i will ask the viewers to like this video share this video and do subscribe to my youtube channel for latest updates thank you for watching this video
Binary Trees With Factors
split-array-with-same-average
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary trees we can make_. The answer may be too large so return the answer **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[2,4\] **Output:** 3 **Explanation:** We can make these trees: `[2], [4], [4, 2, 2]` **Example 2:** **Input:** arr = \[2,4,5,10\] **Output:** 7 **Explanation:** We can make these trees: `[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]`. **Constraints:** * `1 <= arr.length <= 1000` * `2 <= arr[i] <= 109` * All the values of `arr` are **unique**.
null
Array,Math,Dynamic Programming,Bit Manipulation,Bitmask
Hard
2162
19
all right what is going on everyone uh today we are looking at lead code number 19. it's called remove the nth node from the end of the list and so here we have a list of one two three four five and the number n here is 2 so we want to take 1 2 we want to remove that nth node from the end of the list okay so we remove that 4 we return that list the original list but with that nth node removed here we have one so we're going to go back one this is the first node we remove that it returns an empty list here we remove the two okay and one of the things that we have to look at is that can we do this in one pass okay so let's jump over here in the conceptual and so here we have a list of one two three four and five okay and our n is going to equal two and we have to figure out well how are we going to remove this nth node right over here well one way we could do this is we could get the length of the list we could just go ahead and iterate over this entire list here and get the len would be five okay and then we could do len minus n which will give us our remove index okay that will tell us that here is our zero one two and three len minus n three minus five or five minus three two is going to be three and this is gonna be the index that we wanna remove from and so the way we could do this is we could just create a previous and a current and we can just iterate this until we get to until current equals that index three okay current will get over here to index three and then we can just go ahead and break this pointer over here at previous and set it to current.next previous and set it to current.next previous and set it to current.next okay now this wouldn't be doing this in one pass this would be two passes because we're going to have to do a whole first pass to get the length and then we're going to have to do a whole another pass to go ahead and find the index and remove it the other issue is what if the node that we want to remove is 1 right if we're setting a previous and a current here then if we have to remove this first node here then what we want to do is have this be the new head and that wouldn't work either using this method okay so let's think about this in another way let's go ahead and clear this out and let's say we have our input here 1 2 3 4 and 5 and n is going to equal 2. how do we do this in one pass well let's say we have a tail node okay and we set it here and we only increment it n times okay so tail is going to go one and two okay so our tail is going to be there now our previous we're going to set it to a dummy node that comes right before the head and we can just set it to -1 okay and we're going to go ahead and -1 okay and we're going to go ahead and -1 okay and we're going to go ahead and set this dummy node to previous and then our current now is going to be or we can call this remove node okay that's going to be the node that we're going to remove we'll set that at the head and our tail is at three it's at n well as we move n times from the front now we just increment these three pointers all the way until the tail equals null until it gets out of the list and let's see where our pointers land okay so we increment this tail over here remove node over here previous over here we go and increment our tail over here remove node over here and previous over here and then our tail is going to equal the null uh our remove node is going to land right here where on the node that we want to remove and our previous will be right before it now if we want to remove this it's as simple as breaking this pointer that's pointing to the four node and just have it point to remove dot next okay and because we're using this dummy node even if we have to remove this node number one we can do that we're not going to run into any bugs we can just go ahead and break this and set it over here and then we just keep a reference to this head here we can say dummy head and then we return dummy head dot next okay and so what is our time and space complexity uh with this well our time complexity how many times are we iterating over the list we're only iterating over the list once so it's going to be o of n okay and then our space complexity how much space are we creating relative to the input well let's see here we have to create a pointer for previous we have to create a dummy node we have to create a tail pointer and we have to create a remove node pointer so no matter if the input size is 500 or it's five the amount of space that we have to create is constant okay it's the same amount of space so our space complexity will be constant space okay so let's go ahead and jump into the code here and so first thing we want to do is go ahead and create our dummy head okay and we'll set that to new list node and we can set this to minus infinity or you can set it to -1 infinity or you can set it to -1 infinity or you can set it to -1 any anything is fine any of those is fine and now we want to have a reference first we're going to say dummy head dot next is going to equal head so it does connect to our input and now we want a reference to that dummy head so we can say let result head equal dummy head we're going to want this because we're going to increment that dummy head all the way through our previous and so we do want a reference to it that way we know that we have that we can return something at the end and then we can create a counter here to go ahead and find our correct area for our nth node our remove node so we can also have a tail here so let tail equal head okay and now what we're going to do is we're going to say while count is less than n we're going to go ahead and increment the tail okay and now what do we want to create a current node or we can say remove node to head our prev is going to be our dummy head okay and now what do we want to increment our tail all the way to the end okay so tail is going to equal tail dot next our removed node is going to equal remove node.next okay and our preview is going to increment okay now that we have these all in the correct position okay remember here all of these variables are going to now be in the correct position when tail gets to null what are we going to do we're going to say preve dot next is going to equal remove node dot next okay and now what do we want to do well we have this result head reference here to our dummy head we're just going to return result head dot next okay let's see here we want to increment count here okay and that does it and so this is in one pass it's linear time and constant space okay so important thing to remember about this is using that dummy head method it's a really important thing anytime you're dealing with any sort of linked list problems that are dealing with uh addition or deletion where you have to remove a node or add a node really consider using a dummy head some sort of node that just has a you know it could be any sort of value in there that goes right before the head of the node it just makes deleting it takes out a lot of the edge cases whether that node is the first node the last node any of those things it just kind of gets rid of any of those edge cases so that is leak code number 19. remove nth node from the end of the list i hope you enjoyed it and i will see you on the next one
Remove Nth Node From End of List
remove-nth-node-from-end-of-list
Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head. **Example 1:** **Input:** head = \[1,2,3,4,5\], n = 2 **Output:** \[1,2,3,5\] **Example 2:** **Input:** head = \[1\], n = 1 **Output:** \[\] **Example 3:** **Input:** head = \[1,2\], n = 1 **Output:** \[1\] **Constraints:** * The number of nodes in the list is `sz`. * `1 <= sz <= 30` * `0 <= Node.val <= 100` * `1 <= n <= sz` **Follow up:** Could you do this in one pass?
Maintain two pointers and update one with a delay of n steps.
Linked List,Two Pointers
Medium
528,1618,2216
35
hello everyone i'm young first welcome to my channel this is the series about the self mock technique we interview today we will solve the any problem we need code together so let's start it's 35 it's a easy problem so racing we should resolve this within 10 minutes so let's start with the description together search insert position given a sorted array of distinct integers and a target value return the index if the target is found if not returns a index where it would be if either were inserted in order you must write an algorithm with oh runtime capacity so the accent so this is a typical problem for binary search if you are familiar with the person layer user or api that is the big left and left are in superclass plus it's nowhere bank lower bound there is a build building function to do this because this operation is very common uh and of course we can and we can use the built-in and we can use the built-in and we can use the built-in api to solve this with just oneness but i think it's better that way we deal with this by our code because this is uh what the interview we are want to want us to do so let's do that this is a typical band research there they there is a pattern to do that for example the no index no pointer is uh zero and the high pointer is the last index so we get no we got a range that is from o to high the law is inclusive and the highest excision and well the range is not empty look at the mid middle of the and we need to tag that if nam's middle is large are equal to target if it is we need to make the high equals to meet us we need to make the no to the mid plasma so as a return goal this way well when the range is uh empty the low will be the first index where we're numbs no large are equal to target that's uh that's all if you look at the implementation of the bisector left or the lower bound the implication be very similar with what i did so let's run the code okay are our optimal rx are accessible let's submit it yes we did that so this problem is very difficult so i think you should be familiar with the pattern of the band research after that you can implement those codes very quickly in a real interview so good luck see you tomorrow bye
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
23
in this video we are going to solve merging of case sorted lists it's a very popular problem and it has been asked quite a few times in facebook amazon google microsoft adobe byte dance and many more companies so it's a very important question so let's understand the problem so uh in this problem we are given a few linked lists in general we will be given k linked lists and these are sorted so this is the first linked list l1 this is l2 and l3 in this case k is 3 so we have three linked lists and you can see that the values are sorted so the goal is that create one singly linked list out of all the k linked list such that this is also sorted so uh the number of nodes in this part the total number of nodes by adding the values is same in both the linked lists so how we can do that so i have color coded the node so that you can see that this color of nodes light very light blue kind of coming from the first link list and then the greenish one these are coming from second link list and so on so let's see a few approaches so first thing would come to your mind that may be very naive is that take all the nodes so we have n nodes in total so we can sort them in login approach using a simple sorting method and you will get the linked lists but that is very naive we are not using the fact that the nodes are already sorted so even if these are not sorted this approach would work but we have to utilize this sorting property so let's see a much a better approach so the optimized approach would be that you keep you can keep one pointer each at each of the k linked lists so we have k link list so we have k pointers and currently all of them are at the beginning of the list so we have not yet started building the main list so the list is empty so first one should be the smallest among all of these and smallest among all of these will be in the beginning so because three would be larger than one similarly two would be larger than one four is larger than three so we will just have to compare among k different keys at a time so we have pointed to current pointers to all the linked list heads so minimum overall minimum will be one of these it's not sorted in this direction mind you this 3 4 can be the first linked list also so the minimum would be among these k keys so we will compare among k different keys at a time so let's say minimum is one of these either the first one or the second one so let's keep the blue one now we have added this to the main link list this node so in the first linked list we will move the pointer here next maybe this was also one so we would have taken this also it's not that once we have taken from first list uh the next one will be from other list maybe all the keys are smaller than the minimum of all the other so the next pointer in the first list is here now in the second node so now we are comparing one three and three so the smallest is one now this is also added so the pointer in the second list moves here and we have to compare among two three and four so two is the minimum so let's add 2 here and this is added so the pointer moves here in the second list so we are comparing on 3 6 and 3. so minimum is 3 let's pick this 3. and the pointer is here so 3 5 and 6 minimum is again 3 so this is added now pointer in the third list is here so 4 5 6 4 so this is added you see that this last list is now empty we have added all the nodes so now we are comparing on these two values 5 and 6 so minimum is 5 and this is added and finally we have to compare again just one key which is 6 and now this list is also empty and this is the result so uh the main thing that we need here is to a way of comparing k different keys so we are picking minimum among k keys minimum of k different values so what would be the way of uh implementing this a natural way would be to come up with the idea of a min heap because mean he exactly does that we are not bothered about ordering among these keys but we are bothered about what is the minimum among those k keys and that is what minip does so uh we can use built-in functions so uh we can use built-in functions so uh we can use built-in functions built-in constructs like built-in constructs like built-in constructs like priority queue it's available in c plus java python everywhere so let's take a priority queue and insert the head of all the lists so we would insert let's use this page we would insert 1 and 3 in the priority queue so at a time maximum k values can be there in the priority queue so time taken to compare k values would be log of or getting the minimum would be o of 1 but again you have to do epify which can take log of k time so let's take this time as one operation as log k so minimum would be one so we added this one and the pointer is here so whenever we uh insert the minimum from this priority queue so priority queue will have at max k keys so whenever we pick the minimum and add it to the main list the result list we find what is the next of this so here we will be inserting the node pointer instead of the node value so that we can check what was the next so next of 1 was 3 so 1 is now removed as the minimum and we insert 3 this node pointer not the value into this priority queue so 3 is inserted now again the minimum is one and this one is coming from here so we put one here and see what was the next so this pointer is still intact the next pointer since these are pointers i am repeating again and again so this one is gone and now the priority queue has three instead of one now it's next of one two and three minimum is two so we put two here two is popped its next is six is pushed minimum is three let's say this three comes so this is popped and it's next that is five is pushed into the queue priority queue now we have three six five so you get the idea next three will be picked this one and its next will be pushed four next four will be picked and its next is null so we will not put anything so now we have just 6 and 5 here so minimum will be 5 and its next is also null so now we have just 6 in the priority queue and we will pick 6 and again its next is null so the priority queue becomes empty and at that point we return the head of this new list so what will be the total time there are n total nodes and i said that uh picking the minimum takes one unit of time but ep 5 will take log of k and after some time this k will also decrease some of the lists may become empty so total log k for one operation so n log k is the approach here this approach time taken and the naive approach was n log n so n may be very large total number of nodes and k may be a very small quantity so this is a faster approach and in this is the time complexity and space would be at once we are storing at max k node pointers so we can say o of k now let's write the code for this so we have to define a comparator for our priority queue since it may not be available this link list pointer we don't have a way of comparing based on which field we want to compare in this case we will compare based on the value so let's define our comparator so take two pointers list node star a list node star b so if you want to sort based on the smallest value you have to take greater than and now we will define the priority queue so the priority queue will have list node pointers and we will use vector as container and the comparator let's name it pq and now initially we will insert the head pointers of all the lists so there may be some lists so there may be test cases where you have a list this is a vector of list node but that is empty so you have to insert only if that particular list is non-empty now we have to check maybe that priority queue was empty nothing was inserted there are no nodes so if this is empty then simply return null otherwise this is the head of the final list that we want to create so now we have handled the case that priority queue is non-empty so we can priority queue is non-empty so we can priority queue is non-empty so we can safely pick the top element the minimum element this is this will be the overall minimum also and let's pop it once we have used it we have to pop it and if head next is there then we have to push the it's next since we popped the head it will be popped from one of the k lists so put insert the next from that list itself it may be the last element in that case we will not insert but if the next exists then insert it and let's keep the current in the final list because this head will always be pointing to the first node in the resultant list the longer list we have to also keep track of the tail will be the current list current node that we just inserted so that we can uh make the next of the tail as the new node that we want to insert next so we can you can call it tail or you can call it current anything let's call it current so initially head is the current one and we will insert next of head so while pq is not empty we have to run this loop again the same logic that we applied earlier here in the beginning pick the minimum pop the element and check its next current next equal to this n so current is the tail the last node in the longer linked list so this new node n comes here and now current or tail is pointing to this n and the node that we popped out if it's next exists then we will put it into the priority queue and this will continue till this priority queue becomes empty and then we will return head so let's run it on a few test cases it's working for our case so let's submit it and the solution is accepted so i hope you understood this so uh if you want in python and java it's very simple you have to if you understood the logic there is nothing much here it's a very simple code in fact this same logic is repeating for initialization and all the other values so uh good luck and see you in the next lesson
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order. _Merge all the linked-lists into one sorted linked-list and return it._ **Example 1:** **Input:** lists = \[\[1,4,5\],\[1,3,4\],\[2,6\]\] **Output:** \[1,1,2,3,4,4,5,6\] **Explanation:** The linked-lists are: \[ 1->4->5, 1->3->4, 2->6 \] merging them into one sorted list: 1->1->2->3->4->4->5->6 **Example 2:** **Input:** lists = \[\] **Output:** \[\] **Example 3:** **Input:** lists = \[\[\]\] **Output:** \[\] **Constraints:** * `k == lists.length` * `0 <= k <= 104` * `0 <= lists[i].length <= 500` * `-104 <= lists[i][j] <= 104` * `lists[i]` is sorted in **ascending order**. * The sum of `lists[i].length` will not exceed `104`.
null
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
21,264
55
hello and welcome today we're doing a question from recoat called jump game it is a medium let's get started given an array of non-negative integers given an array of non-negative integers given an array of non-negative integers you are initially positioned at the first index of the array so that would be index 0 each element in the array represents your maximum jump length at that position determine if you are able to reach the last index example 1 given an input of nums equaling 2 3 1 4 we output true because we can jump one step from index 0 to 1 and then from here index 1 we can jump 3 steps to get to index 4 which is the last index and example 2 we have numbers equaling at 32 1 is year before and we output false here because we always arrive at index 3 no matter what and its maximum jump length is 0 so it's impossible to reach the last index so from here index 0 we jump 3 index 1 we jump to take it to 3 next 2 we jump 1 2 plus 1 is still 3 we always land on index 3 but its maximum jump is 0 so 3 plus 0 will never get us to index 4 which is where we want to go so there are multiple ways to solve this problem one approach would be to kind of explore all the possible jump pads so if we know our maximum jump is to kind of see what happens if we jumped 1 if we jumped 2 and then over here if it's 3 you see what happens if we jump 1 2 then 3 so at each index we would keep branching out to see what our next jump value could be in that path so while this answer is valid it does get computationally pretty expensive and there is a better way to do this for example taking this input nums let's say we had another value at the end here 3 now our maximum jump is at index 3 so the rightmost value that we can approach at this point is index 3 if we go to index 1 we know it's invalid like we can always jump here from index 0 because their max value that we can reach our Mattox index we can reach is index 30 so we're covered for index 1 - all we have to do covered for index 1 - all we have to do covered for index 1 - all we have to do is go from index 0 jump 1 2 up 2 3 these are all valid indices that we can land on so from here we see our max index is still 3 over here from index to our max rightmost index that we can reach is still 3 now at index 4 even though we can reach the last position we have to output false because we can ever actually arrive at this index because our rightmost value is 3 no matter what jump path we take we'll never actually reach this index to then reach West so as we iterate through as soon as we land on an index that is greater than our rightmost possible value that we can jump to we want to output both now if this wasn't there if this 0 wasn't there our maximum right index that we can reach at this point is 0 1 2 3 same thing over here we're at index 1 plus through jumps these three index 2 plus one jump is still 3 now index 3 we can jump 4 so now our right is 7 and this right is greater than equal to the last index we want to reach which is at index 5 so we output true otherwise we just keep iterating and updating right as we see it so let's just go ahead and code it this up we also want to start with write equals 0 since we start at this very first index so write equals 0 and our last index is a length of Nam's minus 1 all we need to do is a one pass iteration so for I in the range I is the index so if I is greater than our right most possible value that we can jump to we want to return false now if this place that we landed on has another set of jumps that can increase our rightmost possible value we want to update right so if numbers of I the value of that index plus the index we are on how many jumps from where we are is greater than from where what we can currently reach you want to update that so right eagles numbers of I plus I and if write the rightmost value that we can reach is greater than equal to last the last index then you want to return true so let's run code it is accepted and submit and it is accepted as well so this is a row of n run time and oh of one constant space solution let me know if you have any questions or comments down below otherwise I'll see you next time
Jump Game
jump-game
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position. Return `true` _if you can reach the last index, or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[2,3,1,1,4\] **Output:** true **Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index. **Example 2:** **Input:** nums = \[3,2,1,0,4\] **Output:** false **Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 105`
null
Array,Dynamic Programming,Greedy
Medium
45,1428,2001
729
um hello so today we are going to do this problem which is part of um august daily challenge the problem is my calendar one so basically um what we have is we want to implement a calendar where we can add a new event if um it will not cause the double booking so if there is no conflict or there is no overlap with another um existing interval and a double booking this is just explaining that a double booking is when you have two events right with the start and finish time and they have an unempty intersection right um and the event is represented by of course just start and end however this is important here is that it's a half open interval so start is included but end is not right so the range is not closed at the end um and the range of real number so basically this is what it means um it's the numbers between start um and end but end is nothing close and the class we want to implement it has a of course an initializer and has a booking book function with start and end and that function returns true if we can add the event to the calendar and false if not and we can't end the event if it will cause a double booking if it will overlap with another interval so that's the problem now let's take a look at an example here so we have first 10 to 20 right um so this is maybe 20 like this and then after 20 so this is 10 um we have something that starts 25 to 15 to 25 that is so 15 maybe something like this to 25 here and then 20 to 30. right so you can see um already this one we can't add it because then we'll have an overlap but we can add this one um because 20 this is remember this is not inclusive so this is um open interval here and so we can add 2030. so we return true here we return false for the second one right because there was an overlap so we couldn't add it and then we returned true for the first one um yeah so that's pretty much the problem now let's see how we can solve it um okay so let's see how we can solve this so the first thing you we know that we need to do is definitely um since with this book here we need to check if there is an overlap between two intervals so the first thing we need to think about is how to detect an uh an overlap and so what we can do is let's just go case by case into different examples or different cases of intervals and see if we can find a general function or a general formula to check to determine if two intervals overlap right so to do that let's just say for example we have two intervals right let's say we have a which is basically maybe just a1 and a2 for the end and the start and b which is b1 and b2 right so these are the two intervals that we get and we want to check if they overlap um so we have a couple of cases right either let's say a is like this right so basically b ends before a and so something like this so b1 b2 so b ends before a okay so this is our first case so in this case you can see the bigger the overlapping interval so we is the lapping piece is this here right okay what is how can we what is this value here so this value actually is just the minimum of the two sorry the maximum of the two so the one to the right more so the maximum of a1 b1 here and the minimum of these two right of the end which is minimum of a2 and b2 and this makes sense because to overlap we need to go to the common area and common area is um of course the start is just the higher value right and then the um the end is the smaller value right because we want the common portion so with this formula this is uh what it is so with this if you want to detect an overlap we can just check if this is smaller than this if the start is smaller than the end then we have an overlap right um okay so now let's see let's check another use case here so if basically this is if the max of which is the start of a1 b1 is smaller than the min of a2 b2 then we have an overlap this means basically an overlap so this is a good start now let's see if it applies to other examples so let's take another case here where we have okay so um the first case was b ends before a right so naturally the second case can be b ends after a right and so in that case what would be the example so maybe we have something like this and this is a2 and then b ends after so something like this so in both cases um b starts after a and here b starts after a um one thing i want to mention is that this analysis case by case to solve a problem is a good technique to use um so we just keep it in mind and now we have b1 b2 right so in this case does this still applies so what's the um intersection here what's the overlapping piece it's this until here right so same thing it overlaps from the to get the overlap again it's just the one that starts the latest and the one that ends the first right that's the overlap if there is any overlap and again this interval what is this interval is just the max of a1 and b1 which is b1 right and then the end is the min of a2 and b2 which is a2 in this case and again this is a valid interval if this is smaller right and so same thing here we have this formula valid a valid way to check here right sorry okay now i'll see another last case where there is no overlap and see if we are able to detect it with this so case three uh basically b starts after so in both cases here b starts after a uh but before a ends right and here let's have b starts after a n so that there is no overlap and we don't need to do this like for a ends before b because then it's the same thing right it's just we are swapping which one we are calling a and which one we are calling b so we don't need to do that the analysis for let's say a ends before b because that will amount to the same thing um and same thing with uh a starts after b ends right uh so with this last case here what we have is a1 here let's say a2 here and then we have b1 here and b2 here okay so there is no overlap right but if we were to pick this formula here so that this is no overlap but if we were to pick our formula what will happen to the how can we check if there is basically what i'm looking for is if this is false can we say that there is no overlap right so let me paste this so what is the max here so this is a2 right uh sorry the max between a1 and b1 that's b1 and the min between a2 and b2 that's um a2 right but you can see here right a2 is smaller than b1 and so this is our start and this is our end so what we have because of this is that our end is smaller than our start right so this is not a valid interval so our check here is false so this is false which means no overlap okay so right away what we can say now is with this analysis is that to check if there is an overlap we just need to check if this is if the max of both a1 and b1 is smaller than the min of a2 and b2 that means we have a valid overlap so with the reason overlap if it's false that means there is no overlap and we can book the interval and that's pretty much the main thing we need for this uh problem so what do we do with the rest um so sorry about this so what we need to do here is in our booking function here we just need an array that starts that saves all the bookings and then when we are booking we just take every interval already in booking and check if it overlaps with the new one if we find only one that overlaps we return false and we don't add the interval and if we don't find anything that overlaps then we return true and add the interval um so that way it's pretty simple solution the main part the main tricky part is to know how to detect the overlap easily um yeah so that's pretty much it let's go this up and make sure it passes these cases um okay so let's write down uh what we saw in the overview so we need to have an array of the bookings so far so let's say an emptier starts out as an empty array and now we need to check um if there is an overlap so let's create so let's just go through the bookings right so for be in software bookings we want to check if there is an overlap so we'll create that function between b and the interval at this interval so let's call this interval a start end so i'm going to check if there is an interval between these two if there is we want to return false if there isn't we want to return true but we want to also add this interval because we are able to add okay and now let's create this function for overlap between a and b so what we said is we just need the max of a1 and b1 to be smaller than the min of a2 and b2 and a1 and b1 a1 and a2 are just the start and the end of the interval a so let's just write it like that and b1 and b2 are the start and the end of b so if this is the case that means there is an overlap if not there is no overlap right so we just return it and yeah that's pretty much it so let's run this um here we need to just make it valid um okay let's see what's the problem here so there is an invalid syntax uh yeah so i think it just needs and this is like a okay yeah we don't need this side okay so that seems accepted so let's submit okay so that passes test cases now um it's not the fastest solution um but i think it's the easiest one to explain um to get a faster solution you could for example have bookings be a sorted list and then just binary search for this new interval if you don't find it return if you don't find it there is no overlap but if you find it then there is an overlap um yeah but that one is a little bit trickier so yeah i'll stick with this solution um yeah so that's pretty much it please like and subscribe and see you on the next one bye
My Calendar I
my-calendar-i
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**. A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.). The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`. Implement the `MyCalendar` class: * `MyCalendar()` Initializes the calendar object. * `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar. **Example 1:** **Input** \[ "MyCalendar ", "book ", "book ", "book "\] \[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\] **Output** \[null, true, false, true\] **Explanation** MyCalendar myCalendar = new MyCalendar(); myCalendar.book(10, 20); // return True myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event. myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20. **Constraints:** * `0 <= start < end <= 109` * At most `1000` calls will be made to `book`.
Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added.
Design,Segment Tree,Ordered Set
Medium
731,732
1,748
let's solve problem 1748 of lead code sum of unique elements you're given an integer array nums the unique elements of an array are the elements that appear exactly once in the array return the sum of all the unique elements of nums so what they're saying is you'll be given an array something like this which might have duplicate numbers and we need to find out the sum of all those numbers which are unique so one is unique two is not unique because two appears twice three is unique right so we need to take a some of this and return so how am I going to do that I can what I can do is I can maintain two sets Okay S1 would be the set in which I'll put all the unique numbers S2 would be the set where I'll put in all the duplicate numbers I'm keeping duplicate just to check if the number is in duplicate set then I will not add it to S1 or I can call it unique set and I can call this duplicate set right so now I go through each number for Num any nums if number is in if it is in unique set then I'll remove it from unique set remove it and add it to duplicate search okay L LF number so it will go into the lse blog if number is not in unique set so number is not in unique set I'll now check if number is not in duplicate set okay if it is not in duplicate set then I can add it to the unique set right and finally so I have all the unit set after the for Loop is complete so I can return the sum of unique set and now what I could also do is I could reduce this operation of doing a sum here right by maintaining a variable sum and keeping that zero and whenever I add to UNI sum I'll increment s okay I'll increment s by number and here I'll in decrement as by number so I can finally just return the number let's run and see that worked for all three cases let's submit it and see and that took 12 milliseconds
Sum of Unique Elements
best-team-with-no-conflicts
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Array,Dynamic Programming,Sorting
Medium
null
232
hello everyone welcome to my channel so today we are going to do the good daily challenge queue using stats so let us pursue this question then about the constraint and finally intuition behind the scene and then the coding can a Time complexity for the same so first of all this question so I required to including the person first after speaking that is simply a queue where whatever comes first that goes out first that is the thing let me stay so that's the thing which we are required to implement and this we are required to implement using only two stacks means not more than two copy one also but uh so here the thing would be that only two stacks will be used questions that implemented Q should support all the functions of a normal queue that is first peak of energy so the whole thing basically required to implement our own data so that is the thing here then the thing which would be here is including this my Q Plus here which is this push the pushes will even take to bulk of the cube and then Bob removes the element from front of the queue and returns also the same and P it's about to return the element at the front of the queue uh yeah and then put an empty just to return true if the queue is empty holds a device so that is the thing here means these four functions which are there which are required to be implemented here now comes the part you must use only standard operations of the stack which means only push to talk take off from the top and size is empty these are the only valid operations in depending which may not be supported natively you may simulate stack using a list P Cube that is the only ended queue as long as you use only a stack standard operation so basically implementing a queue using a stack but all the operations which are there that should be so standard operations only which are ported in stack now comes the part by the constraint which are there so as it's just that would be from one to nine only at most hundred calls could be there for this four operations uh we see these are the functions required to be implemented and all the coil to the top 10 Peak are valid they want to say that there would be elements in that particular queue then only pop and Peak would be implemented else they won't be implemented so that they went by ballet now because the next part like this okay follow for the same that can you implement the using such each operation is demortized order of one time complexity in other words performing in operations will take overall in tongue even if one of those may take longer so that the thing which we are required to clean so here they have already mentioned that we are required to use to start and using those two stack means uh using these two stack we are required to implement the cube and stack we all know that how Stacks are if this is one two three then surely the output will be three to one but if it is one two three in this queue and the output would be one two three so using two stack we can do that like C then it would be at the bottom then two and then one and then here the output will become something lenses that's why using two stack we're easily able to convert into a cube so now let us go ahead that how we are required to implement the same so yeah if we see here use P2 stack one step two this is there was function with the state that is this push with this thing and we are pushing to our first stuck that little thing so push operation performed now comes the part about Mom for popping from and what should be the element which is being at the top but here's a pop exactly means that the element which is which was pushed at the starting to the queue so for that purpose we will be checking that if our Step 2 is empty and our stack one is not empty then in that context we will be checking we will be pushing whatever is there at the top of the stock first thing we will be ongoing until our staff one becomes empty because we are going to pop out from the stack one you all know that two stacks are there so if one two three are there then while we are pushing here so what will come to the top would be one only means the element which was pushed at the starting and this is what we require in our queue also means this would be pushed out so that does the thing here and because of this thing only we will be easily able to succeed without this operation and if this is not the case it's a stack 2 is not empty please start to still have some value and in that context whatever is at the top of the star too that we will be popping out and returning that as a value so that is the scenario here so this was for the pop now comes the part for the other functions which required to implement that is p can empty so it takes simply means that what is at the top means what is the first element which was being pushed towards Cube but for that purpose again the same thing would be done the way it was for the box but the thing here is that we won't be popping that out that is the only difference which we are required to do here because here we are required to just tell that what is at the top we are not required to just pop it out we just required to keep that element as it is but the thing would be that we require that this element should be a means this element should be there ruining and you're just required to tell that which is the topmost element so that's what we are required to do here now according to the part our last one notice it is empty or not so we will be directly checking that both of them are empty then surely it is empty yes if anyone of them would be having some element and that simply means that uh that I Q is not empty so that is the thing and that's why we are doing things like this so the time come is like sitting space complexity so as per the space complexity we can see that this order of n right what comes the part for the SE complexity so here this push operation is order one right this pop operation foreign because you know we are popping out until this that exists so that's a scenario and here it is but here it is Amor files because of this scenario and same goes for the peak operation as well this big Corporation also it is order of one but a modified and just click empty let us directly we are saying that it is empty or not so all operations here are order of when we have and they have already asked us to perform all these things in that we only so yeah this was all for this thing in doubt because comment out then yeah and this was a lot 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
1,765
like in actually bought the simple problem like kuju variation here oranges problems is equal to zero i less than ri plus for is equal to zero effectively is equal to q dot second dot sorry okay q dot front dot minus one comma zero okay so for int i is equal to zero i less than 4 i plus again so may i pick next coordinate next what basically next coordinate car index liquid entire is equal to r plus dri and cc is equal to c plus dci so yeah basically this is suppose dri will be the x coordinate of this cell dca 0 is it will be the x coordinate of this cell and like this i can search all the surrounding cells again so it cell may mean if condition if greater than equal to zero and cc less than c or sub say important condition grid rr cc should be greater than what one plus grid rc is run fine so if you have understood the video please like the video and subscribe the channel so thanks for watching guys have a nice day
Map of Highest Peak
merge-in-between-linked-lists
You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells. * If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell. * If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell. You must assign each cell a height in a way that follows these rules: * The height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1.
Linked List
Medium
null
856
hey everybody this is larry this is day 18 of the leeco daily challenge of for march uh or 17. okay i'm wrong so what day 17 of the march league daily challenge hit the like button hit the subscribe button join me in discord let me know how you think uh how you feel what about this prime and all this other stuff uh so today i'm actually wearing my uh i survived defense hike rate hike of 2015 t-shirt uh it's just rate hike of 2015 t-shirt uh it's just rate hike of 2015 t-shirt uh it's just uh if you're into finance you're into the stock market and stuff like that you uh hopefully you made it out okay today is a green day and all that stuff i don't know what i'm saying over there anyway today's problem is uh score of parentheses that's kind of weird isn't it i mean what's up with all these like parentheses problems anyway uh like i don't know is this gonna be another stack problem is that i don't know then it kind of takes away some kind of uh like if you keep on getting the same type of problems then and you have the same type of solution i think it takes it a little bit away because then you're not um you don't have that um like if you group problems by the solution then you don't exercise the part of your muscle that is like okay what kind of problem is this right so i think that's the only concern i had for uh for these kind of groupings but um with that said let's get started okay so let's see the score of a vertices is based on problem um okay so you have four minus one a b is a plus b okay and then inside is times two okay um i think it is just i mean this is just a stack and being careful um yeah right i think so yeah um i think that's pretty much it so let's kind of get started on that one then right um how do i think i just have to be careful i mean i don't think there's anything tricky about this one this is again a stack problem and when you see these kind of balanced parentheses type thing it's almost going to be always a stack problem unless there's some like funky uh hard problem uh though n is equal to 50 maybe there is um no i mean this is still gonna be a stack problem i was gonna say maybe there's some like funky dynamic programming you think and i'm sure you can do something with dynamic programming and something funky but for this one i think you could so a stack should suffice as long as you're really um careful about it um yeah i mean i think that's it i don't i mean usually i have a very you know like i tried to have a very precise idea before coding and in this case i think it's just all about implementation i think ideas um like i have the idea but i have to kind of work out maybe some possible edge cases so i have to the idea i have correct or you know i think it's correct but it's about implementation is the rest of this problem so let's uh let's see how that goes um so okay so let's say if this is it goes to open parens right what does that mean um yeah i mean i think that's we just push on the stack maybe i mean maybe there's some easy quick shortcut way of doing this but for now i'm gonna always just push things on the stack and then see how it goes right like maybe you could represent this in a more efficient way but like i always say um you know efficient wrong answer is still a wrong answer right so get it right first and then we can optimize later don't prematurely optimize okay so then now the top one is the more interesting one right so then we obviously have to pop we can assume that there is a parent so then what happens so if um because i don't think we have to validate it right so it's only parents or balance so if stack greater than one is equal to so if this is equal to the open parents then we should replace it with one maybe so i'm not gonna lie oh and this is a pen that's why it looks awkward um no whoops that's not what i meant to do i mean it's fine but okay so else meaning that top of the stack is a number um that means that basically and i think the hard part for me is just kind of in my head trying to thank for all the cases and making sure that i don't have weird edge cases but i think top of the stack is a number that means that we have this kind of problem but um but i think i'm missing a case i'm missing the case where i have let's say i have this right but with a i think it's just about being careful and getting all the cases but let's say i have something like this right then in that case we will have you know this pops to one this also pops to one and then now going over here what we want to do i guess okay so i guess what we want to do is keep on adding all the numbers that are inside until we see the left paren so then i could rewrite this a little bit um so then while stack my one is not you go to parents and because it is balanced we can we don't have to check that the length is greater than zero because um it's guaranteed to be balanced right so yeah at the very end we pop and then we get the uh we get the answer um but let's just say current is equal to zero while this is not true then current we add the top of the stack and then stack that pop and then here don't know if i need this oh no i do because then now it's equal to the left parent we pop we appen um this is a little bit tricky so if current is equal to zero that means that we match it directly so then we can do one else we do stack dot append two times current because that's what they tell you two that i'm saying um but i would also say that i'm not gonna lie this gives me not that much confidence um this gives me maybe like 60 confidence but in any case we do need to pop off the rest of the things so um yeah so while stack or length of stack is greater than two that means you have all these kind of things right or greater than one sorry if you have at least two you have like these things where basically you just have like uh components and then while this is true you have a as you go to stack.pop and you just add them to stack.pop and you just add them to stack.pop and you just add them uh consecutively i suppose and that should be good unless i mess up something really bad but yeah because then now we have one number left oops let's run it real quick i my confidence is probably like i don't know 80 maybe i'm not super confident that i got every case but let's you know at least make sure that we but this is also why we test right all right let's if this looks good i have confidence i think i skew a little bit on adding stuff to the end so i want to actually also add something in the beginning i guess both is fine um because basically what i'm doing here is um i'm not gonna like case analysis even though it doesn't look that way but i think in my head and maybe in the code a little bit i do combine a lot of cases in my head so which is why it kind of came out like this um but it may be a little bit cheesy that way so we'll see here's a min okay cool yes first try i actually like i said i'm not i wasn't that confident about the solution um but i guess this works then this is great um so each number is going to be pushed on at one push on the stack once um and at the way i know it'll be only be popped once so this is going to be linear time because each character each pair of parentheses will only get one push and one pop right um roughly speaking because technically merging but um so it's going to be amortized kind of uh amateur each of each processing will be uh o one so this is going to be o of n total um you know it's all one advertise each i suppose is how you would say it um and this as well because if you have oops if you have n elements then obviously this is going to just pop end time so that's fine um and obviously it'll be linear space because that it's that's what happens when you use a stack um yeah um i think that's all i have for this one this is a little bit tricky for sure um especially for a medium one um because you have to think for the edge cases so it's not can excuse me i don't think this is conceptually hard but you have to be really careful is what happens with this one so i'm actually surprised and happy that my last two attempts i got on the first try let's see what i did that those times uh okay so actually i did i said that but i guess i did pretty much just oh and i summed the stack actually that's actually better than my current solution but technically i guess it's more uh straightforward how did i do the second time oh i did the same thing the second time so okay so maybe i did come up with it all the time but uh but yeah let me know what you think stay good stay healthy take good mental health hope the stock market treats you well but with mental health um take care and i'll see you later bye
Score of Parentheses
consecutive-numbers-sum
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced parentheses string. **Example 1:** **Input:** s = "() " **Output:** 1 **Example 2:** **Input:** s = "(()) " **Output:** 2 **Example 3:** **Input:** s = "()() " **Output:** 2 **Constraints:** * `2 <= s.length <= 50` * `s` consists of only `'('` and `')'`. * `s` is a balanced parentheses string.
null
Math,Enumeration
Hard
null
779
you guys let's look at this problem case symbol in grammar hmm so I'll skip description so we are given an N at 1 K oh yeah we need to the description so at the root it is 0 and then we have a rule to generate a new row which is replacing 0 with 0 1 so 0 becomes 0 M and replacing one with a 1 0 so for the next row 0 becomes 0 1 become 1 0 so 1 so just doing this over and over again attention that the row start based on what ok and index K retai return the K the index symbol in row n ok so we will calculate the case number kate digit of grow em well this is a typical binary tree right it's complete tree full tree so for cave just if we want to get case number of like the third number of row four we actually get need to get the second number of the row 3 and then get to the number of row first number of road - wait a minute hmm no actually 0 1 0 so I so it's like that this one is if it is odd it should be the left wing of this one and then left wing a right wing of this one so if it is left wing we can see that 0 1 if it is left wing it's the same if this right wing writes children it won't be reversed right so 4 3 we know it's odd so it should we keep it's odd right yeah so it's the left wing of a left wing of parents so it's the same and for here too the one it's odd and it's on the right so it have to reverse so it can become 0 reversed and this one is 0 so we got to root it's also 0 because it's on the left wing so it keeps the same right yeah but how can we judge if it is left-wing or right-wing comparing to the parent if the comparing to the parents this one should always be the right wing and this one should be left wing so left right here is a left right and then left right it will change when we just look up to the road yeah if that's the case we can now just say okay so we will return k if K is odd wait a minute okay we just first calculate the pre-k okay we just first calculate the pre-k okay we just first calculate the pre-k equals here it should be math.ceil equals here it should be math.ceil equals here it should be math.ceil math.ceil Cape / - all right okay math.ceil Cape / - all right okay math.ceil Cape / - all right okay so if K is odd number then we turn case grammar and minus 1 and the pre-k plus 1 grammar and minus 1 and the pre-k plus 1 grammar and minus 1 and the pre-k plus 1 we have to divide it right reverse it right so mod I - sorry lot by 2 in the right so mod I - sorry lot by 2 in the right so mod I - sorry lot by 2 in the other case we just return k grammar m minus 1 please okay so it's done and we the base case is that if N equals 1 return 0 this should be an integer right let's run it finished Keith Graham is not defined type Oh God Ron Esser oh so the second row the first one ah hmm second rule okay pre one is uh it's not sealed it should be aa su minus one because here like three you should be too and the index should be if index is 3 then it should be to write plus one okay three ah God it should be floor my bad hmm still not accepted I've got two one okay and then we got one zero I got we turn 0 because 1 is odd we should reverse right - what okay is also ah God K is also 1 indexed okay so k is also why next 1 2 3 4 1 2 1 so we got k if one two so k oh if he's hot God he said it's one based hmm still not right got three one they got two zero so it's okay one so you should be sealed okay one then should be also one to accepted God got confused with the index problem so it's so slow so this is the recursion time so actually so far Oh n because we've checked row by row space there's a stack the stack is also and we improve it actually we can improve our think we can just improve it by to do it with tail recursion let's try tail recursion okay tail recursion time is also K space will be constant so the keys that we should return always return if you pass down mmm pass down passed down the result also so we could create another one called Creve breathe no we should say okay case grammar function okay actually the body should be mostly the same Oh slow because we use console.log I think because we use console.log I think because we use console.log I think anyway we should we could just do that do something like this and the key part is that we should not add extra calculations here we should just return grandma a grant grammar toggle yeah toggle true or not should be one was plus yeah carrier I think maybe carrier okay so we do the saying if it's uh we returned eighth grammar M minus 1/3 a we returned eighth grammar M minus 1/3 a we returned eighth grammar M minus 1/3 a with a career theory is okay if K is odd then she should be Kara one right and this one so this is done but I finally when we got to one we return plus carrier career and gets the mod of two so and then we finally we can return k grammar k zero oh I forgot to plus it a try if it works wrong time ever Oh finished submit Keith Graham is not defined oh this one accept it I think it might be faster yeah look we use tail recursion and help us and of course we can write we could write in - I know we could not could write in - I know we could not could write in - I know we could not write in direct in iteration what our recursion is good enough and I think we can just do that you do the direct calculation right I think that if this the funny spanning tree if oh so this is one is but I need to find the direct mathematical formula it's a waste of time yeah so that's all for this one okay see you next time bye-bye
K-th Symbol in Grammar
max-chunks-to-make-sorted-ii
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` row is `0110`. Given two integer `n` and `k`, return the `kth` (**1-indexed**) symbol in the `nth` row of a table of `n` rows. **Example 1:** **Input:** n = 1, k = 1 **Output:** 0 **Explanation:** row 1: 0 **Example 2:** **Input:** n = 2, k = 1 **Output:** 0 **Explanation:** row 1: 0 row 2: 01 **Example 3:** **Input:** n = 2, k = 2 **Output:** 1 **Explanation:** row 1: 0 row 2: 01 **Constraints:** * `1 <= n <= 30` * `1 <= k <= 2n - 1`
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
Array,Stack,Greedy,Sorting,Monotonic Stack
Hard
780
1,609
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is even odd tree so in this question we're given a binary tree named even odd and it has to meet the following conditions the first condition states that the root of a binary tree is at level index zero and at level one their children are at level two index so it says that the leveling starts from zeroth index and for every even leveled index all the nodes at that level have odd integers in strictly increasing order and the third and final rule states that for every odd index level all nodes at the level have even integer values in strictly decreasing order and the order is from left to right for both the conditions so we are given the root of a binary tree and we have to return a Boolean value as our output we have to return true if the binary tree is even odd which satisfies these conditions else we have to return false now let's take a look at these examples and see how we can solve this question so let's take the first example given to us this is example one now let's take a look at the three rules the first rule states that the level starts from zero so this is level one and this is level two level three and so on and this is the condition for even level and this is the condition for odd level so let's mark them this is the even level and this is also even level this is odd level and this is an odd level and finally we have to return either true or false as the output so we know we have to iterate through all the levels and this is a clear sign that you can use BFS so that you can iterate all the levels and at every level you have to perform some operation so I think BFS is a good choice for this traversal so in BFS you maintain a queue so initially you add the root into the Q I'm only taking the first element and there is a left sub three and right sub three for every root now we are at even level we have to check if the values present at even level are odd in nature and are strictly increasing so keep track of a tree node which is initially null and I keep track of the current node which we retrieve from the que so the current node is one so remove it from the que and we are have to process it we check if it is odd yes it is odd and check if it has any other nodes in the current level no there is no other node so this condition is satisfying for level zero and now for the next iteration and we keep track of the level is initially zero now we have to go to level one now how do you go to level one you add the left child you check if there is a left child for this yes there is a left child so add it into the que check if there is a right child yes there is a right sh so add it into the Que Now take the topmost element from the queue that will be the current node and pop it from the Que now we are at odd level check if that value is even yes 10 is even and compare it with its previous value now we have to check if it is in strictly decreasing order so that is in descending order it's strictly decreasing that is the current element now we access this now we have to compare now current will be here and previous which was initially null should become this element so update current value to previous so previous will now become 10 and now check if 10 has a left child yes 10 has a left child so add it into the Q check if 10 has a right sh no so you don't add anything and now this becomes the current element so this becomes four so pop it from the Q check if this is a even number yes it is a even number and check previous value is strictly increasing yes 10 is greater than four so this condition is also satisfying and now we have to update the value this becomes previous four will become previous for the next iteration but now there are no more elements because we finished processing this level and now we have to add its left child and right child into the que yes left child is there so add it check if right child is there so add it and now go to the next level so these two elements are also accessed now in every iteration previous will become null and now we go to the next level so we are at this level now and using this level variable you check if it is a odd level or even level and for every level we reset back previous uh to null so that we can start new level comparisons now take the top element is three so that will be current so pop it so three is the first element and check if it is odd yes it is odd because we are at even level now this becomes previous three becomes previous and before going to the next element check if three has a left side yes three has a left side so add it into the Q check if three are the right here yes so add it into the Q and now you pop the current element from the Q and this becom seven let me rewrite this now check if this current element is odd yes it is odd we need odd element check if it is strictly increasing yes previous was three and it is strictly increased so this condition is also satisfying now before going to the next element check if seven are a left side yes check if seven has a right sh no so don't add them previous element is seven and current element is the topmost element nine so current element is nine so pop it from the queue check if this is odd yes this is odd check if it is in strictly increasing order yes the order is being maintained so both the conditions are satisfied for even level and now before going to the next element check if 9 has a left child no so don't add it check if 9 has a right child yes so add it and before going to the next iteration we increment the level and we reset back previous to null and now we are at this level now the current element is 12 so take that check if it is even yes because we are at odd level check if it strictly decreasing yes it is strictly decreasing so 12 is the first element in the level Now update previous to 12 and current element is eight you don't have to add anything because this is the last level and if you check left for left and right sh both are null in all for all the nodes in the last level so I'm not checking them so current node is right check if it is even yes it is even check if it is in strictly decreasing order yes it is in strictly decreasing order so pop that element from the Q now previous is eight and current is the top element which is six so pop it from the Q and check if this is even yes check if it is in strictly decreasing order yes so both the conditions are meeting again now update the values previous will become six and current node is a top element from the Q so two will be the current element so pop it and check if this is even yes check if it is strictly increasing or check if it is strictly decreasing order yes both the conditions are satisfying again and now increment the next level we are going to the next level so level is four but now the Q becomes empty it means we processed all the elements once and if we haven't returned false until now if at any point if one of these conditions were failing we directly return false as the output now let's implement the same steps in a Java program coming to the function given to us this is the function name and we given the root of a binary tree and the return type is a Boolean so we have to return either true or false as the output like we discussed we are implementing this using BFS so I'll need a q so declare a Q This Q will contain trotes I'm going to name it Q and I'm going to implement it as a link list so initially I'm going to add the root into the Q so q. add of root and I'm going to keep track of the level by using a variable called level and the level is initially at zero now we keep iterating through the que until the Q is empty so the condition is that until this Q is empty this while loop will run and now for every level I have to keep track of the previous node right so that I can compare it with the next uh node inside that same level so that I can Implement these two conditions if it is strictly increasing at even index if it is strictly decreasing at odd index so I keep track of a note I'm going to name it previous note and initially it is null and now let's find the size of the current q that is how many nodes are present in the current level so I create a variable size and use the size method on the Queue now let's iterate through all the elements inside the queue by using the size variable so for every level this size variable will keep on changing and I use a for Loop to iterate through all the nodes inside that level now inside every level I have to keep track of the current node so that I can compare it with the previous node I'm going to name it current node and I'm going to extract the current node from the queue using the pole method so this pole method will remove that node from the que so this pole method will return the first element from the queue and also remove it from the queue and now we have to check if the current level is even or odd so I keep track of the level variable right so I'm going to check if it is a even level by using the modulus operator if it is zero the REM remainer is zero then it is a even level in the else block we're going to handle the Logic for odd level so first in even level we have to check that they're only odd integer values so access the current value so if this current node do value if you mod it with two if it leaves a rem remainer of zero then it is a even value so this is even level logic right so at even level we have to check that only odd integer values are present but if we encounter a even integer value so we can directly return false and now again we have to check for the second condition where we return false that at even level the values are strictly increasing we return false if it is decreasing order so to check if this is a decreasing order we use the previous node and the current node so first we check if previous is not equal to null because initially it is equal to null and now we check if the previous node value is greater than or equal to the current node value if this condition is true then it means that it is in decreasing order but we need strictly increasing if it is in decreasing order then we return false so this is the logic for even level now in the else block we have to implement the logic for odd level so this will be similar so I'll copy this and make some minor changes so this is odd level so if at odd level like here the value should be even so to return false we check if the values are odd a value when you do modulus operator it leaves a rem remainer one if it is odd then we return false and we have to check if the values are strictly decreasing so we do the opposite of that we check if the values are strictly increasing if previous value is less than or equal to current value then it show then it means that it is an increasing but we need decreasing if it is an increasing we return false so for example if we are in the last level this is the previous value and this is the current value for the next iteration when the current is here previous has to become here so update the previous node value so previous node will become current node and now we have to add the left child and right child for every node into the que so first we check if the current node has a left side so if current node do left is not equal to null only then we have to add that value into the Q so q. add of current node. left now let's copy this and do the same for the right child so if current node. right is not equal to null then add current node. right into the Q and now this for Loop will handle the logic for one level and before going to the next iteration we have to increment the level right so initially level was zero so before starting the next level we increment level and this y Loop will happen for all the levels until the queue is empty now outside this y Loop if we never returned false then we return true as the output now there are a few typers here this has to be previous node and here also n has to be capital now let's try to run the code the test case are being accepted let's submit the code and a solution is accepted so the time complexity of this approach is O of n where n is the number of nodes present inside the binary tree because we visit all the nodes once to process them and the space complexity is also of n because we're using a q to compute the output and all the nodes will be added into the Q that's it guys thank you for watching and I'll see you in the next video lady
Even Odd Tree
find-all-the-lonely-nodes
A binary tree is named **Even-Odd** if it meets the following conditions: * The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc. * For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right). * For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right). Given the `root` of a binary tree, _return_ `true` _if the binary tree is **Even-Odd**, otherwise return_ `false`_._ **Example 1:** **Input:** root = \[1,10,4,3,null,7,9,12,8,6,null,null,2\] **Output:** true **Explanation:** The node values on each level are: Level 0: \[1\] Level 1: \[10,4\] Level 2: \[3,7,9\] Level 3: \[12,8,6,2\] Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd. **Example 2:** **Input:** root = \[5,4,2,3,3,7\] **Output:** false **Explanation:** The node values on each level are: Level 0: \[5\] Level 1: \[4,2\] Level 2: \[3,3,7\] Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd. **Example 3:** **Input:** root = \[5,9,1,3,5,7\] **Output:** false **Explanation:** Node values in the level 1 should be even integers. **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `1 <= Node.val <= 106`
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
563,1005
136
welcome to joey's tech my friend in this video we will look into solving an array problem known as single number the problem is there on lead code number 136 and you can find the link to its problem statement in the description box however we will now look into the problem statement ourselves without further ado let's take a look at the problem you are given an array of integers every integer is present two times in this array except one integer we need to find that single integer in this array you can see that 4 is the integer that is present only once and we need to write an algorithm that spots 4 as the output let's first understand how the algorithm is going to work to solve this problem we are going to use the bitwise xor operator what happens when we perform a bitwise x or operation on two values the xor gives one if the corresponding bits are different and it gives 0 if the corresponding bits are same let's understand this with the help of an example the binary representation of 4 is 0 1 0 and the binary representation of 2 is 0 1 0 we are going to perform the bitwise xor operation on 4 and 2. so the xor of the last two zeros is going to give us 0 because both the bits are c the xor of 0 and 1 is going to give us 1 because the bits are different the xor of 1 and 0 is going to give us 1 again and the xor of 0 and 0 is going to give us 0 because the 2 bits are same over here as well interestingly this is the binary representation of 6 okay one interesting thing about xor is that if it is performed on two same integers then it yields zero let's see how these two zeros are going to give us 0 if xor is performed on them the two bits here are 1 so xor operation on them is also going to give 0 over here these two bits are also same so we are going to get 0 over here and we will get 0 over here as well okay thing to note is that if xor is performed on two same integers then it gives 0 as the result we know that in our array all integers are present twice except one so when xor is performed on them they are going to return 0. hence the xor operation on these two twos is going to yield a zero and the xor operation on these two ones is going to give zero as well when xor operation is performed on integers that are present twice then it's going to yield 0 now when we are going to perform the xor of this integer which is unique and 0 then let's see what we get the binary representation of 4 is 0 1 0 and the binary representation of 0 is 4 0's now if we quickly perform the xor operation on 4 and 0 then we are going to get 0 here 1 over here 0 and 0 over here 1 over here and 0 over here this is again the binary representation of 4 so xor of an integer and 0 is going to yield the integer only the thing is crystal clear if we keep performing xor of an element with its previous element okay then eventually the final cell of this array will hold the unique integer if we do the operation then the xor of 4 and 1 is going to give us 5 the xor of 5 and 2 is going to give us 7 the xor of 7 and 1 is going to give us 6 and the xor of 6 and 2 is going to give us 4. and remember this is happening because there are integers which are present exactly twice so when xor operation is performed on them they are yielding zero so indirectly it's the same operation happening over here and that's why the last cell of this array is giving us the unique integer present in this array the single number i hope the algorithm is clear to you let's write the java program implementing this algorithm i have created a java class named a single number in my project in which i will begin writing the program i will first create the main function for which i am going to simply type psvm and there you go main function created for me first we are going to declare and initialize the array that is going to hold the elements it will be an integer array so let's write in square brackets and let the r name be a error equals to new int square brackets again and let's put in the elements so they will be 4 comma 1 comma 2 comma 1 comma two there you go array declared and initialized as we saw during the discussion of our algorithm that we will perform the xor operation on an element with its previous element for that we'll have to start a for loop that is going to iterate over this array the loop is going to start from the second element because if we start the loop from this element then there is no previous element on which xor operation can be performed so it will be for end i equals to 1 i less than error dot length i plus there you go loop created now to perform the xor operation on any element of this array and its previous element we will write the following line of code so it will be arr within square brackets it will be i cat equals to sign arr i minus 1 the carrot sign over here is the bitwise xor operator okay this is the main logic and now all we have to do is to print the last cell of the array err so for that we are going to write system dot out println err and the last cell and we can find the last cell using arr dot length minus 1 okay along with this let's print the items of the array arr to see if they match with the items of the array that we calculated during our algorithm discussion for that we are going to write another volume for in this time there will be another variable let's call it j equals to zero j less than a r dot length j plus and over here we are going to write system dot out dot print because we want to print the elements of the array side by side so it will be arr j within square brackets concatenation operator space okay notice that we are using this loop just to print the items of the array this is actually not a part of the solution that we are required to find all right so the program is complete let's run it and check what output it gives and there you go the program says that 4 is the unique integer from the ira err it's the single number and in the second line the program has printed the items of the array so they exactly match with the items that we calculated during our algorithm discussion phase i have submitted this java program on lead quotes website as a solution to the problem of single number it passed all the test cases and took only two milliseconds of time with this we have come to the end of this video i hope you enjoyed learning this problem from joey stick i hope you coded this program along with me i look forward to helping you with programming and algorithms and only for this video goodbye and take very good care of yourself
Single Number
single-number
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. **Example 1:** **Input:** nums = \[2,2,1\] **Output:** 1 **Example 2:** **Input:** nums = \[4,1,2,1,2\] **Output:** 4 **Example 3:** **Input:** nums = \[1\] **Output:** 1 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-3 * 104 <= nums[i] <= 3 * 104` * Each element in the array appears twice except for one element which appears only once.
null
Array,Bit Manipulation
Easy
137,260,268,287,389
1,192
Hello Viewers Welcome To Gautam Gambhir Virat Number One Adhikari Subscribe Loot Directly Or Indirectly Subscribe Button Click Heer Voor Loot Question Free Mode Connection Between Avatars And Benefit From Nov 09 Pimples Subscription Ronit Subscribe Loot Thursday Doob Scam Id Porn Ki With Respect To Inch 9 And Definition Of Chief Proctor Loot Qu 151 Adhir Va Obscene Video Clip Virvar Video Subscribe Loot Quick Airplane Mode Connection Too Big For A Difficult Job Sk Path subscribe and subscribe the Channel Please subscribe and subscribe the two And Bluetooth Difficulty Loot Difference Between Notification To 99999999999 Subscription Time Notes I Will Always Be Amazed Me Notification Loot Subscribe To That It Will Always Be That No One When Pretty Simple Explanation More Modes Of The Subscribe Drowned In School Mid Summer Mid Night Mid Language Video Particular Node In This Innovative Do Subscribe Withdrawal Mist A Time They Riched Into The Surveillance Fuel Love And subscribe The Amazing subscribe and subscribe to The Amazing Redmi Hai Velvet Wave 205 One 999 9999 02351 More Video Subscribe Fifteen Middle Age Ko Dalana Relationship Between Adherent Purva Ve Sril subscribe To My Miding subscribe The Video then subscribe to subscribe from Notes22 Not Do Any One From Nov 09 2012 subscribe And subscribe The Amazing Nuvvu Nenu Subscribe Loot Current Are You Dhaka And Karan And Stamp Are Needed Just Opposite Ronit Particular Video subscribe not withdraw from don't forget to subscribe in reason religion born into higher times of the current president subscribe witnesses subscribe thank you straight raw one time current time difficult not been even after creating live videos god condition with Difficult Collection Adhir and Subscribe Lutz Particular subscribe The Amazing Subscribe Play List and Wikinews and Address of Wool Loot Number of Wave subscribe Video Ko Loot Election Ki Hawa and Jupiter in Amla Wash Fat or Acid Attack Sexual Adhir Veeravati Video then subscribe to subscribe and subscirbe Mode Vo Din Notes From Which We Are Coming To Do's Not Mean That Will Be - 1800 Noddy Not Mean That Will Be - 1800 Noddy Not Mean That Will Be - 1800 Noddy 409 Plus Particular Node Video Current And Take No Difficulty Subscribe And Subscribe The Channel Subscribe Will U Can Hussain Symmetric Pandey Govind Chatak Baikunth From This Particular Word Oil Patience Chronic Tours Fog Current subscribe Video Subscribe Not Visit Appointed For The Subscribe Decide What You Know It Is The Current President Festivals Subscribe Created Strus Subscriber Node Note They Cannot Be Used Before Visiting Verses Porn Video Result Complete Subscribe Will This Remedy Vitamin More Video Subscribe Subscription ID Shampoo Of The Amazing Note Subscribe Now To Receive New I Pin Not Getting Correct Respond Their Picture They Used For Lootna subscribe The Amazing spider-man More subscribe and Amazing spider-man More subscribe and Amazing spider-man More subscribe and subscribe the Channel subscribe Video subscribe this Video plz subscribe The Channel Please subscribe and yet nilo and also needed to 1000 comments commercial watching this video serial next9 kar do
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
1,022
That Welcome To Malwa Today When With Problem Call 100 Route To Leave The Numbers Are Interesting Problem And Security Question And Technological Institute [ Question And Technological Institute [ Question And Technological Institute For Research And Values ​​Through To Values ​​Through To Values ​​Through To Front In Number Starting In Sid Tree Only When Is The What Is The Significance Person Example of 000000000 Fuel Surcharge Just Notice Not Having Any Child Who Wishes To Vaikuntha Left and Right Not Consider Numbers Represented by Padru to the return of the question example2 Solved 100.000 Downloaded by Numbers Till Note Subscribe 508 509 Persons Converted into Indian Values Will Represented 45 to 60 Miles Select 567 Unauthorized Questions or Solve This Royal Page Solution of Van - Already Solve This Royal Page Solution of Van - Already Solve This Royal Page Solution of Van - Already Sold in a Little Water and Doing So Android Samapur Liberation Army Me Than Inside This Calling Baat Samru Toli Research Method Which Create and Take Two Parameters First One Is not for those who were traveling and second one is the parents You pay Swiss Go back to the example Dan Weldon Good at any position Adharmi Not limited to think in terms of the best Remembered This white-collar intercity gives Remembered This white-collar intercity gives Remembered This white-collar intercity gives examples in terms of material Notes and That I Am ₹400 To Decorate The Song App That I Am ₹400 To Decorate The Song App That I Am ₹400 To Decorate The Song App Multiple Extend Deposit To Zainul Number 16 To Different To My Parents Hum And Value Tweet Notification On Soft NRHM Four Alto 800 Key Debt Victims 238 Yacht Welcome To Three Four And Scheduled Tribes In Logic Divya Ko * For Tribes In Logic Divya Ko * For Tribes In Logic Divya Ko * For Students and Parents Saw A Day Routine Dhan Adhere To Calculate The subscribe to the Page if you liked The Video then subscribe to the Page * * subscribe to the Page * * subscribe to the Page * * Phate Note Som Plus Root Kaju 100 Current Note Till Tenth Date Filmaye Points Vitamin Give To My Left End Right Today Can Calculate the Best Next This Sacrifice to Property That Is Not Have a Flu and Video then subscribe to the Page if you liked The Video then subscribe to the Page In the royal wedding life and bring them according to the left side plus I am calling from there is also the are doing everything say its right to draw a runners example giving a bit this position 103 case no veer vikram 2068 solar affair the mid day At sec-12 moment call mid day At sec-12 moment call mid day At sec-12 moment call 100 909 into the current president subscribe to que one plus route daalunga 1000 shot welcome back to record to 100 udaipur welcome to your parents will have to go to i love you to two to take 44000 Converted To Dissolve In President Vinod A Software Will Return To Soak Back 200 Years No Death Will Go For All Its Right Side Effects Soviet Done With Ispat This Patra Classes This Earthly Otherwise Religious Wallet For The Right One To Right Paneer Calling For This Give 14 Quite Right Way Remember For This Is The Road To 9 4 9 Before I Bath Not So Much To * Parents Before I Bath Not So Much To * Parents Before I Bath Not So Much To * Parents Will Be Composed Dos Plus The Current Note Grammar 12152 Here Look Adjectives and Adjectives But and Regions Parents Welcome 50 Questions Comes from Between Tiles I will return and returning this pass Samrat Lakshmi Ruth to leaf will return for boys will return 510 not available backem known and middle and plus phase back to the end whole soul from illusory roots calculated from left three I do n't know feedback inside equation tree liter For Truth No Dues Will Return Nor Will Do The Same Singer For The Right Side 3450 Gil Written 653 Will Return 797 Reduce 672 Equal To English Hum To 6 7 Vikram 3334 Big Guide Promise Child 10:30 Phanda 3334 Big Guide Promise Child 10:30 Phanda 3334 Big Guide Promise Child 10:30 Phanda Style And Will Return To This Value Way Can Edit 130 209 Indian Will Undo And Use This Problem Safed Til This Please Like Share With Your Friends And Subscribe To Channel And Have Any Questions And 100 The Questions Please Like Comment Subscribe To
Sum of Root To Leaf Binary Numbers
unique-paths-iii
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Array,Backtracking,Bit Manipulation,Matrix
Hard
37,63,212
419
hey guys are doing this as chaser who's not bigger the outcomes I'm making these videos to prepare my interview next month actually it will be like ten days from now or nine days in this video I'm going to take a look at four one nine battleships and a board we're giving a 2d board count how many battleships are in it the battleships are represented with X empty slots are representative we thought we may assume the phoney rules will receive alf added board okay made up only battleships or empty slots battleships can only be placed horizontally or vertically in other word they can be only made up to shape 1 by n or n by one so it's a straight line right for battleship at least one horizontal vertical cell separates between two battleships they're not adjacent battleships cool so this is invalid because you see these battleships actually is connected to this one this is an invalid board that I will not receive as battleship so always have a cell separated between them Wow why the idea I think it would be simple like we just move through as we did in like a Sudoku or in queens which is to pick a point and to check if it is battleship then because we're only give the valid board would check these directions and just go DFS like I just to go straight at line to check where it was stopped right and when it stopped we count as this as a one battleship and go to the next one records the next stop but we there might be some like we're going to this X and we go straight down and then this these points may not be may be might be checked again so we need to mark them as Travis we can use a separate what we can use a separate 2d array to have two keep the flag but if we're allowed to like modify the matrix we could just do England right it's X dot and then we can change like change it to what change it to - or empty string okay what change it to - or empty string okay what change it to - or empty string okay let's change the empty string to means it is Travis so if it is Travis we stop right so yeah so it means so the idea is Travis like loop through all the board if found the battleship mark as check checked we use a we use empty string okay if I found battleship then continue mark right continue mark king connected X count one battleship can't one yeah so that's basic idea so let's start doing it so of course we need a count if you size zero and then we create a function called walk yeah walk a point which is X Y if board XY is already Travis just returned we do nothing right if checked already so if not if poor okay I'll use a switch maybe better switch or XY case empty this would return do not and case dot still we do nothing there is no battle battleship but we need to change it to empty right so for board X y equals empty now we get the X right so this is the interesting part if you get a X if we get an X we need to continue mark the rest battleships right but will we oh we need s need set a flag is that oh I need a flag to mark that whether we are in the battleship or not is in battle ship ok is in x equals a false use this flag to mark a continuous checking of X ok if it is X now we need to set index it to true but if it but if we previous one is not X a previously not previously but if we're not in X right if we are not in X then what it means we are getting to this point to get this point it from not from continuous X checks right so we will count plus one and we said it is index to true and then walked left right so how can I do it we can't just call walk or just to go to the next what we check yeah because we're finally we're going to through from top to bottom left to right so if ever there's any battleships it will not go backwards so we just need to check the right to the right or to the left or to the right or to the bottom there's no way to go to laughs because of our Traverse store that way okay so if X plus one smoother than poor okay I'll create a another one call rose or then cost comms +40 dotnet we are then cost comms +40 dotnet we are then cost comms +40 dotnet we are getting a valid board so it's we don't need to care about the empty case if X 1 is smaller than clothes yeah and poor oh this is X or X means uh mmm the Rose okay my bad maybe I need to row and column this might be easier to understand okay call them grow if we roll plus one smaller than Rose which means there is the next row this next row and board row plus one equals two X which means there's a there is a X to the bottom then we should walk there walk a row plus one column right and if not because the body will be valid if this is not true we can check the column right well plus one equals x then we can walk to row column plus one so okay so if we get this X this will set the next to act two and go walk to this one and go to this one right and finally when there is no nothing we can which know where we can walk we were said what we will set to is set it backs right it's not ended so is index in X equal to false and that we need to set itself to empty as well yeah so that's all what it is trapped for the recursion maybe I think we need to maybe we could just use the flag here I think right is in X is previous second yeah brief previous okay now use the previous prove if crave is empty then we count no we could pass this to X and then pass it to X all right okay oh okay we can use is proof X if it is not and then this would be true right whoo and finally every week hot Oh No but finally we will all start with every point of the board right so loop through all the board it will be or let row of boards or let OH mmm this is not right we need to using that let I what we use for H you know it's the same so or definite rows still be useful boy let us now what do we walk right we want road closed the previous race not X because he's connected he's already Travis in the previous check so ok we start with let's uh and finally we return now let's try to review our code before we submit okay we loop through audit points start with false flag which is previous it's not X and we will walk through it if it is empty we means it's Travis already so we do nothing we skip it we return if it is a start then it's not a start of a battleship we set it to empty to mark it as checked and then return and for the X well X is a little tricky I mean if it is not continuous x check which means the flag is false we count the battleship right and then we will look to the other to the continuous x but there that might be for directions well Wow but we check the points from left to right so if there's a battleship with the top left will be first check right so we just check to two directions which is the tour to the bottom here if the if there is a X below it then we walk to that at the market as empty and then it will actually check it continuously to the last X right for the last X ok here we'll check to the X to the right and then until there's no X this will stop right and in a continuous check these will not be triggered and we will mark each X to empty so when we go into this X actually these three X will be marked as Travis and count with +1 so I think this should and count with +1 so I think this should and count with +1 so I think this should work its run the code cool they submit Wow we're accepted let's try to analyze a time and space complexity for this one Wow first time and pass cool while we has a double nested for loop here so it will attract for the all other points and we're actually using nothing no extra space okay so the time will be in and correct M rows and columns for the board this is a time a space while we're doing the week as we said we do not use the extra space so it's constant but there is a like call stack here we use a recursion well we actually could transform the walk here well it's because we use walk yeah okay so the maximum actually will be for worst case will be max open in Iraq you said it max n this is a cost AK mm-hmm said it max n this is a cost AK mm-hmm said it max n this is a cost AK mm-hmm plus we are doing England modification we change the original board okay so this is it this is the solution for this one but we actually there's a follow-up one but we actually there's a follow-up one but we actually there's a follow-up could we do in one pass we already doing in one pass and use only one a constant extra memory while we use a recursion maybe we could rewrite it into rewriting it to remove this stack call stack yeah we can't do it I think every recursion could be written into a iteration it's possible and without modifying wow this is a trick so we to remove the stop marking the board to remove England modification how we do that okay let's analyze the example well is to the for the first line it's like this okay let's just look at the examples suppose some simple form simple for him like there's something like this for one rule while this could be checked for one pass right and we just account the continuous X groups like X is not at the end the previous when it's not X the head right so actually we could get this for two battleships right and if the next one is like this mm-hmm so this of course this was one mm-hmm so this of course this was one mm-hmm so this of course this was one all right and this is a problem if there is something like okay as more dot here there's something like okay that's it - one here X is - if it's okay that's it - one here X is - if it's okay that's it - one here X is - if it's something like this for this role naively it will be actually one battleships all right but actually it is already checked the previous here is already X so actually should be she modified to 1 0 while this actually give us the hint that actually we could count it wrong row by row and the thing after all the battleships we are not checking the battleships but body by checking the battleships hair head like this is two battleships we look from top to bottom and check the heads this is a head and we got two and this is a head of course for the role or there's only one head right this is the head and this is the head so we get two and then we go to this world and we got this is this the head or not it is actually a body right because there's an X before it so it's 0 well so the idea becomes clear that we could check battleship head come right to the idea the rule is if for a board for like okay I J is head if I minus 1 J and I J minus 1 it means the point to the top and left is not X right if it's not X then this is ahead right no matter where so if these are the head there might be some X to the right but this will not County that's had if there is a Mac X to the bottom but this will not count it as head right cool so actually we could do it with one pass without anything okay let's do it so let I count equals zero a four that I equals zero I swear I'm bored okay we still need to check if it is a head or not ff4 bro calm equals x and the left is not X and B okay so if we it is actually if he's overflowed it's just um undefined in JavaScript so mmm no they look there's a problem so okay to the left is not X it means it might be okay left right okay left calm equals column equal zero or it's not zero then a row column minus one is not X right and the bottom so Row is not rohui's and not rose - one okay oh no it's it is they were - one okay oh no it's it is they were - one okay oh no it's it is they were last one or row plus one come is not two equal to X right so this is the condition of its being a head if this is true then we come across one and then finally we return account wow this is perfect oh there is a assignment to constant bearable oh submit yeah you're accepted so this is actually it's better it's a simpler and okay the time would be the same Oh M space no extra space no claw stack it's constant and input or is not modified while this super cool but I must say the first solution is more jet more general because for the second one the second there's a case that it's restricted to valid boards you forget in the embedded port like this it's impossible to handle this but if we have to say if we are going to check if the pink what is that it or not we better use this one like the backtracking say if like this we could check that check the X here like if it has several directions that connected to another X we can just do return or return false or anything yeah so 4 divided cases this one is better but this one is more general - yeah ok so this one is more general - yeah ok so this one is more general - yeah ok so that's all for this problem happy helps you next time bye
Battleships in a Board
battleships-in-a-board
Given an `m x n` matrix `board` where each cell is a battleship `'X'` or empty `'.'`, return _the number of the **battleships** on_ `board`. **Battleships** can only be placed horizontally or vertically on `board`. In other words, they can only be made of the shape `1 x k` (`1` row, `k` columns) or `k x 1` (`k` rows, `1` column), where `k` can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). **Example 1:** **Input:** board = \[\[ "X ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\]\] **Output:** 2 **Example 2:** **Input:** board = \[\[ ". "\]\] **Output:** 0 **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is either `'.'` or `'X'`. **Follow up:** Could you do it in one-pass, using only `O(1)` extra memory and without modifying the values `board`?
null
Array,Depth-First Search,Matrix
Medium
null
29
hello everyone let's try to be a cheat code ninja today this problem is amongst the top 50 questions asked in Facebook interviews so let's look at it in this question we are given a dividend and a divisor and we have to perform the division operation without using multiplication division or the mode operator we also have to get rid of the fractional part in the output we also have to avoid some integer overflows so let's come up with an intuitive solution for this let's look at this simple example where we have to divide 10 by 3. as we have learned in school that division is nothing but multiple subtractions we will repeatedly subtract 3 from the dividend until we cannot do it anymore hence the new dividend will become 7 4 and then finally 1. and finally the dividend is less than the divisor hence we cannot continue this operation we could do this operation only three times hence the result is 3. and the time complexity would be we'll have to do this subtraction operation n by D times and the space complexity would be constant this time complexity of n by D would result in a time limit exceeded in lead code let's try to optimize this algorithm by reducing the number of subtraction operations let's look at a new example let's keep three variables in it decrement would represent the amount to subtract and counter would represent the amount to add in the output in case of a successful subtraction initially there will be 3 and 1. now let's subtract by three the dividend becomes 29. and let's add 1 to the output now let's double the decrement variable and similarly let's double the counter variable as well now let's subtract 29 by the new decrement hence the dividend becomes 23 now let's increment our output by the counter variable let's again double the decrement and the counter variable now let's decrement the dividend by 12. hence the dividend will become 11. now let's increment the output by the counter variable let's double the decrement and the counter variable again now we cannot subtract decrement from the dividend anymore hence we'll reset decrement and the counter variable to their initial values 3 and 1 respectively now let's subtract 3 from 11 and let's increment output by the counter variable let's again double the decrement and the counter variable now let's decrement the dividend by 6. let's increment the output by the counter variable let's again double the decrement and the counter variable now since 2 is less than 12 we'll reset the decrement and the counter variable to their initial values 3 and 1 respectively now since the dividend is even lesser than the original decrement will stop our computation hence the output would be 10. the time complexity would roughly be log of dividend base divisor because we are doubling the divisor value and always trying to divide by 8. the space complexity would be o of constant now let's Implement our solution let's take the absolute value of a divisor and our dividend as it will simplify our solution our output is going to be negative if one of the divisor or the dividend is negative and the other one is positive if either of these conditions is true then our output will be negative now let's initialize our output to be zero Del a is greater than equal to B we will try to subtract from it let's initialize our counter to be 1 and our decrement to be the divisor now here we will double our counter and the decrement on each successful subtraction hence we'll check if a is greater than equal to the decrement now we'll subtract the decrement from a now we'll increment the output by the counter variable now let's double the counter and the decrement variable here we are just doubling these two variables now let's return the output if the negative condition is false else will have to make it into a negative number now we can return our output after checking the Overflow condition as per the question the output must remain in this range these values are 2 raised to the power 31 and 2 raised to the power 31 minus 1. now let's submit our solution as you can see our solution is accepted if you have any concerns regarding this Solution please mention in the comments if you thought this video was helpful please leave a like And subscribe to the channel thanks for watching
Divide Two Integers
divide-two-integers
Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-2.7335` would be truncated to `-2`. Return _the **quotient** after dividing_ `dividend` _by_ `divisor`. **Note:** Assume we are dealing with an environment that could only store integers within the **32-bit** signed integer range: `[-231, 231 - 1]`. For this problem, if the quotient is **strictly greater than** `231 - 1`, then return `231 - 1`, and if the quotient is **strictly less than** `-231`, then return `-231`. **Example 1:** **Input:** dividend = 10, divisor = 3 **Output:** 3 **Explanation:** 10/3 = 3.33333.. which is truncated to 3. **Example 2:** **Input:** dividend = 7, divisor = -3 **Output:** -2 **Explanation:** 7/-3 = -2.33333.. which is truncated to -2. **Constraints:** * `-231 <= dividend, divisor <= 231 - 1` * `divisor != 0`
null
Math,Bit Manipulation
Medium
null
445
Hello friends welcome to code Sutra let's all lead code problem number 445 add two numbers in this problem we are given the head of tool linked list for example these are the two link lists and we have to add them and return the sum of these in the form of a language for example what is the sum of seven two four three and five six four the sum is equal to 7807 and we have to return this in the form of this language so how do we go about this first of all let's observe and draw out the intention the first thing is the addition should always start from the least significant bit that is you cannot start your addition from here or here you have to start your addition from these two endpoints that is the first observation that we have now let's get into the second observation or I would say the corner cases what are the corner cases is when there is a carry for example six plus four is ten you cannot just write 10 in the node instead you should write 0 at that node and you should carry 1. so that is one corner case what is the second Corner case that you have the second Corner case is suppose we have eight two three plus three one three something like this what happens though the length of both of the linked list is three we will be having an additional one at the end that is we have to look at all the corner cases that is the second thing now how can we implement this see one thing is we can use a recursive caller reverse the list but it is never advisable to modify the actual given linked list it is never advisable so what can we do we can actually use the stack what will stack do for example let's put all this element in this into the stack 7 2 four and three now let's have another stack this will be S1 stack and this will be S2 stack this will be 5 this will be 6 and this will be 4. now whichever is at the top of the stack is nothing but the least significant bit so what we can do we can have two variables one to keep track of the sum and we will do the sum and we will update this so we create a new node which is of the value of the sum that is equal to 7 but don't forget when we add the next node that is six plus four and we'll be removing this from the top of this type the next is six plus four but what is 6 plus 4 that is equal to 10 can we add 10 no we cannot add 10 but we have to add so what we'll be doing is we will be creating a node 0 that is the first thing then we will be pointing the new notes tail to the next node that is new node.next this is the first step is node.next this is the first step is node.next this is the first step is equal to the answer already existing answer whatever was our answer will be pointed and our answer will also be updated to the new node this is what we'll be going to this is a very too simple step that is for example this was our existing answer now you want to add something at the mean most significant bit what you will do will change this was our answer previously what we are going to change is we are pointing this new node and we will point to this and we will change our answer to point to this as simple as that is how we add a new node very simple right so but keep the corner cases in mind whenever we are doing this we also have one more additional variable to keep track of the carry so this will be our pseudo code we'll be having two stacks and we will add all the elements from link list one and two to this tags after that we will be having two variables one is sum one is carry and we will initiate our answer to null that's the first thing then while at least one of them has an element we should key keep on doing the addition that is we will stop this while loop only when both of them are empty now what happens if one of them have elements we will just add that particular element to the value and we will also add carry to the sum then what will be a new carrier new carry will be updated that is equal to sum by time for example we get 30 what will be the new carry will be one so that is what we are doing now we are creating a new node and we are changing for example we created a new node and this was our existing answer we just point to this and we will update our answer to this that is what we are doing this in this step and don't forget we have to change the sum to 0 finally and finally what we will be doing this is one of the corner cases that even after doing the sum if there is a carry left over we'll be doing the same operation and finally we will be returning the ends see this problem can be solved with many approaches but it is never advisable especially in an interview to modify the original given list so we will be using this particular approach and this is the code which is very straightforward and finally we'll be returning the answer thank you for watching the video please do like share and subscribe
Add Two Numbers II
add-two-numbers-ii
You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. **Example 1:** **Input:** l1 = \[7,2,4,3\], l2 = \[5,6,4\] **Output:** \[7,8,0,7\] **Example 2:** **Input:** l1 = \[2,4,3\], l2 = \[5,6,4\] **Output:** \[8,0,7\] **Example 3:** **Input:** l1 = \[0\], l2 = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in each linked list is in the range `[1, 100]`. * `0 <= Node.val <= 9` * It is guaranteed that the list represents a number that does not have leading zeros. **Follow up:** Could you solve it without reversing the input lists?
null
Linked List,Math,Stack
Medium
2,1774
1,903
hey everyone how's everything going this is steve today let's go through an easy problem lead code 1903 largest odd number in the stream let's take a look at the problem first you're given a string num representing a large integer written the largest valued odd integer as a string that is not empty substring of none or an empty string if no on integer exists and then it further gives a definition which everybody knows a substring is a continuous sequence of characters within a string let's take a look the given input num is a string 52 the output is 5 why because this is the largest odd value integer 52 is an even number so the largest odd integer is five right and then let's take a look at the second example which is four two zero 6 this one is an even number no matter what whatever we do every single digit of this given string is an even number so there is no odd integer exists in this given no substring that is can be interpreted into a odd integer so we written an empty string the last the example three shows us three five four seven this one itself the given string itself is already an odd number so we just return the entire thing itself so how do we approach this problem these are all the given three examples how do we approach this problem you see the constraint is the number is length is smaller than which means it can go up to 10 to the power of five so this is way beyond the in the integer maximum value so apparently we don't want to parse all of them use whatever language of your choice to parse it out to an integer that's going to throw exception overflow or whatever error or exception right so what we want to do is actually pretty simple we just want to check every single digit beginning from the right end we move towards the left end as soon as we find an integer on the right side that is an odd number we can just what we can just return the string from the beginning index 0 all the way up to that integers index right this is way the way to solve this problem this will guarantee to give us the largest odd valued index odd value integer in this given string why is that we can just think about that say if this one like 27 7 is an odd integer right 27 is also an odd integer 427 is still so that's 5427 right so as soon as we find the odd integer on the most right side then we can just return from the very left end which is index zero all the way up to that index right so that's the way to solve this problem pretty straightforward the reason why i want to talk about this easy problem is that people tend to overthink about this problem they might think of because like say this explanation kind it's it kind of hints that you need to find all of the substrings right say substrings on 5 2 and 52 is it true that you need to find all of the substrings of a given string for this case it's going to be say three five four two seven so five sub strings already and then you want to find 35 354 3432 35 427 do you need to find all of these substrings in order to find the maximum value odd integer no that's not the case so do not over think about in fact if you go that route you feel brute force to find all of the possible substrings is going to create a lot of extra time complexity probably you're going to end up in time limit exceeded exception right so you don't need to do that's the whole point i want to bring up this problem so now uh let's oops what's going on let's just to put this idea into the actual code which is to write a simple for loop okay let's see uh 4 and i equals we'll start from the very right end which is num length minus 1 i greater than or equal to 0 i minus so we'll check if or pass it integer past so now we can use pass that is because we're only passing every single digit so it's for sure never going to exceed the integer maximum value in java or in whatever language of your choice so none chart at oops i divided by 2 not equal to 0 that means this is the odd value if that is the case we'll just return num substring 0 to i plus 1 because the substring the first index is inclusive the second index is exclusive that's why we need to plus one here that's it very simple and then in the end if there is none we just written an empty string now let's run code error chart cannot be converted to string yeah that's correct so what i need is i need to attach an empty string to this so that it's a string instead of the character in java so that it can be parsed using integer pass int okay this looks good now let me hit submit all right accept it very simple and straightforward again just don't overthink the problem just use the most straightforward and easy way to solve this problem largest odd number in the stream um if you like the solution of the problem or just the problem yourself or you think this video helps you understand the problem please do me a favor and hit the like button that's going to help a lot with the youtube algorithm and i really appreciate it and don't forget to subscribe to my channel turn on the bell notification so that each time i publish a new video you'll get it instantly so and also feel free to check out all the other videos that i've posted on my channel it's about depth first search breath first search dynamic programming you name it all different kinds of videos to help people better prepare for their upcoming coding interviews yeah that's it so hopefully i'll just see you guys in just a few short seconds in my other videos thank you so much for watching
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
114
Hello friends I'm A Cloud Solutions are great at Microsoft and my aim is to empower every single person to be better at technical interviews keeping with that goal in mind today we are going to do a very interesting lead code problem called flatten the binary tree to linked list problem and if we see some of the popular companies who already asked this question there are companies like Amazon Google Facebook Microsoft Apple Bloomberg Uber Goldman Sachs buy dance and lift so that's why I'm paying my utmost attention I hope you also enjoy the video so this is the lead code medium problem and also very well like problem basically we are given the root of a binary tree and we need to flatten this tree into a single linked list okay so this is the whole problem statement now the question is how do we actually flatten it in the link list and what are the rules for it so the first rule is that the linked list should use the same tree node class where the right child pointer points to the next node in the list and left child pointer is always null so what does it mean by this definition suppose we are given a tree or binary tree that looks like this in the example basically the linked list structure would look completely different it would look something like this where all the nodes are always on the right side and nothing or the left child is always going to be null so it is going to be a one-sided tree it is going to be a one-sided tree it is going to be a one-sided tree basically the second condition we are asked is that the linked list should be in the same order as a pre-order in the same order as a pre-order in the same order as a pre-order traversal for or any binary team so the question is what does a pre-order question is what does a pre-order question is what does a pre-order traversal means suppose this is the tree that we are given the input if we want to do a pre-order traversal the rules to do a pre-order traversal the rules to do a pre-order traversal the rules for pre-order traversal is basically for pre-order traversal is basically for pre-order traversal is basically first we iterate over the root node then we iterate its left child and then we iterate Its Right child so as long as the left child exist we will keep going in the left Direction once left child is no longer existent we will go and go for the right check and always we will first iterate the root child if we do that basically in this case the pre-order basically in this case the pre-order basically in this case the pre-order traversal is going to look something like this so first we are going to iterate to the root node so root node is one okay so first we are going to visit one then again left child so left is also two so we will visit two then again left child three so again three now we do not have any more nodes below this one this is null so because this is null now we will see that whether its root node honey had any write nodes or not and yes it does have a right node so we will start visiting the right nodes again and then we will keep on repeating the same process so now we have visited everything on the left subtree so now we will start iterating on the right subtree so if we go over here now we will visit node number five and then node number six so this would be the pre-order traversal now the question is pre-order traversal now the question is pre-order traversal now the question is that for the given input tree uh what should be the answer look like so we have to consider a couple of items uh in order to generate the answer first one is that it has to be the pre-order is that it has to be the pre-order is that it has to be the pre-order traversal and then it has to be like a one directional tree okay so uh keeping with both things in mind the tree structure and the answer is going to look something like this where the first node is going to be one and then the second node is going to be in the pre-order traversal too but two we are pre-order traversal too but two we are pre-order traversal too but two we are going to mark it on the right side the next one is going to be three so again 3 is also going to be marked on the right side and if we keep on repeating the same process basically This Is The Answer tree that we need to return that represents the flattened binary tree that we are given as the input so this is the binary tree and this is the linked list version of it and that this has been flattened uh now in terms of like input and output basically the input for this one is going to be something like this so basically this is going to be the original input that we are given that represents this binary tree and after flattening it are the tree is going to look like this and we need to return an output that looks like this so basically this is the whole ask of the problem now let's see that what is the approach we can take okay suppose this is the most basic input or most basic binary tree we are given now in any tree problem what we are going to do is we will try to see that what would be the solution for this one and then using a recursive approach we can actually solve it for much bigger problems because that is common property entry if we see most basic structure of a tree basically it has a root node this root node currently has a left child and it also has a right child okay so let's mark some values so it makes sense for us to understand so this value is 1 this is 2 and this is three suppose these this is the given tree now if we want to flatten this one we will have to keep track of two items first one is that it has to be the pre-order traversal so has to be the pre-order traversal so has to be the pre-order traversal so pre-order traversal we already know the pre-order traversal we already know the pre-order traversal we already know the value is going to be 1 2 and 3 in this order second thing we have to keep track of it is that it has to be a flattened version and everything in Just One Direction okay so what does that mean that structure has to look something like this where all the three nodes are just the right Childs nothing on the left child keeping with these two items in mind the answer in this case is going to look something like this and notice in this case the root node Remains the Same this left child is come as the first right child of this root node and the right child of this root node or this node to becomes this Note 3 so basically if we just see what are the actions we did in order to generate this answer first of all we took this left child and currently this left child does not have any children of its own so there is no like uh left child over here or right child over here right but if we see in the answer currently for this left child or this node it has a write node and that right node is whatever the previous Roots right child was so what we did is first of all for the existing left child we uh had the left child dot right so right child of this original live chat which was originally null because it does not have any values over here so this value was originally null we marked it as the root dot right and which we can see over here that in this case uh this root dot right this is this right child we mark it over here okay so this is one thing we did second thing we did is in the answer currently this root dot left this left node actually has some value over here but in this in the answer this left child is null so we will also do that so currently this root dot left is going to be null okay that is also the second thing we did what is the third thing we did is that currently this root dot right this value is pointing towards the right child but rather than pointing it towards the right child now we are pointing it towards the left child which we can see over here clearly so the third thing we are doing is that root dot right that was originally pointing towards the right pointer now it is pointing towards the left child and that's it that is the whole logic to solve this problem and how we have been able to generate this let's try to see it for a bigger version and we will keep on repeating the same process these three items so now we will try to apply these three rules for this given tree and this is the original bigger version so first of all we will recursively try to find a smaller subset we will do these three things and keep on repeating the same process until we find the full answer so first uh if we start iterating from this root element first of all what we can see is uh this is one of the candidate for the left sub child where we can actually apply these three rules so let's apply that so after applying these three rules basically uh for this particular portion this 2 3 and 4 the answer is going to look like this 2 3 and 4 and if we just mark it over here we will get a tree structure that looks like this now in this case now this is the perfect candidate because we do not have a full subtree so basically we have this left sub portion we have this right sub portion we have this root node and again we are going to apply the same logic so if we apply the same logic in this case again second recursive second recursion what we need to do is for this particular left node basically we will need to see that what is the right most tail and the rightmost tail is four so this 4 needs to point over here and this one rather than pointing to this 5 on the right child this needs to point over here and the left child is going to be null so this is all we need to do so if we apply these 3 logic basically first of all we are going to have our root Node 1 as the right child we are going to point over here rather than pointing towards this file so if we point towards this portion we will get the values to 3 and 4. and if we see currently this 4 is now pointing towards this value number five so that we are going to Mark over here and basically we are going to have values 5 and 6 in this case and if we see the left portion is always going to be null for every single one of them and this is the answer we need to return I know I have not drawn this properly so let me just do it properly and this is the most simplest approach what we did is we first of all try to find the solution for a smaller subset we find the base cases and the rules we applied those rules to a bigger case and we using recursion we are able to generate this answer and this is a very simple answer to understand if we see time and space complexity in this case the time complexity is actually going to be go of end and if we see space complexity the space complexity is also going to be Big O of n because for recursion it is going to need to store some runtime stack so first of all we are going to create a helper method that we can use as our recursive method so let's just do that now in this helper method first of all we will check that if the given node is null we can simply return null second thing we can check is that if the given node is like a leaf node which means it does not have any left and right child then we can simply return that node as it is now we will have to find the leftmost tree node for any subtree so we will have to create a new tree node called left tail and we are going to call the recursive function again and same way we will also have to find the right most tail so we will also do the same thing and we will call the recursive function again now will come the meat of our logic so first of all we will check that if the left tail value is not null if it exists then we will have to put those three conditions that we discussed earlier first of all for this left tail value which means the leftmost value of any subtree we are going to Mark Its Right child to point towards the node.right then for the existing node.right then for the existing node.right then for the existing node dot write value we are actually going to point it towards the node dot left and in the end the node.left value that we in the end the node.left value that we in the end the node.left value that we currently have some value pointing towards we are going to mark it as null basically that's it now in the end we need to return the right tail or the rightmost element so we are going to check that if the right tail is equal to null then we need to return the left tail if it is not null we will return the right field and now all we need to do is from our main method we will have to call the flattened tree method with the first root node let's try to run this code seems like our solution is working as expected let's submit this code and our code runs pretty efficiently compared to a lot of other Solutions so which is great I will be posting this solution in the comments so you can check it out from there thank you
Flatten Binary Tree to Linked List
flatten-binary-tree-to-linked-list
Given the `root` of a binary tree, flatten the tree into a "linked list ": * The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`. * The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree. **Example 1:** **Input:** root = \[1,2,5,3,4,null,6\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100` **Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Linked List,Stack,Tree,Depth-First Search,Binary Tree
Medium
766,1796
1,615
hello everyone welcome back here is vanamsen today we got a very interesting coding Challenge from lead code maximal Network rank so uh we will try to involve graph and additional logic to improve upon our recent implementation so trust me by the end of this video you are going to feel like a coding ninja so let's dive in all right so let's first understand the problem we are given a number and representing cities and a list of Roads connecting those cities so each city is represented by an integer index and the goal is to determine the maximal network rank between two cities and the network rank of Two Cities is defined as the total number of Direction connected roads to both cities so given this example on the screen so optimal solution is 4 and why because CT 0 and City one have total of four connections so one two three and four and also we are counting this particular Road uh just once or not twice so now when we understand the problem uh how to solve it so we will compute the number of rows connected to each City and find the city with the maximum and second maximum roads so then we will calculate their combined network round so uh sounds simple right so let's get into coding so first we will create a list called a degree to store the number of Roads connected to each City so calculate the degree for each City and it will be degree equals zero times n and for U V in roads degree U plus one and degree V plus 1 as well so now uh identify the highest and second highest degree so sorted degree will be sort that sorted set degree reverse through and Max degree will be sorted degree 0 and there is no second Max degree only one unique degree then set to zero so second Max degree will be sorted degree 1 if length of sorted degree greater than one else zero and now count cities with the highest and second highest degree Okay so uh now we need to identify the cities with the highest and second highest road connected so we did it and we will do this by uh we did it by sorting the list and picking a position 0 and position one so the top two values will give us the maximum and second maximum degree and if there is only one a unique degree in our cities our second month's degree should default to zero and this is a key Edge case and then let's continue so uh now if there is more than one City with the highest degree we need to check how many of them are directly connected so this is a crucial for our final computation so Max count will be degree count Max degree and second Max count will be degree count second Max degree and if there are multiple cities with the highest degree than if Max count greater than one directly connected will be sum one for UV in rows if degree V equal Max degree and possible connections will be Max connections time Max count divided without remainder by 2. and if possible connection equals direct connected then return to times Max degree minus 1. and return to times Mark degree in order case and now final so if there is only one city with the highest degree so the combined Network rank of two cities with the same degree would be then 2 times degree minus one only if all such cities are directly connected otherwise it's just 2 times degree and finally if there is only one city with the highest degree we will check if its connection with the cities having the second highest degree so let's implement it direct connection to second sum one for UV in rows if degree U degree V in Mark's degree second Mark's degree and second Max degree and if second Max count Direction connect to second and return Max degree plus second Max degree minus one and return Max degree Plus second Max degree okay so this is our implementation uh so let's run it to First some simple test cases so yeah all good and it's working correctly so now let's run this for unsynthesis cases so hopefully it will run and yeah all good and our implementation bit 99 with respect to runtime and also 99 with respect to memory so it's quite efficient and uh also much faster than naive Brute Force approach uh yeah I have also solution for brute approach and for this uh with test cases edge cases so uh yeah awesome uh it works perfectly and now for those of you interested in solution in other programming languages like go rust and C plus I will provide implementation in the video description below and thanks for tuning in I hope you found this session insightful and if you did don't forget to smash the like button share and subscribe for more coding session and remember coding is about getting their right answer but also about understanding the problem and crafting the solution optimally because it's very important to understand the problem and if you have time try to optimize it and also have you in your toolkit optimize solution as well so keep practicing happy coding and see you next time
Maximal Network Rank
range-sum-of-sorted-subarray-sums
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either** city. If a road is directly connected to both cities, it is only counted **once**. The **maximal network rank** of the infrastructure is the **maximum network rank** of all pairs of different cities. Given the integer `n` and the array `roads`, return _the **maximal network rank** of the entire infrastructure_. **Example 1:** **Input:** n = 4, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\]\] **Output:** 4 **Explanation:** The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once. **Example 2:** **Input:** n = 5, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\],\[2,3\],\[2,4\]\] **Output:** 5 **Explanation:** There are 5 roads that are connected to cities 1 or 2. **Example 3:** **Input:** n = 8, roads = \[\[0,1\],\[1,2\],\[2,3\],\[2,4\],\[5,6\],\[5,7\]\] **Output:** 5 **Explanation:** The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected. **Constraints:** * `2 <= n <= 100` * `0 <= roads.length <= n * (n - 1) / 2` * `roads[i].length == 2` * `0 <= ai, bi <= n-1` * `ai != bi` * Each pair of cities has **at most one** road connecting them.
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
Array,Two Pointers,Binary Search,Sorting
Medium
null
11
hello everybody today we're going to be doing leak code number 11 container with most water let's start by introducing the problem given n non-negative the problem given n non-negative the problem given n non-negative integers a1 a2 to a to the N where each represents a point at coordinate I comma a to the I and vertical lines are drawn such that two endpoints of line I as at is at I comma a I and I come okay screw the introduction to this problem I don't know about you but I find that to be extremely confusing this problem is not that difficult I'm going to introduce the problem myself so let's take a look at the input is going to be an array of numbers and at each index the number represents the height of a wall so if you look at the first index here the first number is one which corresponds to this first wall here of height one the second index with index one is eight which corresponds to this red line here of height eight so what are we trying to do here we're trying to return the container with the most water so a container has two walls which are the height and the height of the two of the container is the minimum value of the two walls so here the this container with the red walls here one of the walls height is eight the other wall is height seven so the height of the container is seven and the width of the container it's just the distance between the two walls so the distance for this container with the red walls the first wall is at index one the second wall is at index eight so the distance is seven so the width of that container is seven so what you want to do is you want to look at all the container or you want to return the container that holds the most amount of water so if you're ready to solve this problem with me come to the whiteboard but as always I encourage you to solve the problem first and then come check out the video so if you're ready to solve the problem let's go to the whiteboard to solve this problem we're going to use something called ratcheting so what ratcheting is we have a pointer here at the first index we have a pointer here at the end index and that every stage where we are either going to decrement the ending pointer or we're going to increment the starting point sir so we're also going to be keeping track of the height of the current container the width of the current container as well as the air of the current container at the end of the algorithm we'll just return the maximum area that we have seen so what are the conditions where we will either increment the starting point or increment the ending pointer well what we're going to look at is the height of the two walls that the pointers are pointing at we will always want to keep the higher height of the two walls because that's going to give us our largest possible area so every iteration we will first measure the size of the container then we will either increment the starting point or incrementing increment the ending port decrement the ending pointer depending on which wall we want to keep so let's go ahead and go through running this algorithm and I think you'll understand how it works so first we're starting at index 0 and index 8 and next year we have a wall height of 1 and at index 8 we have a wall height of 7 so that gives us a container height of 1 and a width of 8 which gives us an area of 8 so because our starting point err is shorter than our ending pointer we will increment the starting point err so now our starting point err is a wall size of 8 and our ending pointers of wall size of 7 so that gives us a height of 7 and now our width is 7 which gives us an area of 49 so we will now decrement the ending pointer because our wall height is shorter our ending pointer so now we can see that our wall height our container height is 3 and the width of that container is 6 giving us a total area of 18 now because our nd pointer is shorter than our starting point er we will decrement the ending pointer so now both of our walls are of height 8 giving us an end the current width is 5 giving us an area of 40 so what I want to talk about now is we have two walls that are the same height right so how do we know which one to decrement well what I'm going to tell you is it actually doesn't matter which one we pick and the reason why it doesn't matter which one we pick is the only way that we can have a container size between these two points that is greater than the container size of these two walls is to have two walls between these walls that are higher so to illustrate that I'll just show you what if we had two walls here that were both of height 100 well if we decided to first increment the starting point and then we decided to decrement them then we would hit a wall of 100 and then we would have to start decrementing the ending pointer right so eventually we would hit this container that had a greater size than the current container were on so even though we're not getting all the possible container volumes it doesn't matter because the only thing we're looking for is the maximum container volume so we'll choose to just decrement the ending pointer so now this gives us a height of 4 and a width of 4 giving us a volume of 16 so we will decrement the ending pointer again this give us a height of five and a width of three giving us an area of 15 so we'll decrement the ending pointer again giving us a high of two a width of two in an area of four finally we will decrement the ending pointer again giving us a height of six and a width of one giving us an area of six so you can see going through this algorithm our maximum area is 49 so we would return 49 as our answer so what's the time complexity of this algorithm well the time complexity this algorithm is Big O of and the reason why that is because we are ratcheting from the end to the start until those two points meet and once those two points meet we're done so we only look at every item one time which is why this is Big O and the time or the space complexity of this algorithm is constant because we are not using any extra space to solve this algorithm the only space we're using is the input array so we use no extra space let's go through coding this algorithm let's start by defining three variables well first need a starting point er we need an ending pointer and then we'll also need the area to start to zero the end can just be equal to the length of your a minus 1 to get the last index and the area will just start off with a zero so while the start is less than the end we'll want to get two things we will want to get the width of the current container and we'll also want to get the height of the current container and we'll also want to update the area so what's the width is just going to be equal to the n minus the start the height is going to be the minimum of the index at the start and the array ending index and to update the area we just need the maximum at the current area and the width multiplied by the current height and the last thing we need to do is just make sure that we're properly updating our starting and ending pointers so if the start is less than the end then we'll increment the start otherwise will decrement at the end and then the last thing we need to do is just return the area you okay so now that we've solved the problem let's take a look at the results so here are the results of the algorithm that we wrote there's really not too much to explain here the this is the optimal solution to this problem in order to solve this problem we have to find the optimal or the largest container and define the largest container we need to go through and we need to look at every single one of the walls at least one time so this was a fairly simple problem hopefully you were able to get it without too much trouble and I hope you enjoyed the video and I hope to see you next time
Container With Most Water
container-with-most-water
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`. Find two lines that together with the x-axis form a container, such that the container contains the most water. Return _the maximum amount of water a container can store_. **Notice** that you may not slant the container. **Example 1:** **Input:** height = \[1,8,6,2,5,4,8,3,7\] **Output:** 49 **Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49. **Example 2:** **Input:** height = \[1,1\] **Output:** 1 **Constraints:** * `n == height.length` * `2 <= n <= 105` * `0 <= height[i] <= 104`
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle. Area = length of shorter vertical line * distance between lines We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
Array,Two Pointers,Greedy
Medium
42
230
Yes, hello developer child Gary, it's me. Today's prole problem is this 130th k-th small list 130th k-th small list 130th k-th small list element in a quest. i has a width, so the cheat lane route is given. 2 Heejin Lee This is a problem that can be passed through the kth step element in the tree. If such a tree is given and k is 1, then the first step element can be returned. 123 Buying, the first smallest element is the enemy banker, and the top is the number 1. If you look at the second example, there is a tree like this, K is 3, and you just need to take the third smallest argument as 2nd, but here it is 3, so it seems like you just need to take 3. Let's solve it. First, I use a binary tree and an array as arguments. I created a function that receives it. If there is no tree, the function will be important in this turn. Otherwise, we will release Cherry's deli in the array received as an argument and look at the resume function. Now, the binary tree on the left of the binary tree. I put it as the first argument and put the array as it is. And 5 Oh, I would have called it by inserting it again on the right side. And the function called efs can be added from the function given as my problem. 5 I make the hair that will be given as an argument. What is d f 2nd fl dfs? The function is called Hunchback. Then, if you call it, yes, it will resume, and it will go through all the trees in the s panel that we have created, and values ​​will be through all the trees in the s panel that we have created, and values ​​will be through all the trees in the s panel that we have created, and values ​​will be pushed here. And when that function is finished, it will be beheaded once. So, it will be sorted in the order of unknown order. Umm, since it is the 155 5kth, it starts from index 0, so it is short to find the subtracted value from Real and make 2 turns. The example passes normally, but the spelling of the light is wrong. 4 You can check that it passes normally. Yes, I do it like this. I solved it, but I think there is a way to solve it without this sort function. 4 So, it would be good to try solving it like this and find a way to solve the soft alcohol without going through it one more time. That's the end of today's video. If you like this, please click like and subscribe. Thank you.
Kth Smallest Element in a BST
kth-smallest-element-in-a-bst
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_. **Example 1:** **Input:** root = \[3,1,4,null,2\], k = 1 **Output:** 1 **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], k = 3 **Output:** 3 **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104` * `0 <= Node.val <= 104` **Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,671
162
hi everyone once again welcome to the channel today in this video we are solving a very famous problem find peak element this problem is almost got asked in all the top giant companies and in last six months this problem got asked itself 17 times in let go as per the lit code tagging so this is very important a peak element is an element that is strictly greater than its neighbor given an integer array nums find a peak element and returns its index if the array contains multiple peak elements return the index to any of the peaks you may imagine that the nums at the minus 1 index is infinite negative infinity as well as nums at the right side of our index so this is given as a negative infinity so in the first example as i can see we have this 4 element 1 2 3 then 1 so if we go we can see that 3 is the peak element because on the 3 we can see the left side is smaller and the right side is also smaller so this is the peak on that so the index of 3 is 2 we need to return the 2 as our answer similarly for second example let us understand this over here more picture really so this is the given array let us try to represent in a some kind of graph lets me put this point so let us say this axis on the 0 and 1 is over here somewhere 2 is somewhere over here and then we are getting 1 again back and then 3 is let's say put it somewhere on here 5 is more upper than so 6 is let's say somewhere here and 4 is in between 5 and 4 so like this if we can see so we can try to put graph like connect this all the dots so 1 3 5 then 6 and after that 4 is over here so as we can see by the picture itself the this is the peak element one is this another peak element is this so we can return any element index so for 2 the index is 1 or for 6 the index is 5 as in array index is 0 base so we can return so let's see what is the answer here the 5 is written but we can written like it is also mentioned over here so how to solve this kind of problem so one of the straightforward you should have a mindset like you need to just try to find out the solution don't worry about the time complexity in the first solution you have to just try it and find out which solution so as we can assume that like this negative infinity on the left boundary and the right boundary is the also the negative entry then there must be some element in this array is the peak element so how to find that element so what we can do we will start comparing two adjacent element at a time so we will compare one and two so which is let's say if we are running this for loop i then we compare i and i plus one element and here the condition as we know the left side of i so for this i we will try whether it is a peak element or not we know the left side there is a minus infinity sitting on it so what we need to do here we need to compare if nums of i so we will see if we will check if nums of i numser i is greater than the nums of i plus 1 if we found that which means we found the peak element and the i is the answer for that we need to return the index so this is the answer itself so here we will check is 1 greater than 2 no then 2 is greater than next one yes it is so we can written one over here so that is the one approach to solve this problem but in this approach like for the worst case data let's say if the data is given like 1 2 3 and 4 let's say only 4 element in that case we will not find this and also as we are using i plus 1 so we need to run the loop only i less than n minus 1. so the last element will not cover over here once you reach in the end if the answer is not return you will just return the index of this element which is ah length of our nums dot length minus one the index of the last element basically so this is the answer as you can see here the three is less than this guy but the right side as we already given in problem is negative infinity which is smaller than 4 so hence we can return it so you can pause the video and try to code this yourself it is very straightforward not much complex so here is the code i have already written for that what i explained here this is the simple iterate over the numbers till the n minus one and compare the two edges and element if nums of i is greater than numbers of y plus one return i add otherwise it but as you can see in this problem it is asking like solving this in o of n time which is very obvious but can you do it in o of log of n so let's try to think how we can solve this logarithm so whenever we need to optimize the linear solution in logarithmic solution then there must be a some hit in your mind like we need to find out and try it and somehow apply the binary search so that only we can get the time complexity log of n but as we study like in binary search we most of the time encounter and where the data is sorted in some form and then we try to apply the binary set but here the data is not sorted at all but how to use the binary so first of all let's say just use the binary search principle so we will have low or left or the right or the uh high in index starting from like this is zero index and this one is the n minus one now we will be on the somewhere find out the mid element now what we need to do at mid so we will compare mid element with the mid plus one why we need to compare this mid plus one then only we will try to ah like take the assumption which half we need to move so let us see in this graph itself if somehow the mid is this element and if i compare ah 3 with the 5 as you can see this is an increasing curve this is a increasing curve so the left side this 3 can't be the peak element so 5 or there might be a more element on the right side as we already identified that like 3 is less than 5 so we are sure that there is a minus infinity at the right rightmost index so we can see that this 5 can be a peak element or there may be any element on the right of 5 because 5 is on the uh increasing side of this slope so we update our left pointer to mid plus 1 here mid plus 1 so left to this and we will keep trying this again same if it is possible so we will again get the mid of 6 is the mid now we compare is 6 with the next element which is mid plus 1 so 6 is greater than 4 yes and the previously we are coming the negative infinity is also there if it is nothing so yes we can say that this 6 is the our peak element but how we can conclude we cannot conclude here we just update our right point array over here right to mid as we so if we have this mid over on this slope and we are comparing mid plus 1 mid on lies on the downward slope then we will reduce the right half we will discard the right up as we know like this mid element has a element right side which is lesser than its and there must be a left side some elements if nothing then minus infinity is still there so we can this element can be the mid so that is how we will apply the binary search if you got the idea you can pause the video and try to implement code so let us quickly implement the binary search code so for that let just discard this code and define the variable i am so defining sort and l is for start from 0 r is start from start length minus one and then we will apply a binary search so this is a very famous template like binary search second template if you are not much aware of binary search how it is work and the how what are the types of template you can check out my binary search video i will post the video link on it so let's find out the mid first so it is always good to take care of the overflow part like that way and once it done we will compare the elements if nums of mid we will compare ah numbers of made with the num summit if nums of mid is greater than nums of mid plus one if it is the case then we need to look in discard the right half so in that case this will become r will become mid otherwise we will update our left so left will become mid plus one so that's it and in the end the left will be the storing the index of our answer we will return the left so l for that so let us try to quickly compile this first and second test case given in the problem and also let us put one or two more custom test cases where we have like one element and two or i guess this is not the valid test case maybe i am not sure but let us say two and one so let us try these all the test cases and if we get the correct answer then we are sure enough it will be pass it seems like we are getting the expected answer now we can submit the code and see how it is behave and it got accepted so this is the binary search solution as you can see this straight forward every time we are discarding half of the array element so hence the time complexity of this solution will be o of log of n and this space complexity as you can see we are just using the variables which is of one so try it out and there are many other binary search important problem and facebook is like binary search is very favorite topic so you must know different templates of binary search and different problems on that so just try it and let me know how do you like this and subscribe to the channel thanks for watching
Find Peak Element
find-peak-element
A peak element is an element that is strictly greater than its neighbors. Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**. You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in `O(log n)` time. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** 2 **Explanation:** 3 is a peak element and your function should return the index number 2. **Example 2:** **Input:** nums = \[1,2,1,3,5,6,4\] **Output:** 5 **Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. **Constraints:** * `1 <= nums.length <= 1000` * `-231 <= nums[i] <= 231 - 1` * `nums[i] != nums[i + 1]` for all valid `i`.
null
Array,Binary Search
Medium
882,2047,2273,2316
328
hey guys today this will L code 328 Old EV link list given the head of a single link list group all the noes with old indices together followed by the noes with even indices and return the reordered list the first no is considered OD and the second no is even and so on note that the relative order inside both the even and or groups should remain as it was in the input you should you must solve the problem in all1 extra space complexity and of end time complexity so how do we solve this problem let's go to the first example as you can see in the first example we will have this link list right so as you can see this Noe and this node and this Noe are at AES right they let's say label them right it's going to be three and it's going to be four here and it's going to be five here right so as you can see this node this and nodes are at all indices and there should be before all the noes with even indices right so how to solve this problem how do we come up with a solution for to group them right so we will we are going to use two pointers let's say we're going to have an old pointer and we're going to have an even pointer let's say we have an even pointer and our even head starts from this position and our old head starts from the head of the link list right so once we know this what we're going to do is the next of this OD is OD node is going to be the next of this even mode right so we'll uh point to this and the next of this even is now old pointer is going to be here and the next of this even is going to be the next of this o right the next of the OD right the next of this even is going to be the next of this o so we will point this to this one and now e is going to be here and the next of this o is going to be the next of this even right so we will move uh this to this position now as you can see um now always going to be here right so the next of this OD is going to be the next of I mean the next of this even is going to be the next of this OD right so now this Four Points to n right so as you can see the even link list is going to be two and it's going to point four and four is going to point to none right and the old link list is going to be um is going to be one is going to be the first and 1 point to three is going to be the next one and the last node is going to be five right Five Points to n so as you can see the last pointer always going to be at this position and is going to be at this position right and the head even head is going to be here for example the even head is going to be here right even head let's say our even head is going to be this one and our is going to be all head is going to be this one so head right we have two heads right now what we're going to do once we are here our old this pointer is this the tail since we can just say the tail right the tail is have to point the even head right so we can say just this uh Old Dot next is going to be um or do next going to be the head the even head right this we can just say the even head uh we can just say even head right then um then once we just do this we can just return the OD head is going to be just the head of the link list the given head of Link list we can return the head right so we are going to solve this problem this way so the time complex is going to be open the space is going to be all FES we're going to use just pointers right even in Old pointers so first we have to check whether the link list is going to be whether it is none or not um yeah if the link list is going to be none what we're going to do is but we don't need to I think for let's start with our two pointers let's say we're going to have old let's see we're going to have o the O is pointing the head of the link list and the even is going to point to Z head next right yeah then let's say we have an even head let's say we can have an even head is just ini the head next right then what we're going to do is while the even end while even and even do next while this is true weate while this is true right since we are moving two steps each time then we have to check like um this is true then once we have done this the OD is going to be the OD is just um the OD next is going to be uh the even do next right even Dot next right and our o is going to be now move to O next and the even do next is going to be the next of the even position is going to be uh o do next right and our o is going to now our even is going to be even do next and once we have done this we know like um the old do next the last the tail of the Old Link list it's next is going to be the even head right the even head once we have done this we can just return we know the even head the tail of the even head is none right so we can return just the head because the head of the Old Link list points to the head right so the head of the link list we can just return the head instead of the Old Link list just so the time complex is going to be complexity is going to be the time complex going to be of N and spe complex is going to be since we didn't use any extra space like that is going to be scale so we have just open right so let's see if it works for the given test cases okay so as you can see pass for the two test okay what if we have given let's say what if we have no any head right as this point as you can see we don't have any head do next right what if we don't have any what if we have only um what the head is none so if the ha is none this my so an error right so we have to check like if not the head and or what if we have only one node right if we have only one node um if we have only one mode what is going to happen right if let's say we have only one mode let say we have this mode right so as this case the is going to be at this position and the even is going to point to none right then o do next is going to be the even head is just the none right so we can only check if the head is none right this case we have to return just the head right away right uh since this may thr an error right let's see uh let's have another let's add a test case for example is remove all of them okay let's see if works for yeah as you can see past if there is no node what if we have one let's say we have three here let's say we have one mode right okay see so we passed right so let's submit it so as you can see it this much of python user and this much of in space right so guys if you like this video please subscribe it's going to help me a lot and if you are um if you just uh one more want more videos um please um touch the notification button and if you can share this video for people who learn about DC so thank you very much
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
1,859
Al so this question is soled in the sentence so a sentence a list of words separated by a single space and no leading space and trailing space and every single word has the index so you just reward is based on the index so um you can use hashmap key is going to be integer and value is going to be the string so you will um B basically derse the whole entire map and you want to get um based on the index right and then we need to uh put it into the stream Builder we want to return the string so this will be the first solution so hashmap integer string map equal to new hashmap all right and then we need to know like um how many items like how many word inside the sentence so it's going to be S split right and then um so once we derse then we need to create a stream Builder so stream Builder s SP to new stream Builder all right return. two stram right okay so basically we can Traverse the um uh string uh once it's split right so for string in strings right then I can basically know index and the index going to be what integer. parse in the last value is going to be string do chart at string length minus one right but you have to convert to the in so minus Z okay so we get the index then we need to get the whole entire uh remaining right so um I can just use substring so I'm going to put a map I'm going to put the index into the map and get a subring so string. subring so this is from zero all the way to the this guy right I mean the index represent what the integer but we not actually allocate the uh the position right so it's going to be uh sh L minus one so shr l so imagine this one this is three right three- one is two so from 0 to three- one is two so from 0 to three- one is two so from 0 to two the index all right let's look at another one this is from this is L of five right so 5 - 1 equal to four five right so 5 - 1 equal to four five right so 5 - 1 equal to four right so from zero to four but not including four so it's going to be exclude the last Index right 0 one two 3 then you get a list all right and then basically we end it all right so um we have every single word corresponding with the index inside the map then we want to derse then how do we know the length so length is going to be this guy right so how many space we have zero oh sorry one 2 three so the length of the string is what four right one two three four so we can Traverse based on this so for in i z i less than string i++ string i++ string i++ and we're starting at the index zero right so when we say uh s spe p and then we say map. get I + one this is how then we say map. get I + one this is how then we say map. get I + one this is how we get the number one right number one and then we need a space but not the trading space right so we need to make sure if I + one right so we need to make sure if I + one right so we need to make sure if I + one sorry uh yeah I + one uh does not equal sorry uh yeah I + one uh does not equal sorry uh yeah I + one uh does not equal to string L then we will append the space you can use the other way I does not equal to string. length minus one so there are the same idea I believe this is going to be what oh CH cannot convert the string I think this is a little bit table um oh hold on so I don't need to convert the integer that personing I'm I can get this one right away oh yeah that was a typle all right so for time in space this is a time this is the time and pretty much this is going to be what how many item in is right so the L the time is going to be all of them the space is going to be all of them right all of them and then how many item in the map all of them right so they the worst case are all of them all right so another solution is going to be using the array instead of hashmap so you still going to use the stream array I'm still going to have a stream Builder and then based on the result I'm going to put the current corresponding index inside the result Ray so should be new string and then the size is going to be based on what the str. length you'll definitely see what happens so the size is going to be four for this one right and then you need full space I mean full index right later on we say speed. two string okay so I still have to Traverse the whole entire strings right and then my index equal to what string add right and this is going to be L minus oneus Z right so I get the index but this index starting uh from one right I need to say result IND this minus one is equal to what the string subring from zero to the end right the minus one pretty much it right so it's going to be similar to hashmap then we need to Traverse from I equal z i less L i++ then we can basically uh obtain whatever we have inside the result right so result the I so I represent what I represent index inside a result we didn't put extra space for there right we starting at index zero so imagine index is what one we say 1 minus one and then this is the word for the string so we say result uh result I only and then we need to add a space so if the I does not equal to string Leng minus one then you will say sb. pen space okay so Prett much all right the time and space are the same this is all of time this is space all of space so if question common I'll see you later bye
Sorting the Sentence
change-minimum-characters-to-satisfy-one-of-three-conditions
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence. * For example, the sentence `"This is a sentence "` can be shuffled as `"sentence4 a3 is2 This1 "` or `"is2 sentence4 This1 a3 "`. Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_. **Example 1:** **Input:** s = "is2 sentence4 This1 a3 " **Output:** "This is a sentence " **Explanation:** Sort the words in s to their original positions "This1 is2 a3 sentence4 ", then remove the numbers. **Example 2:** **Input:** s = "Myself2 Me1 I4 and3 " **Output:** "Me Myself and I " **Explanation:** Sort the words in s to their original positions "Me1 Myself2 and3 I4 ", then remove the numbers. **Constraints:** * `2 <= s.length <= 200` * `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`. * The number of words in `s` is between `1` and `9`. * The words in `s` are separated by a single space. * `s` contains no leading or trailing spaces. 1\. All characters in a are strictly less than those in b (i.e., a\[i\] < b\[i\] for all i). 2. All characters in b are strictly less than those in a (i.e., a\[i\] > b\[i\] for all i). 3. All characters in a and b are the same (i.e., a\[i\] = b\[i\] for all i).
Iterate on each letter in the alphabet, and check the smallest number of operations needed to make it one of the following: the largest letter in a and smaller than the smallest one in b, vice versa, or let a and b consist only of this letter. For the first 2 conditions, take care that you can only change characters to lowercase letters, so you can't make 'z' the smallest letter in one of the strings or 'a' the largest letter in one of them.
Hash Table,String,Counting,Prefix Sum
Medium
null
446
hello guys and welcome back to lead Logics this is the arithmetic slices 2 subsequence problem from lead code this is a lead code hard and the number for this is 446 so in the given problem we are having an integer AR nums and we have to return all the arithmetic subsequences of nums so what is an arithmetic subsequence so arithmetic subsequence is a you can say sequence that will consist of at least three elements so minimum we want three elements and the difference between any two consecutive elements is the same like if you pick any two consecutive elements of a sequence it should always give you the same difference so let's see here we have three examples of arithmetic sequence and an example of nonarithmetic sequence so let's start with arithmetic sequence the first sequence is 1 3 5 7 9 so the differ difference between 1 and 3 is 2 5 and 3 is also 2 7 and 5 is also two and 9 and 7 is also two so the difference is same if you pick any two consecutive elements and similarly for this sequence 7777 the difference is zero and for this sequence the difference is min -4 so since the difference is same and -4 so since the difference is same and -4 so since the difference is same and it is also greater than three elements so it is an arithmetic sequence but this example you see the difference between the first and the second element is zero then between this two is one and between these two is three so this is not an arithmetic sequence so what we have to do that we have to find out the number of subsequences of an array uh which are possible arithmetic subsequences so let's see through an example suppose we have this example 2 4 6 8 and 10 so there are seven possible arithmetic SE subsequences how you see 2 4 6 yes a possible answer 4 68 yes all are two then 6 8 10 yes then we have 2 4 6 8 yes then 4 6 8 10 yes then we have this entire array as the same and also 2 6 and 10 also yes so now let's see how we are going to solve this but so we are going to use a DP along with a hashmap and the hashmap will store the difference between the pairs and its entry along with it and we are going to create a DP to store the previous results so first of all initialization of the DP and the hash we are going to do and then we are going to iterate over all the pairs so we'll be to using two Loops I and J to perform to form all the pairs of the indices I and J where I is less than J and then we are going to Simply calculate the difference calculate the potential common difference and uh that difference what we have calculated we'll check in the hashmap if it exist in the hash map we'll do the updation of the count in that case and if it does not exist then we'll uh put it into the hashmap and once the hash map is completely filled then we can accumulate the count from the DP table which we have and then we can simply result the return the result so let's now come to the coding section but before that do like the video share it with your friends and subscribe to the channel if you new to the channel so first step will be let's define the L then the second step will be the DP table initialization so this size will be of n cross n and then we have a hashmap so hashmap we can take of int I think we can take it of long so we have the hashmap defined as well so this list array list of integers will actually contain the elements which have the same differences and this long will be actually difference so let's start by now the first step is to hydrate over the and populate the hashmap so long temp equal to num of Y and if map does not contain the key and if the map does not contain the key temp that is the num ofi then we have to put it into the map so here we are populating the map because we want that the array list for every integer is initialized before going into the main logic and then map. get temp do add all so the first element we can add here is this now it's time for the now we are going to iterate our all the possible pairs so all the possible pairs will be formed by I equal to 1 I goes less than n i ++ then we are going goes less than n i ++ then we are going goes less than n i ++ then we are going to iterate over the G gal to J will come from I + 1 because G gal to J will come from I + 1 because G gal to J will come from I + 1 because since we are forming a pairs we do not need to repat the elements J should be also less than equal to n and J ++ ++ ++ and long equal to 2 L nums of IUS nums of G now if the map contains the difference so we are here calculating the difference and if the map contains the difference then we need to do some updation otherwise we can simply leave it here so if it is inside so int K will be the elements in the map and for every element we'll be checking if K is less than I then we'll be updating the DP table and adding the DP of Ki + 1 because in this adding the DP of Ki + 1 because in this adding the DP of Ki + 1 because in this case we are going to add the current element into the hash map so accordingly we have to do the updation hash table also that is the we need to add the number of subsequence as well so that's why we are doing this operation and if it is less than I if it is greater than I then we can simply break because this is invalid case now here we need to add into the sum the DP of I and the g because we need to accumulate the results so that why we are accumulating it into the sum and then after this we can simply return the sum now let's see if it's Run f there has been some error so okay it run fine for the sample test case let's run for the hidden test cases as well so okay it passes with a good time complexity and a good memory complexity you can see so the time complexity for this solution is O of n² because that comes from here we are iterating over all the uh pair of indices and the space complexity uh is used for the DP table that is for and that is also of n² and you can also check my uh C++ Python and JavaScript Solution by C++ Python and JavaScript Solution by C++ Python and JavaScript Solution by going into the solutions panel and checking this solution and you can find here the intuition approach the complexity the Java code C++ python JavaScript and yes Java code C++ python JavaScript and yes Java code C++ python JavaScript and yes do remember me to apport so I hope you understood the logic do like the video share it with your friends and subscribe to the channel if you're new to the channel thank you for watching the video have a nice day
Arithmetic Slices II - Subsequence
arithmetic-slices-ii-subsequence
Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`. A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same. * For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and `[3, -1, -5, -9]` are arithmetic sequences. * For example, `[1, 1, 2, 5, 7]` is not an arithmetic sequence. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. The test cases are generated so that the answer fits in **32-bit** integer. **Example 1:** **Input:** nums = \[2,4,6,8,10\] **Output:** 7 **Explanation:** All arithmetic subsequence slices are: \[2,4,6\] \[4,6,8\] \[6,8,10\] \[2,4,6,8\] \[4,6,8,10\] \[2,4,6,8,10\] \[2,6,10\] **Example 2:** **Input:** nums = \[7,7,7,7,7\] **Output:** 16 **Explanation:** Any subsequence of this array is arithmetic. **Constraints:** * `1 <= nums.length <= 1000` * `-231 <= nums[i] <= 231 - 1`
null
Array,Dynamic Programming
Hard
413
1,291
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have not liked the video please like it subscribe to my channel so that you get notified whenever i post a new video so without any further ado let's get started problem is sequential digits very easy problem an integer has sequential digits if and only if each digit in the number is one more than the previous digit so sequential digit means like if this is a sequential digit means the this number is one more than the previous number similarly three is one more than the previous number which is two so this is a sequential digit so cancel number so return a sorted list of all the integers in the range low to high that have sequential digits so we have to return all the numbers all the integers which have sequential digits between this range so from 100 to 300 there are two numbers which are which have sequential digits one two three four similarly if you see this one over here thousand and thirteen thousand so in this uh between the thousand and thirteen thousand you can see there are one two three four five six seven there are seven sequence integers which have sequential digits see one two is greater than 1 then 3 is 1 greater than the previous digit which is 2 like this so let's analyze from this how we can approach the problem let's analyze this analysis from this test case so see we need to make the numbers we need to make those numbers which are between thousand and thirteen thousand right and they should have sequential digits so if you see these numbers can start from one also it can start from two also three also four all four five six right so they can start from any digit so let's see how we can make uh how can when approach the problem so this is input given this is low and this is high so we will what we can do is we can generate all the numbers which we can make write all the sequential numbers which we can make and then we will see if those numbers are between this range if that number is between the range we will add it to our final list this is the final list so how to generate all the numbers which i have sequential digits see first of all so we decided that over here if you see from the output the numbers can start from 1 to 3 and it can go up to it can start from 9 also right like that right so uh let's see 1 two three four five six seven eight nine like right these all are the digits from which we can start a number so if we start from one starting digit is one now we have to make all the sequential digits we have to make all the integers which have sequential digits so after one if we start our number start our integer from one after one what should come two should come because we need to make sequential so what we have to do is this is our current number let's say this is the current number so in order to make the next number what we do and i over here let's say i over here is 1 because we are starting from 1 now if you want to make next number what we do number into 10 plus this uh next i let's say next i is 2 because after 1 2 should come so number plus i so what does this become num is 1 into 10 plus i is 2 so this makes 12 so see 1 2 is there now after 2 what should come i should become 3 and this is a number so what we will do again 12 into number into 10 number is 12 into 10 plus i 3 so this becomes 123 hence see these are sequential digits we are making this integer nav and it has sequential digits but still this 123 is not between this range thousand thirteen thousand so we'll go ahead so then what we will make it will be 123 into 10 i is four now plus 4 so this will be 1 2 3 0 plus 4 that is 1 2 3 4 now if you see 1 2 3 4 is between this range one two three four is greater than low or equal to and it is less than high so this lies in between this range this lies between the range hence we will we have our output list and in that we will add one two three four we will add right and then we uh we can again traverse further so what we do is uh now i will become 5 i becomes 5 and 1 2 3 4 into 10 plus i so these are different recursive calls right in each recursive call we increment our i and number gets updated so 124 into 10 1 2 3 4 into 10 plus 5 so this becomes 1 2 3 4 5 and this also lies between the range see 1 2 3 4 5 lies in the range so one two three five also we will add in our output list one two three four and five right then uh we'll go further i will become six so what we will do is number is one two three four five into ten plus i is six so this becomes one two three four five six so twelve thousand uh sorry this is something this is one lakh something so this becomes out of the uh this becomes greater than high so this we cannot take in our output so if you see one tooth it's still one two three four five only one two three four five six this number becomes greater than high right so we will not take it and from here we will return we will just return because now no further number we can make that will be greater than high only so that will not obviously come in the range so we'll return we return and this is v this is how we return now let's uh again we return here and we come here to again we start from 2 again now we start from 2 we return here now we start from 2 so for 2 what we can do next obviously see it's not that after you know we can have different choices like 2 is there then we can have 4 we have to make sequential only so after 2 only there is one option of getting if this is i over here is 2 is there so i 3 in the next call so 2 into 10 plus 3 so this is 23 so 23 does not lie in the range so we will go and make next recursive call i will become 4 so 23 into uh this will be 10 plus i is 4 so this will become 2 3 4 also not lies in the range will again do so i will become 5 here right and 2 3 4 into 10 plus i will be 5 so 2 3 4 5 now 2 3 4 5 lies in this range so we will add that in our list two three four five this will be added in the list and then again we will continue further so these are different recursive calls we are making right so uh 2 then i will become 6 2 3 4 5 into 10 plus 6 so this 2 3 4 5 6 that is 23 000 now this becomes greater than high was 13 000 so this is not in the output only 2 3 4 5 is in the output right so similarly you can make all the numbers you can make all the other numbers using like three then three will then after three four bill will become so i'll not make the entire three but similarly you can make all starting from four then starting from five starting from see starting from three will be three four uh three four and then three four five six so three four five six will be a number starting with three four five six then starting with four it will be four five then four five six seven this will be number starting with four five six seven then five six seven eight nine and we cannot make from seven eight will not is not in the range then seven eight nine is also not in the range but seven eight nine there is no other digit that we can use ten we cannot use right so here it will end similarly for eight also so i hope you understood what approach we are using we are every time making a recursive call so first of all we are having a loop which will start from 1 and go till 9 and these will be our starting digits we are making a recursive call and recursive call we pass this i and the number which is the new number into 10 plus the current i this is the number which goes in the next recursive call so if that if this number is in the range of like if it is greater than low and less than high if it's greater than low and less than high then we can add it to in our final list we add it in our final list so let's see the code for this i hope you understood the approach so seek very simple code what we are doing is we need to see our starting digit could be any no any digit now from 1 to 9 it could be any digit starting 3 4 5 any digit could be the starting digit so we are having a loop in which we are starting from i to 1 and till goes till 9 so we are having this dfs in which we are passing this low high and the current i and number initially we are taking zero we starting from zero so this is dfs call if the number is in the range if lies in the range then with answer then we push it in our answer list final answer list otherwise if the number becomes greater than high or our i becomes greater than 9 so i cannot be uh that now greater than 9 i cannot be 10 so if i becomes 10 is simply later and otherwise make the dfs call 2 i plus 1 and number into 10 plus i next call right for example over here what we were doing every time the next call was the next call it was like i was i gets incremented and next call was on this number that is 123. so this is uh pretty much it and after this for loop is completed in the answer list we'll have all the numbers all the integers which lie in this range and are sequential so we'll sort them because they are asking for a sorted list so we'll just sort them sort the answer list and we'll return it so the time complexity for this since we are doing sorting so it will be o of n log n and space complexity will be of n because we are taking that answer list and over here there is one more approach which we can have for this we just need to find all the sequential all the integers that are sequential so what we are what we can do is we can generate all the sequential digits all those integers that have sequential digits that is c this integer has sequential delays four five six seven eight all the these will be some 36 35 36 so you can all generate uh you can write all of these in an area right these are integers which have sequential digits then just simply you can run loop and just check if uh these in which if any integer is in the range if it's in the range then push it so this is one approach uh this you can use and otherwise the approach which we you know which we can use also is this recursion i hope you understood the approach and the problem let me know in the comments if you have any doubt and if you like the video and it was helpful please like it subscribe to my channel and i'll see the next video
Sequential Digits
immediate-food-delivery-i
An integer has _sequential digits_ if and only if each digit in the number is one more than the previous digit. Return a **sorted** list of all the integers in the range `[low, high]` inclusive that have sequential digits. **Example 1:** **Input:** low = 100, high = 300 **Output:** \[123,234\] **Example 2:** **Input:** low = 1000, high = 13000 **Output:** \[1234,2345,3456,4567,5678,6789,12345\] **Constraints:** * `10 <= low <= high <= 10^9`
null
Database
Easy
null
1,602
hey what's up everyone today the question what i'm going to say is uh 1602 the finalists well known in the binary tree said that they're giving us a root a binary tree and another u in the tree and uh from the description down be here and you'll see like units known in the binary root at the root so that there are no possibility that the roon and u are non-pointers are like no roon and u are non-pointers are like no roon and u are non-pointers are like no we definitely can't find the answer even is uh it can be like the next note or it can be like maybe not but those two elements cannot be known uh return the nearest node on the same level that is to the right of u or the return now if we use right most node in this level so it definitely we can find u in root as long as it's just like the result can be known uh so give you the example of the this is the fourth so the negative the right the next right now there is a five if you want to find the next round node of six which will be none pointer this is basically a really classic question of a bfs the level search where you just get a uh the whole level of that and you search for it if there's a target value that's matched with the u value that you're gonna to find the next one if we do not have the next one it's gonna turn out otherwise return the value that is the next tweet so that we can the data structure we're going to use is uh the dq uh why is that because by using the dq we can actually to uh access the uh the front and back front the back of the element when we are doing the uh finish that when we are doing the uh level search uh we need to make sure that we can access to the end of the array so that we can append the next value because whenever we are traversing like the 203 we definitely want to edit the four five and six in the next level so that we need to make sure that we can we have access to the back of the uh queue but we also need to have access to the front element so that we do the last level uh last level terrestre so that we can get access to the two and the three so um this is reason why i use a uh dq this is convenient so that we can get access to both the back end and the front and the uh elements so uh let's straighten the code so we're gonna see uh dq we should just call that a d uh yeah and the free initialization we're just gonna push back you can just put front because there's no element in it right so just gonna do push back or perform either one will work right and we know that the dq is not empty we can to perform some more operations which is to do the leverage result first right and uh it's just a template that you can remember that remember the current size because whenever we're like uh adding the y into the queue so that we have only one element we only need two terms of that one time right obviously we have the two elements here the two and three we only like to go the four loops for like twice so that we uh can add it also the next level uh notes into the queue at this for loop and we're just gonna see uh if we uh just gonna get a return node which will be the doll front or back it will be front right because we are currently examining the uh front elements to make sure that uh if they are the target value we are trying to find and uh the values for the next level we're going to add in that we will be appended into the end of the queue so this is quite different and uh you can just use a frontal and whatever you want just make sure that you know and you say like the current value equal to your dot value what are going to do is to make sure that uh we're going to find if see this is the last value we're going to find so we just turn it down directly it's really like that when we are trying to find the rightmost node over 6 we're just going to return the next one which is now right and otherwise we can just return that uh return d dot front right this is the node that we are trying to looking for because whenever let me just write the example whenever when we are trying to find the four five six and then we will find the let's say is five right and we actually for each time we need to pop copy because this is a note that we have examined before so we need to pop that otherwise there's gonna be duplicates right so that the four has been uh removed from this picture and now we are examining the five node and i will just find out that the five has already uh is the target value we are looking for so the sixth the next node is what we're going to do so this has been popped right and this is a note that we are looking for and uh possibly there are some nodes in the next level that i had that have been added into the queue so that uh maybe like there are some random values and here so that we don't get the off back we only get the data from right so this is there and after doing that we're just gonna to add the next level you see this is not the norm we're just gonna push what push back or push back right left and if the current all right it's not equal to uh one pointer we're just gonna the down push back turn the right after we're doing all of that is to add the this is the uh at the end of the loop we finish traversaling the uh one level every time we go through this for loop we will finish like troublesome in one level and let me see what else are gonna miss uh yeah if say finally we cannot find the element i'm just going to return it now right because there's no way we're gonna but uh actually the code will not reach here that's uh there's a sentence that says another code uh is that user node in the binary tree would uh root it as root so that uh there's definitely going to be a uh we can definitely find the answer it's just a matter of whether or not it's not so uh this is yeah let me check him out yeah this is uh let me gonna try the second case and if it sinks out smoothly we can go and submit all right so cool this is it and as for the time complexity it will be open because uh in the worst case we need to examine every node in the binary tree for like if you just give me the node that in six and we're gonna definitely gonna say to examine every node in that and for the space complexity it will be o uh let me see it will be oh um we are gonna level so we're gonna be open because it will be proportionally to let's see we have uh two to the power of n nodes so that we need to in the last level we need to store this kind of a node so that you are proportionate to a number of nodes and uh let me see uh why the time complexion is always because the uh yeah this is not a special tree treat just binary so there's no like attributes that we can take advantage of that so yeah that's basically it uh find the nearest red note the binary hope you understand that feel free to comment me if you uh have something that confuses you or like etc sort of things
Find Nearest Right Node in Binary Tree
find-nearest-right-node-in-binary-tree
Given the `root` of a binary tree and a node `u` in the tree, return _the **nearest** node on the **same level** that is to the **right** of_ `u`_, or return_ `null` _if_ `u` _is the rightmost node in its level_. **Example 1:** **Input:** root = \[1,2,3,null,4,5,6\], u = 4 **Output:** 5 **Explanation:** The nearest node on the same level to the right of node 4 is node 5. **Example 2:** **Input:** root = \[3,null,4,2\], u = 2 **Output:** null **Explanation:** There are no nodes to the right of 2. **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `1 <= Node.val <= 105` * All values in the tree are **distinct**. * `u` is a node in the binary tree rooted at `root`.
null
null
Medium
null
668
Hello friends, in today's video, these problems are discussed in 61 dedicated smallest number maze problem. Before starting, I would like to tell you that this problem is a very good problem and you will find this problem or observe this problem in many places. If you do then you keep watching the video canting all, you will get to learn very well and after this, if you ever have this problem then problems related to it will come then you will be able to do it with certainty that you have solved the problem, do you have a multiplication table and What is the value of Net ID in that? Come, your dutyable is equal to Bauji, it is of impression size and the value of Airtel's lover stabilizer of every year is exactly equal to 2G and the components of lineage business name end are in the printer that thm all s. Eliminated and Roshan Multiplication Tables Okay, so you have to return the element in front of you, then if after simple, you have to think of its exact solution, if you ever feel like drinking it, then you have to study the roots first for half an hour. You will get the biggest gift solution, if you have to then what will you do with whatever woman in your house, what should you do with them, do something on them, set them, return the advocate element, okay then you will know easily, so first. Hotspot but then you would like your macro we took the tube of okay then is good only able to send me a text message send a n tell us which ones in the table grinded it and did something to me later removed my table 200 Let's test and what is your smart statement what will happen in the episode table answer tiffin mention that I as click soter smallest element is big insomnia tweet answer its timely message giver is maintenance a profitable created and are you dry Done mintu hai log in this exciting and rotting hormone recipe will be the specific gravity is the maximum of white tell something find the third 210 superintending engineer has interested power so if you turn off the setting then never Congress is getting nine to decorate means your So near solution also time is not working means if you shopping will not forward yet and your memory beam phone number 9483 in beta testing version support time induced in the limit exceeded is going to repeat if you are ok then it means Adani clear solution to run our work with this I am not swimming across because remember you, that white lily is a blessing on your home, then I told you first of all, what is the problem with you, if you ever had such a big constant that he could not fast for you, right? So tell you only one thing in your mind that who knows, make this rule that when brother is not able to tell you the solution, then in the real office there, in most 90% of the cases, real office there, in most 90% of the cases, real office there, in most 90% of the cases, binary search is done, only then something happens, that is the problem of match, otherwise 1995. In the sentence, you may have balance problem, then I tell you to turn your mind towards binary search tree, we will do binary search, you will have to start seeing your problem, okay, so I explained, let us know brother, it depends on the clear key, then some lock. Lock MH1 function and will do chilli - 1 green MH1 function and will do chilli - 1 green MH1 function and will do chilli - 1 green something and will do OK, so in the absence of writing, how will we solve this problem that if you see that it was 125 and you have felt the table is the same 12324 figure table spoon or not, have you started this? From the rally of one to three layer and see the records Choli 123, it is developing in the same way and you started paying us clear, refill which is your tips is the smallest element, it is okay, but if you mean, what do you have to do, you also have a meaning, what should I do with one. Not by taking but by cross, hold all the rallies and what else check Ramesh's check that connect with him how much of his small balance is making your payment means like every now if you don't know the answer noise then example what you have to do you any one of the elements Take this question, if it is the accepted answer then it is ok then when will the answer of one year be made Which can be laser request accept to accept answer see the cover answer is that giver that your face 1234 500ml is such that less daily 1234 so that you will get any of your various types of where will it be made only when your table has at least The elements should be such that they are less dedicated, only then there will be a week for the answer. Tell me, you need to know. Okay, now look, if you don't even know the answer, if you start, then there will be a lot of trouble, you will have to clean it. You know one thing. Mukesh If it changes, then you and it changes, then you can put your answer in the range of 1721, so what do you do, if you want to meet anyone, please check in the middle school circle that I can make it smaller, how many valleys, seas, with this, it is connected to the cable. From the least value which is smaller than this, if you are from criminal PM, then from the middle element in you, your Ambedkar's answer can be made. Otherwise, if chilli means what kind of playlist, which if it is now how time blast, then either you get this. If the work doesn't work then you have to take a bigger increase than this, you will be able to notice that otherwise, if you have a personality smaller than Mirch, you can become an MP, but for Mirch Chhodi, how will you know this because see how you are given her one two three four five six. Seven at tyu but now good pooja like where is your cheek initially yours add on one where is your r 98 then you will milk closing is the middle pass of important now a little blurry from your place how will you know that this So you will have to find out, not only if you make it small, if you are just for the sake of meaning, then only brother, where will you be able to get from, okay, then what are we worried about, brother, how to make it bigger, you left the party, how innocent you are, then if you are someone Also grab the cell like you just made a watch and how are the values ​​kept in it a which how are the values ​​kept in it a which how are the values ​​kept in it a which understand this 123 a quarter okay so if this is the second cell then cut it tour oy look see how this belt here You see here how the balance is for Rear Scientific Two 123, it is kept for this type, okay, that means, if you have any table, for example, it should be on I through in detail, okay thing and how many end columns are there in your table? If there are two three end columns, then what kind of belt will I take in it, I will do it, I * kind of belt will I take in it, I will do it, I * kind of belt will I take in it, I will do it, I * Vansh is fine and how did I look into it, before people, I will sew them like this in your I throw, I will talk about it, I am two three and here What will be the feeling of I into A? Okay, now look at the solution, you have one of your elements from one, you should check how much has changed in this row, which is a small, okay, so if you assume that this support is one of the elements here. You this is there any admit in the back column I*P this is you is a small any admit in the back column I*P this is you is a small any admit in the back column I*P this is you is a small okay and after this send the plus one column element is I*plus one is this is I*plus one is this is I*plus one is this is your a big okay or is a big that is what we assumed that That which is the value of I in two pieces but the request is not accepted that if from here you if you want to see how you will write this I * request from VS on the website we I * request from VS on the website we I * request from VS on the website we are in demand if you * yellow soldier by the way then come are in demand if you * yellow soldier by the way then come are in demand if you * yellow soldier by the way then come sit point This tilak, all these laces will come out and Iodine plus one is a big one, we also know it, okay, so you can see it is into electrical 2X, so now how much would you have got in a small one tablespoon of ghee 123 456 meaning hotel, this is one of the victims who will come. Small spoon is ok, so you can see here, can I drink, what will come out of the yellow, if one turn comes, then how much chilli total Click then what we believed that from tell into pieces is a small one so I this is behind you jaggery how much verification is this in the room 1234 dresses pelvis which is a small one then will be appealed a spiral so you know that you You can check, like if you have to click five, then you can also check that I have left the mark here, but you will have to keep one more thing in mind because one thing is that this is the truth that I have selected, what will it be, that is, absolutely minimum of access oil. Or these will be okay, access oil or end tricks, you will have a column madam and elements, no, the one who will be drinking will be the people in the middle of the city, this will be the only thing that you will find in this team that will decide, how many people will be associated with five in number one. If you see, which if your key value has been calculated, 651 is okay that come here only what is your which is I throw okay so fiber 125 register profile with Sony only smaller than five but spread here right meaning emergent a What's the get and minimum VC's that are smaller than five okay this is what got where if you are doing it for business then you will get three elements in the first row which are less than five in seconds so here's this So and spa yes brother, I have reached here, what will happen, so friend is total or you are behind the glass, which you can check the notification of, it is not smaller than 245, it is only big, okay so you mixed two and If you add it to the stones then how many elements will be there which will be small again 5353 but then you can do it comfortably brother the kidneys are bigger than the f-35 but you have a kidneys are bigger than the f-35 but you have a kidneys are bigger than the f-35 but you have a total of 6 elements which are hanging smaller that when Whatever you mean, whatever your table is, there are six limits on it which are such that what is the party small 123 look for entry taken then starting again is the element then meaning brother where can you be from, what will be the file tears dizziness When you like these from the media and when you are on the file, then brother, where are you? It is possible that there is six elements connected to Wi-Fi, six elements connected to Wi-Fi, six elements connected to Wi-Fi, so what have you missed? Whatever you answer, store all your fives in it for one time. Now I need your help. It was time for you to get justice. This was the statement of everyone, which was the limit channel for you at this point. You can also make it possible that again there may be some small element which is Ajamat 357, there is some element which is smaller than one small five, you are paying for it according to the smallest one, okay, so what to do for that. We will subtract the middle of our r and compare and fry the minute, then you will come here and but here our will come, okay your that you have subtracted your car, okay so you we have been filled with love that now we will give back now Like I got the lift answer or but right now it is 70 like ghee is an element smaller than five but that guy is some other number five smaller than which element is smaller than someone in your table, for payment to us we will have to use this for our surgery. Leave the night cream completely because you because of yourself, they are young and dark and hard, your photo is so what else is there? In this way, it is possible that you will have to check the answer. Okay, so you have already done media here. Dual is chatting from here, so don't cry first. Leave him. What time will you sleep? What did I say? Apart from the bulk pack, albums and You will be extra if you do Atul 2821, then what comes to you, I am the first one, leaving you, oil and shampoo, we have kept it here, it is okay for you, we have kept two, and second, leaving you will be the element, you are bittu, that is, you are the one. You can see that it is bent here that it is small brother only and what will happen only in big cities, send your 283 i.e. zero album that you can check it small, send your 283 i.e. zero album that you can check it small, send your 283 i.e. zero album that you can check it small, technical pizza has been declared big, so now here or here Vice chancellor in the limits of details which are second small then Mitthu's is your third element, then when will any album text answer be made with you while on that small activist 's Ali Mansoor, you are related to that the 's Ali Mansoor, you are related to that the 's Ali Mansoor, you are related to that the last 3 years are death or Ask an unbreakable text message, if you are not able to make it from where in the village, then I will have to chant to you will have to make me bigger, I am the second one, there is a short time limit, so no matter how much Delhi is there, it should be made smaller and the value of the element keeps on increasing. What should we do if we ask our alchemist Laxman, what will be the help to you, from here your game will be played, it is okay, apart from what was said, okay, the work here is only for communication, more spiritual awakening, still, if you update your plate, then you will If I get a replacement or it happens, I am fine sir, please comment that you are fine and I will be seen again, then see if I am free, then first of all I would like to leave the request that the minority of the third figure will be bye, no, you will get a little bit bye two remedies after a few seconds. How much is 150 small the sacrifice of big is fine and in the whole of his or table whey he last thought that the bike leaders are 111 elements or which are fixed and big this means total how many five elements are there which are small again and that You can withdraw cash from here 125 This is a total trick What property was required to become an officer I being the element of total which are features which are quite small, I had artificial mince which is a small dessert What will we do Hmm ok Brother of updating, now such things are the file, it must have come in your table earlier, it was yours and now what will we do with our album, what will we do Means Malleshwari, now what do you have to do with your medical, you have to take your car to the minimum. So what will we do to you and if you take it to my phone then what will become of your base, now it will become on you, if you break here, then you, your sister, government people will break to the leader of 128 teacher group, what will happen to you, now your Bar unsuccessful send one up that I agreed what to do in four districts when if where you were suggesting what we will do and have reduced it from low to medium so that why should we increase our surgery and share that I am some other small There is an element which you can make from here. If you cannot make any element from the clan, then you will enlarge your beans and increase the oil, so brother, the bigger the element, the more profit you will get from it, instead of leaving it and adding fat. This is what we read so you got the need so this is passed in and that's it here legs FreeCharge hectares of land will sink you delete all the groups and check brother's pick how many elements are there which are smaller than your stomach climate So all the rogues and edits, either we got it right and after that, yours, Sachin's intake, in the middle of the bank and this day is getting released every week, first give up so much of your rights, the eliminator is just this much, there is the filter. If you do then how much time will it take to finish the total eye lock m2m half a minute in the van now and again these things again and again reduce risk time positive yoga mintu return payment then our work is required by doing this because you also enjoy every fun. First of all, did you calculate all the points, how many elements of your friend are small, but here we are overtime, this will work here because we told you that how many people will be connected to one in this row, there will be 1 by elements which is Arthur Ashe. If we are sitting small then we will destroy our life very soon, so better understanding has been given to Pan, okay, first of all, what will we do by giving, do you know the series, do you know what is your age, tent and equal, one and all equal right data. Meanwhile Mukesh is doing the entry from here, okay what have you forgotten, half of the answer is right in the middle of Vellore like this, what will we do with it, first let us do it through our tears, then I have given its property to wild and equal two and back. His comments will be taken as medically useful and plus and minus llb-2. If medically useful and plus and minus llb-2. If medically useful and plus and minus llb-2. If you can send a message to this thing then you will give it a plus and Bittu is equal to this. Okay, why is the alien always writing so that if ever the integer overflows then it means we will Go subscribe, don't follow, okay, but later on you will check how much limit is there on chilli powder, so we have zeroed the Shree account because it is debit, then what will you do, wait all your evil points, I have brought them from equal to one. What will be the minimum of meaning of what will be made by a batsman jokes small we will be debit in it that will leave the soil or else and that Only then the most element that can be donated in a hair is that when you were from here, the fiber here is 125 that I have only three elements in this channel which can be smaller than the village, Capsicum, I am fine, let's meet in front, I took and You can do it, okay, now any rich person from where you are, there is a lot of Mughal army while how many elements are smaller than that, how this which is smaller than chilli, if the target is of daily Urdu, then you are here, you will take this medico and you A, we will reduce the questions. Okay, like see, when your advantage has become cancer, look here, if it is made from here, then you have reduced your fans. Khurram, where have you come for your school, so look at you and Imarti you. Had met with my flight that you can see that means it is absolutely free, this work is optimal answer Mukesh, small 5 elements, this is the one of this element when it is the smallest, otherwise if the account is less then what will we do in it for this type Blood, what will you have to do for this, you can increase your fans on Admit Plus, you can get two wickets on MS Word, again on this platform, Next Aamir's value is a big reason, so it is more necessary that brother, the businesses related to him should get it, okay and details in these boxes below. Answer, OK, so this is ours, this is our Vice Chancellor, he is the head, OK, this is the approach you have taken, its timing will be of weakness, that order is here, caliber limit is here, collar has to be fitted in the mixer, it is ok, middling the time. Or lock the red number and get the benefit normally in minutes. Okay, and if I talk about it was mixed by using the oven without any tax and that it is submitted here to enrich the knowledge that by doing Braj Bhasha, you can That patient must not be understanding the TV. If you have any problem then do tell in the comment section. If you liked the video, then like the video, subscribe the channel, share it with friends. Watch this friends now Liquid and Tech. care external links
Kth Smallest Number in Multiplication Table
kth-smallest-number-in-multiplication-table
Nearly everyone has used the [Multiplication Table](https://en.wikipedia.org/wiki/Multiplication_table). The multiplication table of size `m x n` is an integer matrix `mat` where `mat[i][j] == i * j` (**1-indexed**). Given three integers `m`, `n`, and `k`, return _the_ `kth` _smallest element in the_ `m x n` _multiplication table_. **Example 1:** **Input:** m = 3, n = 3, k = 5 **Output:** 3 **Explanation:** The 5th smallest number is 3. **Example 2:** **Input:** m = 2, n = 3, k = 6 **Output:** 6 **Explanation:** The 6th smallest number is 6. **Constraints:** * `1 <= m, n <= 3 * 104` * `1 <= k <= m * n`
null
Binary Search
Hard
378,719,802
326
foreign with the lonely Dash and today we're going over leap code question number 326 power of three which states given an integer n returned true if it is a power of 3 otherwise return false an integer N is a power of three if there exists an integer X such that n equals 3 to the X so what does this mean well it just means that we need to figure out whether N is a power of three that's not the most complicated thing in the world um and the way we're going to solve this um is well there's a couple of different ways we can solve this in fact though I think maybe for this video we will solve it in two different ways so how are we going to do this well let's take a look down here to an iterative approach um so first and foremost when we're thinking about what n is going to be because 3 is going to be 2A power um n is always going to be positive right so it's always going to be positive so let's say they give us the number 13 we need to figure out if 13 can be a power of 3 which we know it's not right because 3 to the first power is three to the second power is nine three to the third power is 27 so there's no integer that will come along where we will reach 13 right so if we take 13 we divide it by 3 we end up with 4.3 and because this is not a whole 4.3 and because this is not a whole 4.3 and because this is not a whole number then we also know it can't possibly n 13 cannot possibly be a power of three I think even the example they give us on the website it says what if n is 27 well we know 27 divided by 3 is 9 divided by 3 is 3 divided by 3 is 1 and because we got to 1 we know that um that 27 or N is a power of 3 it is in fact 3 to the third kind of looks interesting there so uh in order to solve this iterative approach this is all we're going to do we're going to divide n by 3 and if it comes out as a whole number then we're just going to keep dividing until it gets to 1. if it's one then we're going to return true if it's not a one then we're going to return false so that's the first approach that we're going to do it's pretty simple and straightforward the this is all of the iterative iterations we're going to need in order to solve it but there is an even easier way of doing it and we're going to talk about the mathematical approach now if we get a little bit more into computer systems we know that the largest 32-bit integer know that the largest 32-bit integer know that the largest 32-bit integer that we can process is oh look at this I must have left out some left out a number or something like that it's something I got to look up this number it's 2 million oh yeah it's 2 million 147 483 yes that's right is this big old number which um the closest number without going over that is a what do you call this thing a oh my gosh I can't even remember a power of three thank you the word power just flew out of my head is a power three is three to the 19th right because 3 to the 20th is larger than this number so we give us a bad answer but 3 to the 19th is below this number now all we have to do is take that big old number and determine that if we divide it by n that there is no remainder then it is a power of three so this is the most simple way of doing it but a lot of people don't think about uh 32-bit integers being think about uh 32-bit integers being think about uh 32-bit integers being this way to work so that's why we're going to do this in two ways we're going to do this iteratively first and then we're going to solve it in the mathematical way which is just taking the modulo of the largest value uh that is a power of three and determining if it's zero so let's take a look at any of the constraints and see if there's any other edge cases that we're going to have to consider for either of these approaches and look at that all the constraints say is that it's going to be an integer n that is within the 32-bit stream so uh that is within the 32-bit stream so uh that is within the 32-bit stream so uh nope there is absolutely nothing to consider for our edge cases we can just move on to writing I guess two sets of pseudocode okay so for our pseudocode we're going to do two different ways of solving this problem so the first one is the iterative uh solution of the approach and the second one is the mathematical approach so the first iterative one right so this is going step by step the first thing we need to know is that n always has to be greater than zero so that's we're just going to do this iteration while n is greater than zero what are we doing while n is greater than zero well if n divided by three is a whole number right so basically if we keep dividing over and over again and it's a whole number that means it's possible that it is a power of three so if n divided by 3 is a whole number what do we do um what are we doing we're saying n now equals n divided by three we're reassigning the value of n so I'm going to write that in then re-assign the to write that in then re-assign the to write that in then re-assign the value of n to n equals n divided by three done pretty simple uh otherwise if n divided by 3 is not a whole number what do we do well we're just going to break out of the loop because we know at that point that um that it's not and I guess you could say return false because we know it's not going to be a power of 3 but we're not going to do that in this case just because I want to build this slightly differently then once that Loop is broken we can ask ourselves if n is equal to 1 right and we're going back to where we were talking about once it gets down to one here then we know it's a power of three so if n is now equal to one then return true if n is not equal to 1 then return false and then we're done so that is the entire iterative uh way of solving this problem I don't think it's all that confusing but it's pretty simple the mathematical one is even more simple right the first thing we need to figure out is the same thing if n is less than zero we're going to return false because remember it has to be a positive integer the next one is if 3 to the 19th power divided by n is a whole number then we're going to say yep it is something that is 3 to that whole number will equal n then we can just return true on the converse if 3 to the 19th power divided by n is not a whole number what do we do while we return false so those are the two ways of solving this problem let's copy them let's paste them into our work area and let's get coding and here we are the JavaScript work area the lead code website and we're going to start with our iterative approach and the first line says that we need to figure out something while n is greater than zero so while n is greater than zero what are we doing well the first thing we need to do is determine that if n divided by 3 is a whole number we've got to do something else so that's an if statement if n modulo 3 equals 0 we're going to do something else so this n modulo 3 equals 0 is the way we're determining it that the N divided by 3 is a whole number because the whole number won't have any remainder and that's what the 0 is for and if that is truly the case then we can reassign the value of n it's right here reassign the value of n to n equals n divided by three and that's what that line is for now we need to know the opposite too so that's our else statement so what if n divided by 3 is not a whole number well then we're just going to break out of our uh loop that we have set up here all right so that's all of this code here gone all we have left is to make a determination if n is 1 by the time we're outside of this Loop and I'm actually going to make this a little bit smaller so we can see the code here so we need to determine if n is 1. how do we do that well once we're outside of the loop we can ask ourselves if n is equal to one I'm going to get rid of this little thing here then we know that the answer is that we're going to have to return true so we're just going to say return true else meaning that n is not one meaning that it is not a power of 3 else we are going to have to return false and that should be all of the code we need for our iterative answer to this question we're going to hit run see how we did and it is accepted we'll hit submit see we get against all of the test cases and I'm going to guess it's uh okay maybe not the most memory uh efficient but 82 percent 22 isn't bad now that's our first iterative way but we have a mathematical approach as well so I'd like to kind of go over that so I'm going to first kind of comment out actually can I comment out like this I'm not as there we go and I'll comment back like this awesome so let's just try our mathematical approach and there's a couple of different ways we can do this but the first one is let's just determine if n is and it looks like I might have made a mistake here n is less than equal to zero then we have to return false so that's if n is less than or equal to zero then we are going to return false if it's not uh then we don't have to return false but we do need to do our mathematics here right so if in this case uh 3 to the 19th power so that's math.pal 3 to the 19th power so that's math.pal 3 to the 19th power so that's math.pal 3 to the 19th power is a whole number so that we're going to use modulo again divided by n is a whole number equals zero then we know that is also a power of three so then we can just return true else uh we're gonna have to return false because if we have math dot pow 3 to the 19th module and it's anything else it is not a power of three so let's just see if I wrote that out properly and I did um but you know what I don't think I'm quite done with it yet I think we can even make this shorter for those of us who love really short answers to stuff um we can combine them and we can put it into one return statement we're going to return whether the opposite of this is true and this is true so how do we do that well we want to know uh we're going to return if n is oh why is that giving me such a crazy oh that's fine return n is greater than zero and right because that's the opposite of less than or equal to and we need to return whether math.pal 3 to the need to return whether math.pal 3 to the need to return whether math.pal 3 to the 19th power modulo n equals zero so as long as both of these things are true then it is true okay here we go let's give that a go and it does work it does seem to be pretty slow that whole math.pal 3 to the pretty slow that whole math.pal 3 to the pretty slow that whole math.pal 3 to the 19th calling on that collection does uh oh you know what it's not too bad 92 percent oh well even at 196 milliseconds I don't know I'm gonna hit submit and see how we do again just because I kind of don't believe these uh these answers there we go that's a little bit more of what I was expecting but uh those are the two ways that we can solve this question one using Straight mathematics uh which is just a short amount of code there's not a lot to it the other one is iteratively which has a whole lot more code but does run more efficiently all depends on what your approach is and how you like to code so that's it those are our two solutions to question number 326 power of three using JavaScript thank you
Power of Three
power-of-three
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`. **Example 1:** **Input:** n = 27 **Output:** true **Explanation:** 27 = 33 **Example 2:** **Input:** n = 0 **Output:** false **Explanation:** There is no x where 3x = 0. **Example 3:** **Input:** n = -1 **Output:** false **Explanation:** There is no x where 3x = (-1). **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Recursion
Easy
231,342,1889
133
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have not liked the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever i post a new video so without any further ado let's get started uh problem is clone graph in this we'll be given the reference of node in a connected undirected graph so we have to return a deep copy of the graph what does this deep copy means we will see so each node in the graph contains a value so we know this is a graph node which has a value and a list of its neighbors neighboring nodes right test case format so the test case which is given to us let's see what that is so for simplicity each node's value is same as the nodes index and it's one indexed right what does this mean so see if this test case is given like this is the adjacency list which is given to us in the input adjacency list is given so see this is the list given so this is over here what they are saying that each node's value is same as the nodes index so here indexing is one based one indexed means the index will start from one so one two three four means this is one node's adjacency list this is two nodes adjacency lists three nodes adjacent four nodes existing list right so what does this mean so here this one node will be there and its adjacent nodes will be two and four so one's adjacent node so this is the undirected graph so there is no directed edge this is undirected edge two and four so these will be two neighbors of one so this is the adjacency list and the index is the value of that node right that is the value of that node so now two this two node is connected with one that we have already done and it's connected with three so we will make we will have a node three and then we have this three node is connected to two so we have already connected it and four so four is this we have connected and now four node is connected with one and three so four is connected with one four is connected with three so this is a graph which is given to us this graph is already given to us we do not have to create it this is already given to us right so for example uh value is equal to one second node will be values equal to two so that we saw that this will be value one this will value to value three value four the graph is represented in using an adjacency list is a collection of unordered lists used to represent a finite graph each list describes a set of neighbors of node so all these are the neighbors of this node one these are neighbors of node two so we have already created graph right i hope you understood this um the given node will always be first node with value one right so this will be always starting with value one so given node will be one then it will be two three four like that you must return the copy of given node as a reference to the chromograph so we have to uh return the copy so this copy of this node we have to return as the output that is value one node so what does this deep copy means to make a exact copy of this graph so we have to create exact copy of this graph one two three and four something like this exactly copy of this graph we have to create but the difference will be that these are not the same nodes 1 are not the same nodes so for example this node is in memory at 3 000 edges and this one will be some other node they have same values 1 but they are not the same node this will be something somewhere in the memory at 5000 edges right so what we are doing is we are creating a copy but that is a deep copy means these are different nodes although their value are same value is same but they are different nodes right so for each what we have to do is we have to create a copy of this one node that means uh a cop we have to like simply we have to create a new node like we do we create node like this in a new node with the value what with value one so this will be our new node this one and then we just need to connect its these neighbors we just need to connect its neighbors with uh it's like adjacency list we have to create for this node right like this is adjacency listener similarly adjacency list for this one node we have to create in which this two will be also the copy one copied one right and this will be also the copied one right so this is the what we have to do we have to make a deep copy of this graph and we have to return the address of the first node this node we over here said now that you must return the copy of the given node as a reference to the clone graph so this is the first node and we have to return the copy of the given so this node with 5000 edges this is the thing we will return okay i hope you understood the problem uh let's see how we can approach it so we can see we have to make a deep copy right we have to make a deep copy so that is very simple what we have to do we just need to make a new node for every node and that will be the copy one right that is simple right so what we will do is we will start from this uh we will be using dfs depth first search reversal depth first search traversal for this problem you can use breadth first also traversal uh we have we will use the dfs for traversing the graph you can also use bfs so if the difference is just that what is the difference in dfs how we will move we will start from one node then we go to its neighbor two four is also its neighbor but first of all we will complete two's path so one two then we go to three and then we go to 4 something like this we do right but in bfs what we will do we will be uh for starting from 1 then we go to its neighbors 2 4 2 and four so in bfs we go level by level so this is dfs in dfs we just go in one path first to the one end first so but in bfs we go like for this node we have these two uh neighbors so we will traverse them first we will not go to after two we will not go to three we will go to the four which is other neighbor of one so either way you can traverse uh it doesn't matter we will be using dfs in this problem okay so now let's see how we can do this let's see how we'll approach it so see what we will do first of all we start from here right we are starting from here so this is we are currently here at this one node so what we will do we will make a new node of this current let's say this is current so current value currents value we will make a new node and let's say this is a new node let's name it as new node only so this is a new node so we have created a copy so something like this one will be created this new node will be created which is a copy of this one but this is obviously another node it's not the same node it's has value same but address will be something different for this node in the memory right now we have done this now we need to create its neighbors two uh we have to create its neighbors two and four so how we will be going we'll be using dfs so first of all we know this is the node right which is one node we know its neighbors are two and four we have the adjacency list so first we go to two right we go to two so now current is at two so current is here now so what we will do is we will make another copy of this two node again we will make a copy so two will be created obviously it's that different address is not the same node then we go to uh enabler of this two so we go to now current will be current will come here current will be three so we will create three okay now what we will do uh we will go to this neighbor of three left out of three will go so this will be four so we will create a node four so current will be now four at four current will be at node four something like this or uh right now we have so right now current is here now for this four three already we have done uh this one we have to make for this uh four node because this is its neighbor right but this one is already created but at this point see guys at this point we don't know that we have uh like in the previous uh path we have created this one node we don't know because we are not storing anywhere this is this now we just created it so here what we will do now we will create another one node copy of another uh copy of this one again so this we do not need to do we have to use this only because these are connected right this one which was connected to 2 is also connected to 4 so we have to not create another new node so for this in order to solve this problem what we will do now we will be storing these nodes whatever we have created new nodes now we have to make a track of that we have to keep a track of that we have created it so what we will do here will be the previous node and here will be the next node a new node so for this one which was previous we have created this new node which is this at address 5000 this is another this is see these are not the same nodes don't confuse them the this here will be storing the node so this is at the other node 3000 edges node and this is 5000 edges similarly for this two this is the previous node and this is the new node for this also three we'll be storing the previous node and the new node and for this four we'll be storing four and the new node so now when we come to this current and we have to create uh here we have to create copy of this one we will check whether it was already created or not whether for this one whether this one is in the map or not yes this one is in the map means we have earlier created its copy deep copy is already created so just use that only so from the here we will get this is the key right this is the key and this is the value so from this over here we will get the this address of this one this new node and we will connect them right so similarly we will uh do for the same so we will go here so similarly we will be connecting all these like this when we uh right so i hope you understood this fact why we are using map right so let's understand the code once how basically it's working so see what we are doing is we have create have this function where we have to return the node address and we have this function clone graph and we have this map is node star means one node key will be node value will be node and this is a pointer so address of the node will be stored right address this is because this is a pointer variable right so this is node map if the node is null means that there is no graph just return null okay and if there is a single node only in the graph like here it was uh over here it was like this because there was a single node right single node there were no neighborhoods because adjacency is empty right so there are no neighbors of this one node y1 is there because this is one value so then just create a clone of this simply just clone of this node and return that law otherwise we could call dfs on the node so we are calling dfs on one and we're passing the map also so this map is also passed now let's see what is happening in the dfs so what we were doing if you remember when we were traversing the graph what we were doing we were creating a new node we were creating a copy if the copy was not present in the map so for this one two three four copy was not present right but when we reach to four and again one comes then one was present so then we will not make again copy so what we are doing we are first of all making a name uh this is a neighbor this is adjacency list we are creating uh because sc node uh also adjacency list every time we have to create a new because this is the previous nodes adjacency list a new vector for this one node will also be created now wherein we'll be storing 2 this new 2 and this new 4 for this one so a new vector a new adjacency list for this one also needs to be created which is this one and then we are making a clone or we are making a clone of uh this node so once deep this copy we are creating current value and we are storing for the current this current we are storing its clone this new node that is what we discussed right this was a previous node and this was a new node so we are storing it because we have created a copy now we will be storing will be keeping a track of that in the map so the current was the previous this graphs node which is given to us this graph which is given to us is the current uh node and the colon is the new copy of it and then what we are doing we are going to each neighbor of that current so what we will do we will go to 2 so we are going to do and what we will do we will check whether 2 is in the map or not if 2 is let's say here 2 was not in the map only when we are starting one will be in the map so we go to 2 is not in the map means we have to create a copy of so we are creating uh what we will do is we will uh if it is not present 2 is not present so we will call dfs for that 2 right means we'll call this function for two so twos again two copy will be created and it will be stored in the map right and then we will go to the neighbors of two so that is how dfs works right we discussed one then it will go to two and then we will go to three so its neighbors otherwise if two like over here two three four when we are here at four when current is four so then 1 is its neighbor right then we will go to its neighbor and 1 is already present in the map so if one is already present just get the new node address a new node from the map and push it in then adjacency list of that new cl uh node right so this is how we are using the map so then this uh new uh dfs call will not be done if the if it is already present in the map so one is already present in the map so we will just uh in the force adjacency list we will just add this new ones this is this one will be added this right so i hope you understood the problem and the approach let me know in the comments if you have any doubt i found the video helpful please like it subscribe to my channel and i'll see in the next video thank you
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
1,178
hello everyone it's november the 9th look at that we have a hot question today oops now ready to do hot question on tuesdays but i guess that's fine alrighty uh oh i've done it before damn they just recycle hard all the questions oh but this is not this might be one of the questions i've done as a contest it's likely all right so yeah based on my track record didn't look very nice so let's see wow i try to solve it cannot no i don't think this why did i do this question i don't even know september 5th and i failed and i was like alright i'll do the second day all right let's take a look awesome by the way with respect to a given puzzle string a word is valid if both the following conditions satisfy word contains the first letter of puzzle for each letter in word that letter is in puzzle for example the puzzle is abcdfg the invalid words are words contains the first letter of puzzles that contain a as a has a and for each letter in word that letter is in puzzle so all the letters must be in it so has to contain the first letter wait no it contains the first letter so it has to contain the first letter and then the rest can just need to be inside i don't have to contain all of them beef does not contain a and based has includes us which is not in the puzzle okay return array answer where answer i is the number of words in a given word list that is valid with respect to the puzzle puzzles i okay so one that would so okay i must contain the first letter so puzzles is this the first letter is a so for this to be valid it has to contain a okay so i contain a and it only contains a so everything will be in so that's good but this is not good because i have s this is not good because i have l i have c so that's why these are now good single one the first one is good this one's no good s and the same thing with l and c and this one first one's good second one is good third one is good fourth one is not good because i no c no good it's the same thing first is good second is good third is not good so just two yes uh this one first is good second is good third is now good this one's not good because i have b but act is good right actress good and uh this is not gonna know o this is not gonna know t last one first is always good oh wait that's not good because i have g nobody has g i see i completely forgot how i did it so it's a completely new problem the words length is 10 to the fifth each word is 50 character long plus or length 10 to the fourth positive seven lower case electrons each puzzle does not contain repeated characters all right so apparently um we can do o n m but o m must like most likely than time out i think that's what i did last time right it was timeout so cannot do omni so what can we do uh see we have these words all right i have the puzzle so we have to scan maybe we can build a try how about build a try of the words so if we build a try afterwards and then oh how's that going to help if we give it a try afterwards and then i want to check how do we check exactly how do we check well we know the first letter must be inside the try but we cannot really check the try right how do we check the try for the first letter well the okay i see the purpose we try so because it's a try we're going from the root going down if at any position we already know it's not good then we don't have to try all the rest for example the trial will start with a right and then we'll branch out to aaas and then in this case right i branch out to a s and s is not in there so any remaining will not be considered right and again with branch to b and a branch l all the l remaining is not considered all the i is now considered all the c is not considered like this all these three can be discarded in one shot okay um so say i built a try out of it all right i built a giant try out of this then what oh shoot try what's the smart way to build try i don't remember ah man we'll figure it out i'll figure out so a little try and then what we have to go every single one right every single one like if every single one is a valid i have to go through every single character all right every single one is doesn't seem to be right let's say we go a and i say it's inside so a is inside what do i want to know what i want to know is given this puzzle which words does not contain one of the letters in it if i have if each word turns into a set all right if each word turns into a set and each this turns into a set and i can do set difference yeah that's still we have to do every single one that's that gotta be timeout i gotta timeout how do i know hmm how about well that's all that's still omn right that's still omn i think about bit manipulation right they say the puzzle lens is seven right so that's seven and everything is lowercase english letter right so all these can be represented by a 26 bit number we just you know uh set it and then fill it into the bit right into the bit so everything can turn into a number and all these are numbers as well a seven bit number so for each one all we need to do is just to do uh exclusive or all right if exclusive or turns out that it's uh we want everything contained in here is contained in here so exclusive or well is that exclusive or no it shall be and this and with this all right so the idea is if everything in here is contained inside there all right so this one shall all the ones must be one in here all right okay so we can okay and the two so after we end uh this will be a larger bit this will be a larger number compared to this so after we end this shall not change because if there's something that's not in it right that's a mismatch then oh wait it shall be not end it shall be gosh every or right or it the two or it shall be the same right so now we or it's the same we just compare this or this if the result is same that means this must contain everything inside here if anything is not the same ah if everything is not the same i can't contain here but not contained there but that's fine well it's not fine something is in here but it's not in here so if i order it that would be no one so this value will change so exactly so we or it and we also need to find the first value and to check if that bit is set in here okay but so it's going to be 10 to the fourth times 10 to the fifth because i have to go every single one like this and the second one can we do better than that i don't know um how do we do better than that like can we store some information after a certain yeah that's that feels still in a timeout i guess look at here 7 12 right 7 12 means but the operation itself was fast we just need to do hmm two like bit operations now the question is can we use the information from say one of them to deduce for the other so like for the second one we don't have to go through every single one because we went through one i kind of know already can we do that let's say i know a belongs it belongs to this right so what does that tell me everything here is inside here all right and then the first character is also inside here so for this one i don't have to check the first character because the first character is the same right and then i know everything inside here is in here yeah but i still need to do this check i don't know man let's fail so i'm gonna timeout if i try it ten to the fifth ten thousand no that's one hundred thousand i think i have to go back to try let's build a try and see how it looks like so start with a well start actually root start with root and we have a right and then a right the second one is a and s branch out uh a plus a b l e and then x one is a b i l i t y yeah i just uh i say it and then a c tt and hctor and the last one acc ess right so that is a try so first one comes in as a b o v e y z i have to do so we can say see if a is inside say a is inside okay and we check if that is the first yeah we can do the check too so a is inside okay that's good so then we branch asbc we branch to a again is inside so this one is good and then s is not inside so all this branch won't have to go and then b is inside okay and then c is not inside so this differential don't go so we have a and b the two branches left a keep going a is inside so that's good and b keep going we have i and l i is not inside so that friend is done al is not inside half interest so now i have only a itself the next one is a good and then uh end we don't have any more so that okay that's one word so that's for the first oh maybe this is okay i'll try the second one a b r o d y z all right so abr d y z all goes through the exact same process okay but isn't that oh wait that is not don't go through the entire 10 to the fifth and the third one absolute so we go a and so absolutely right so we go a which is good now uh now in the branch out we have asbc right so we have absolute a is good s is good b is good c is no good so we have a s b three branches the next one is a is still good nexus a is still good and says i absolute io that branch is done and l that's when l is good and that's my a is good uh s is good and e is good so we have three well you want to try that yeah i'm very sure very certain that o n is not going to work so if we're sure it's not going to work so let's just go with the try i think we have to at least try the try right if the trial works it's good if the try doesn't work uh we figure something out you know probably just call it quits so i already don't know try the only method i can think of well the second method the first method definitely is going to timeout all right now the question is how do we do the try all right if i remember it correctly i think try is equal to lambda right lambda default right so from collections port default dipped lambda default dict try i think that is a definition which means try is a function right try it as a function and this function returns a function and when you try as a function which is a lambda function it returns a default dipped which takes try as the function again which takes try as a function again which means the default dict each value itself is another default yeah i think that is true so we have root it's just going to be try all right that's root and then we're just going to go for word in words right and for letter in word we say um if so we have to go root is this and each word node is going to be root i say if letter is not in node then node ladder what does it doesn't because it's defaulted we don't we just can go node equals node a ladder it's fine because default dict the next node will be the next try node and we just keep going until the end right until the end so while the end how do we check if the word has reached the end well we check if the word has reached the end by i just realized there is a there could be a faster way if we keep a representation but we don't know right we don't know if there's going to be any branching so i can't do that so we keep going node and at the end the last node will have no children right basically that's what it is last so i can just say land node equals zero that will be the indication of we have reached the end okay let's just keep that right so let's do the try so the trial is done now we're going to go with puzzles right let me say for pus in puzzles so for each puzzle i need to turn that into a set just for ease of handling things right it's not a set oh but the length is seven so i can just go check there's only seven all right so i don't want to turn into a set let's just try just go for it and now we're gonna traverse i'm going to have a result rest equal to this for each one rest.0 and then we say node equals root right and that way it is go one by one i'm going to say for while how should i do that we're going to traverse until now it's going to be a it's a bff so i have a cube right so i have a q and then q is going to be root right and then we say while q all right wow cue the next node and the next node coming out next node if it's not we do this so we find wow cube temp is this all right and i'll say four node in queue right noting hue um i want to go every single one right for letter in node so i'm going to be letter in node so for each node the letter right and now we say if oh and also the first letter so proposing this and then uh is first letter so how do we do that i want to go one by one so we're going to check we'll call each one then yeah how do i know if i need to push two things into the queue right i think i'm gonna push two things one is a root and the other is if the first letter is in it right so for node and is contain first thank you all right and for lettering note and let's say if letter is in plus all right if the letter is impulse then uh temp dot append node letter so the next note right note letter and then letter equals to contain first or letter equals to positive zero right i don't think it was or what is this right what is this bitwise or which is fine okay so when uh do that letter impossible for node okay let's say if a lan node is zero that means we reach the end right plant node is zero then rest minus one plus equal to contain first equals wait can i do that plus let's say a equals zero a zero plus equal to true if we do it again yeah i think it's true so we just plus equal to this right this and else alif right aleph letter in wait what's the letter as else that's four all right so i get a node and if node is the end that means we have reached the end of a word and i want to check if contain first is contained all right otherwise i'm going to go for letter in node and if the letters in the pulse in the puzzle and append the next node right and append the next node and contain first or the current one equals to the first letter right so undo that and once we go through everything let's say q equals 10 all right and once the queue is all exhausted then we go for the second one okay and then at the end we return rest all right let's see if this logic works and it's like if the letter is not if the light is not in this puzzle then we don't go down that route so maybe right maybe so first one is words second one is puzzles right and then we have answers these are the answers and we have another one there's a pair of words and the puzzles and we have the output okay so we have words puzzles answer and this is a find number of valid words given words and puzzles go with it first one is good second one is bad the second one is really bad we missed two of them how do we miss two of them so zero one and this okay let's see why do we miss them apple so a p l e m p all right so it's gonna be p l e a s and please p l e a s e i c ah i have to have end of word i see that so blah and then uh no it was this and then node let's say pound how do i do that in no pound like that show that should also suffice yeah i think so just indicate end of word so let me check if pound right pound in node can we do this no i can do this no oh that is interesting hold on uh note equals no a letter so a letter in node in a word for letter in word right and node go to the next one so node move on to the next empty node and then oh this one never i never reached this one so how hmm for letter in word right and then i'm gonna do a note letter once we go through notice the last one now that's wait how do i do that and here's a way i know like i have a way but it's not elegant right it's not elegant i want some elegant way i guess the last one yeah so for last letter and no letter would go to the next one but that's the last letter i need to notify on the last letter uh this is stupid i have to do like this i have the numerator word all right and then let's say uh say what ladder in position i go to the next one wait that says true right wait hold on so i always go to the next one don't make quick moves let's see let's uh let's print out root let's take a look so we have a p i x please right and then a b p l e and e the next one has a pound and p l e a s and we have a pound none and an e yeah this is true this is good we can do that so i think the tree is fine why is this not fine all right let's see which is 0 1 3 this one right so this one apple is good because i have afp and these two are good as well oh i know now i know so i cannot do this if else no if else it's just if there you go that's how we pass there we go we pass both all right so to try let's see how it goes i mean i can also try let's say uh for p in this i say p plus equals set p set is not subscriptable oh of course it's not p set we'll have to go plus and then this is p set puzz and then in p set i think it might be faster doing this way okay let's use a set uh console okay let's see we can get us charging judging now either on or we time expires hey we got wrong answer not time expired now we're not gonna test this right come on man i see how many we've done oh we passed the nine test this is the last one this might be right i think this might be right but we just need to figure out why this one is wrong expected 40. so we're missing counting what oh and this isn't counting a lot i said this already why are we still miss counting paying first hmm no idea i think we need to oh i don't like this i do not like how this one is going jesus look at this okay so all we can do i need to narrow it down right and then narrow it down to a case now that's not the way to go you want to narrow it down write our own test cases that's how we narrow it down but we need an absolute truth well absolute truth can be obtained just by doing uh set operations right so we're going to write a timeout we'll call it solution 0. yeah let's handle this the right way so let's do a solution 0 which is just going to be rest equals to this right and let's say for puzzle in puzzles right and then p set equals set pause and all we want to do is to do a set difference right which union i would do a union we do a union so a equals set let's say abc b equals set let's say aaa so a is the secret right so asc is the puzzle b is the word and we can do a dot union b this one if b is initial equal to a which is true and we have a c let's say set a d right then we do a union c that will not be equal to a so that's how we're going to do so we have a p set and we can actually do yeah that's let's actually um word sets all right let's do word sets equals to set w for w in words all right and now we have p set as this now we're going to say rest.append huh waiting to count the number of when sum it up hold on are you telling me do we do this p pause sets equals to set plus set p for p in puzzles right and then what then we're gonna do for p impossible right for p and positive for each p we need to go inside words so we're gonna do sum right somewhat sum for w in word sets for each w we're gonna do p dot union w equals p sum this and i'm going to return this and to make it even more yeah this should be fine right so that's solution zero and we can't run solution zero uh what oh shoot i has to also check the first oh jesus ah what do we do all right we do this so pause sets going to be set p and i have to do two things right set p and p zero right and then for p and p zero in this with this equals to p and p 0 in w there we go now we pass right now we pass but this one will definitely time out so we're not going to not even try it but that's our base so now what we can do is instead of doing so we have a solution zero right and i would have another solution equals solutions now the test so we can write our own tests which we need uh from random import and choice python has well let's see python has uh english letters i forgot it has something english letters like alphabet no it's uh there is a thing string module there we go string dot ask your lowercase that's the one so i need to import string okay so import string actually i'm going to try here first report string and from random import choice so string dot ascii lowercase right all right so we can just do choice string dot ascii lowercase there you go that's the one so actually we just go from string import ascii lowercase right so now we have that so the tests we can write tests in equal to so we have to go num of tests equals 10 uh len plus let's do 10 len oh that's too much land puzzle let's do like five puzzles a lan word that can be like 10 that doesn't matter and then the length of words so length words and the land word each word we can use the same each word is what 50. let's go 10. all right so tests gonna equal two oh wow this is going to be something for this in range num tests right and each one going to contain uh two things all right the first thing is going to be a list the second thing going to be another list so first things list is going to be oh lam puzzles all right land puzzles and the land pause lamppost is seven right now positive seven so the first one is the words so i'm going to be for this in range land words right and that's going to be for this range blend puzzles all right okay so we can actually do this right all right now we're going to handle each puzzle how do we handle each puzzle i'm going to say this join all right joint choice ascii lower case for this in range lan word right so that's the first one and we'll do the exact same thing for the second one all right join it's gonna be land pause okay so that's the tests so let's say for i was puzzles right in tests reskin equal to this answer gonna equal to solve zero dot five words puzzles and it's the same if not the same answer s and the test so i'm gonna print out the test which is words and puzzles okay run it i don't know it pass everything which is bad so we're gonna increase how do we number of tests right so we can do more number of tests but i'm putting the fine yeah let's go land puzzle puzzles also 10. land words let's go to 100 word all right and then each one is short geez don't find come on wait are we doing it right let's go back here and then just want to see print words and puzzles yeah seems to be right how about putting the best answer oh zero that's the case that's why all right so we need to uh yeah this is like too random right it's too random it's hard to how to make it well we can make the land wood smaller let's say land word is only five a lamp puzzle let's make it like ten trying to force it yeah still don't see ya still don't see any all right let's say land puzzle is 26. what still the puzzle is long and still doesn't return anything are we still getting zeros now we don't get zeros we have to have some that doesn't oh because the first one needs to be inside dang it can you can't find it that's the thing can find it all right let's how about the 50. let's just like max out we'll try to see all right and then we do more test cases a thousand test case but each one is small right a thousand test cases each one is small and if this we don't do anything i just so pass anything happens nope nothing she's 100 10 puzzles on 100 words wow it's the first time that this method doesn't work unbelievable does that mean we do have to debug this way hold on guacamole yes it's not working man this one is not working holy shoot all right um let's modify this yeah this one is not working this one's not working this one is not working i have to go back to this and we actually have a correct answer so we don't even need this anymore i don't need this anymore i have the correct answer all right okay let's take a look apparently there are a lot of issues with this so what we know is the first one is wrong all right so that's actually good we only need the first one for the word all right for the word only the first one no wait not for the word it's for the puzzles jesus uh left parentheses wait there's no left are you kidding me oh i probably need to there we go so only the first one so the remaining boom no need immediately and narrow it down so now what we need to do is let's remove say half of this so we don't know where half is now we do go here that's about half right so we are removing half binary search right when a binary search to find a small enough set so i can work with no i don't need any of this i'll use this come on yeah show me oh i don't need to i'm gonna run here i just run here oh but it's gonna be so slow oh good right that's good so keep binary search all right we uh let's go binary search and binary search a small enough set that i can work with go up so that's about half and uh we're gonna remove all these so we gotta do a smaller set i don't know i don't like how is this good enough to run with my algorithm super slow uh oh this one's correct so it happens on the other side which means we are going to uh control z gx td all right so now when control f gx td yeah that's the one so everything above it be gone now we know this now we just double check but i'm pretty sure because we have failed so i'm pretty sure this one shall work so just double check and then with this we just need to do the same thing finally such oh wait what the heck hold on what there isn't one gx cd and hold on why is this scheme not working all right let's try to run ourselves maybe i'll work on ourselves as well first of all we don't need these two right and then we do this and oh yeah this then all right let's see how long it's gonna take yep it's actually not that bad uh we don't have to print the test no need to do this boom answer is 19 i'm 18. so i say i delete half i can't believe that like the leading half is not working right i say i'm deleting half right so i deleted half i'll run it again now i pass so i say it's the first half all right so i'm going to delete the second half and run again and it pass again what the hell wait how so what happens is the first half it works the second half it works both half together it does not work oh wait how is that possible the hell let's do this type of removal that's going to take a long time all right yeah we just keep removal until yeah for whatever reason half is not working so we're gonna do that's gonna take a long time all right it's not gonna be like this so we're gonna do a bigger one all right let's go a bigger one this big works how about this big still works so we cannot remove too much how about i remove a third right how about remove a third geez remove a third works how about remove this much i honestly have no idea i have no clue why some work some does not work which one it's like there's a critical one if that's the case it works because i removed the first and my answer okay my answer is well here my answer is too small right so i did not count one of the result how did i not count one of the result i don't know i me just keep going jesus this is gonna take a long am i time all right so how about this nope still down right now yeah i want to find out why it's still not right all right ah the temptation of trying to find a position you've got to be kidding me somewhere here okay how about this okay so is it not right how about here no this one's welcome oh this one's working as well oh i think we're getting closer come on show me all right we are getting closer to the okay how about this one still good to go come on okay about here man this is very frustrating trying to just find out where the problem is uh so still too much oh we're getting there oh still good overall it's bad so i can do a small range that's the small range okay good still good it means different things right ah yeah i just explained to you quarters or higher is also and also well high no these are the same i thought you're talking about high and the high is different no oh hold on maybe we already we're getting there i think that's the one the same both are common there we go that is the one all right we identified that's the one sigma now what i'm pretty sure if i delete this well that's why this won't work this one will work so it's the inclusion of the sigma will cause it to be wrong okay so something with sigma that's interesting sigma is inside now we have to do something similar and hopefully we'll be able to let's just get half of this uh-huh go again oh jeez this is just frustrating very frustrating what if we delete in the middle oh delete in the middle hmm this seems promising delete in the middle yep delete in the middle nice delete in the middle we oh yeah we are we're achieving something okay let's delete in the middle the elite in the middle come on very nice delete the middle beautiful so we are finally making highways and to decipher this stupid thing it's a stupid thing come on nice we still error good nice now i go into the front nice now i'm going to start deleting back right maybe we can be more ambitious now just leave the first one right and also don't delete the last one very ambitious now nope um and we can also try these hmm something in the middle is causing it trouble yeah we're good this is such a huge test case it's just so difficult to work with nice and i just want to know i want to know why what caused the trouble all right come on we can find it we can find a reason ah keep going oh too much so something inside this range is contributing so that means oh shoot god come on man from here to the end okay so deleting this is bad which means i can delete the front okay so we can do here study the front but excluding the first one there we go nice good job now we are getting closer and closer again let's just delete this part if it's good that means we can delete the give you this part there we go oh that's the trick so we can so we just go do whatever right run it's good and that means well actually you have to do this all right move this and we run it so bad go to about half remove go still bad nice almost remove still bad oh that's good careful when i remove the remainder spot remove this let's put which means ah my bad didn't really do it well once i find out the reason i'm gonna celebrate jesus we're getting it down we're narrowing it down oh good we are narrowing it down come on oh okay almost there oh okay sigma is the other reason repeated words you've got to be kidding me really oh finally narrowed it down okay now the question is why wow exactly why oh i see all right let's do this come on yes well terrible run time but it worked that freaking worked oh my god that was the most intensive debugging session i've ever done repeats you know what uh actually i don't know what i don't know i mean we could turn that into i mean yeah we can turn that into a counter right so let's say for word count in so i had to counter a counter right so i'm going to counter words and then we don't have to do this we simply do this or equals count right so if we do it this way it shall still work so many value to well unpack has to be down items okay i have to try this solution and see if it's in it faster i don't think so but might as well try it no not really just a little bit all right that's it i'm gonna have to read the solution again but uh we did solve it we didn't solve it uh i'll see you guys tomorrow adios
Number of Valid Words for Each Puzzle
valid-palindrome-iii
With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied: * `word` contains the first letter of `puzzle`. * For each letter in `word`, that letter is in `puzzle`. * For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while * invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle). Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`. **Example 1:** **Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\] **Output:** \[1,1,3,2,4,0\] **Explanation:** 1 valid word for "aboveyz " : "aaaa " 1 valid word for "abrodyz " : "aaaa " 3 valid words for "abslute " : "aaaa ", "asas ", "able " 2 valid words for "absoryz " : "aaaa ", "asas " 4 valid words for "actresz " : "aaaa ", "asas ", "actt ", "access " There are no valid words for "gaswxyz " cause none of the words in the list contains letter 'g'. **Example 2:** **Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\] **Output:** \[0,1,3,2,0\] **Constraints:** * `1 <= words.length <= 105` * `4 <= words[i].length <= 50` * `1 <= puzzles.length <= 104` * `puzzles[i].length == 7` * `words[i]` and `puzzles[i]` consist of lowercase English letters. * Each `puzzles[i]` does not contain repeated characters.
Can you reduce this problem to a classic problem? The problem is equivalent to finding any palindromic subsequence of length at least N-K where N is the length of the string. Try to find the longest palindromic subsequence. Use DP to do that.
String,Dynamic Programming
Hard
680
215
hello everyone welcome to coding decoded my name is sanchez i'm working as technical architect sd4 at adobe and here i present day 22 of june lead code challenge the problem that we have in today is kth largest element in an array so here there in this question we are given an array of integers we need to identify the kth largest element present in this input array the question seems like a very straightforward question and i have already solved this using three approaches in this video i have solved this question using three approaches the first one is the basic sorting based approach using an inbuilt short method the other one is using heaps technique and the third one is the most interesting one where i have explained the quicksort technique i have coded live for you guys and for the change my video was also on the comment says it all and this question is not a very tricky question but solving it using three approaches is where you can learn apart from this don't forget to check out coding decoded sd division sheet all the crucial topics that are ours and interviews are mentioned as a playlist over here if you go and check out the backtracking one the try one the graph one the dynamic running one you will find the first problem as a template that you need to learn so if you're not aware of backtracking go and check out this video you will learn the template and you yourself will see in all the questions that are asked on the concept of backtracking this template gets applied i have listed few of them in the increasing order of complex complexity medium to hard similarly for the rest of the sheets as well first thing that you will see is the template and then problems where the template is being used how it is being used and in increasing order of difficulty so over to you guys the hard work is all yours i can only be the catalyst and i don't want any subscriber of coding decoded to feel that he or she didn't prepare well after the end of these two months it's your holiday time so don't waste it just like that i promise if you will go through these sheets then these concepts will be on your tips with this let's wrap up today's session over to you guys thank you you
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
661
hey everyone welcome back and let's write some more neat code today so today let's solve the problem image smoother we're given a two-dimensional grid that we're given a two-dimensional grid that we're given a two-dimensional grid that can be a variable size and we just want to apply a pretty simple algorithm to every single cell in this grid so for example this cell over here s we want to replace it with the average of the nine closest cells to it so like the 3X3 square around this position basically we would take 1 + 2 + 3 + 6 7 8 + 11 12 and would take 1 + 2 + 3 + 6 7 8 + 11 12 and would take 1 + 2 + 3 + 6 7 8 + 11 12 and 13 add all of those together and then divide the result by 9 because there were nine elements so to take the average we divide by nine and we want to round down in this case so if it's a decimal value we are going to round that value down now of course not every single cell is going to have a 3X3 square like for example this corner over here if we were to look at the closest cells to it some of them happen to be out of bounds for those we pretty much ignore them but we take the average pretty much in the same way so with these existing cells we take all four of them add them together this time though we would not divide by nine we're not taking the average of nine elements we're taking the average of four so we divide that by four and we still round down and that new value that we have we would end up putting it in this corner spot conceptually this problem isn't super difficult in terms of code how exactly are we going to implement it because if we try to implement it in place like if I were to first look at this cell and then replace it with like the average of the values and I do that then I want to do the same thing here I want to replace it with the average of the closest values to it if we try to do that we're going to end up looking at the value over here it's not the same value that it originally was it's not going to be a one anymore so we're going to have a problem if we try to implement this in place at least if we do it in a naive way I will show you in the second half of the video that we actually can solve this problem in place but for now let's just create another copy of this grid and then fill that in as we solve this problem and then we'll end up returning that grid now the only hard part in my opinion at least for like a beginner would be for a cell like this one how do we even get all of the neighbors you could kind of hardcode it but that would take a lot of code the easiest way is actually to do a nested Loop like if this is the position that we're given and let's say the coordinates of it happen to be RC for row column we then would just run a nested for Loop starting from here going through this row then going through this row and that will allow us to accumulate all nine of those values and then we can divide that by nine and get the total how do we do that well if you look the top left corner is row -1 and column top left corner is row -1 and column top left corner is row -1 and column minus one the bottom right corner is row + one and column + one so we can kind of + one and column + one so we can kind of + one and column + one so we can kind of run a nested Loop where the row iterates over these values and the column colum iterates over these values one last thing to mention if we were to do that over here we would get some values that are out of bounds it would be easy for us to detect that a coordinate is out of bounds because we can verify like this is within the range of the size of this grid but one thing to notice is when we accumulate these four values we want to keep track that we only had four values because then we would end up dividing by four so that's just a little catch with all that said though we can code this up what do you think the time complexity is going to be well one we're definitely going to have to iterate over this entire grid let's say the dimensions are n by m so we're going to have to do that and then for every single cell we're going to have to potentially iterate nine times now nine is a constant so it doesn't really change the overall Big O time complexity this would be overall time complexity and since we are creating another grid of the same size the memory complexity is going to be the same actually it's going to be n * m at least for the first going to be n * m at least for the first going to be n * m at least for the first solution we will find a way to optimize the space down to constant time but now let's code this up first with any type of 2D grid problem I just like to get the dimensions of the grid and that's pretty easy to do in this case just like this and then we want to create that two-dimensional grid that we're going to two-dimensional grid that we're going to two-dimensional grid that we're going to end up returning that copy and I'm going to initialize it with all zeros it doesn't really matter what you initialize it with in Python it's kind of weird to initialize a 2d grid so here with the first ARR we're going to multiply it by the number of columns cuz that's going to tell us how many values go inside of a row and then how many rows do we have that's going to be like this so This is called list comprehension in Python if you've never seen it before but basically gives us a two-dimensional grid of the size of this two-dimensional grid of the size of this two-dimensional grid of the size of this matrix it's all zeros and that's going to be what we end up returning but before we do that we actually do have to populate it so let's iterate over the entire input grid and we can do that like this now is the part where we are going to iterate over that 3x3 Square kind of centered around these coordinates so I'm going to use different variables for that I'm going to have I in range from like we said row minus one all the way up until row + one minus one all the way up until row + one minus one all the way up until row + one the only thing is with python this range function it will actually stop here but not include the last coordinate so if we want to iterate from here including this we have to actually set this to row + 2 we have to actually set this to row + 2 we have to actually set this to row + 2 we're going to do the same thing down here for J in range column minus one all the way up until column + one but it's the way up until column + one but it's the way up until column + one but it's not plus one it has to be a plus two and then what we're going to do is basically keep track of the total for now so I'm going to have a variable up here I'm going to call it total I'm initially going to set it to zero and for every cell so the image at these coordinates i j we're going to add that to the running total so far and we're also I'm going to keep track of the count so I'm going to have a second variable for count I'm going to increment it by one every single time but this code is not complete because right now what this would do is Count would always be set to nine because we're always going to iterate nine times well one thing we haven't done is validated the current coordinate to do that I'm going to go here and say if I is less than zero if it's out of bounds or if I is equal to the number of rows it's also out of bounds or if J is less than zero or if J is equal to the number of columns in any of those cases we've gone out of bounds then I'm just going to continue to the next iteration of the loop so that we don't ever even execute this part that way we don't update the total or update the count because if we tried updating the total of course that would get us an index out of bounds error now last thing after we've gone through that 3x3 Square we do have to take the total and calculate the average from it with the count and this is what we're going to set to the same coordinate the row column coordinate in the result not in the input Matrix but in the result Matrix and then that's what we're going to end up returning so let's run this to make sure that it works and as you can see on the left it does and it's pretty efficient it's about as efficient as we can get in terms of runtime but the memory complexity can actually be improved even if it might not end up being reflected in elak code because the input size of this Matrix isn't super significant but the main reason we can actually do that is if you go here and read the fine print in the constraints you see that the value of an image is always going to be less than or equal to 255 and let me show you why that's important 255 is a special number because it's actually 2 to the power of 8 -1 why is actually 2 to the power of 8 -1 why is actually 2 to the power of 8 -1 why is that important well take note of this value eight that means in binary it's going to look like this four ones and everything before that is going to be a zero this is convenient because we only need eight bits to store this number okay well why does that help us well depending on the language you're using most integers are implemented I think has 32 bit integers in Python it's not entirely the case but in most languages you'll have at least 32 bits to work with so the original problem we had of why we had to allocate a new Matrix in the first place was we couldn't store the total like the average in a Cell because if we do that then if we wanted to calculate like the average of this guy he needs the average of all of its neighbors but if we overwrote those we can't get the original value back but if we have space here we can actually store the original value in the first eight bits like it's already there so we can leave those bits untouched but when we calculate the average for five for example uh let's take all these values and let's say I think it's 27 and then divide that by four it doesn't really matter what the value is I think it'll be something like six we can then take that new value that let's say is six and store it here in these bits so in a way we'll actually be having two values stored in every single position in the grid that works so then every time we want to calculate like the average of this position we can get the original value from the first eight bits which will allow us to calculate the average that's great and then by the time we want to return the entire resulting grid how do we do that because we know that we store the average here so when we do that we will have to for every single cell basically eliminate these eight bits or just take these and shift them to the right by eight bits that's exactly what we're going to do the only thing I haven't talked about is how are we going to take an arbitrary number and store it here and make sure that we don't touch these first eight bits well first of all we will take that number and shift it to the left by 8 Bits for example if we had a number that looks like this one01 in binary and then we take it and shift it to the left by 8 Bits that's basically saying we're going to have eight zeros that come after it so it'll look like this sorry if the handwriting is bad but then if we have that we can take this number and do an operation I think we can actually do either exclusive or logic or because if we take this number and run exclusive or on it with this number what you're going to find is that these bits whatever they are whether it's a one here or a zero here they are going to stay as they are because we know that all of these are zeros they are not going to like conflict with anything here and we know that there's always going to be zeros over here because this number is only going to be up to 8 Bits large so with exclusive or will make sure that these values end up being placed here that's how we're going to handle pretty much most of the bit manipulation it all kind of centers around the fact that the max integer in any of these cells is going to be this which happens to fit within 8 Bits so knowing all of that we do not need to allocate an extra Matrix so we can reduce the time complexity from Big O of n down to constant space now let's code up this more optimal solution so I'm going to keep the existing code as is because then we don't have to like rewrite everything I'm going to get rid of this result Matrix and I'm going to rename the return value to image now let's focus on the lines of code that we are going to change so first of all we want to continue to compute the total among like those nine that 3x3 grid those nine cells we want to compute the total but we don't know for sure that this position that this cell has not been overwritten this might not be the original value that it was so what do we do with it we just want the first eight bits from this value we just want the original portion of that value how do we get that I guess that's the part that we didn't talk about but think about it when we have a number let's say we had eight bits like this 8 Bits And then we put any value over here it could be like a one1 or anything else this portion is always going to be greater than the number 255 because 255 is what this represents if we add anything past those first eight bits it's always going to be greater than 255 so in other words we want to eliminate everything before here so we want to take this and mod it by 2 56 that's another way of saying that we want to eliminate everything before these first eight bits so that's what we do to get the original value so that we can accumulate the total now with the total we are still going to divide it by the count to get the average of it but now we're not going to assign it to the result we're going to assign it to the image to keep it in place now remember this itself is not what we want to add to the image we actually want to take this and shift it to the left by so that's what we want to add here but for us to add it here we can't just do like the simple operation of plus we have to either use the logic or logic xor I'm just going to do exor it really doesn't matter which one you use we can do it this way and I think logic or is like this so I'm going to keep it exor but that's pretty much it this is what we're doing we're taking that and storing it in the bits that go after the first eight bits so we're almost done now but remember we can't just return the Matrix now because we're actually storing two values in each spot so if we only want the new value for each spot this is what we're going to do we're going to iterate over every cell in the output Matrix and for every cell we're going to make sure that we take that cell and shift the bits to the right by 8 that will get rid of the original value that's stored and make sure that we only return the new value which was the average that we ended up Computing so we're kind of in a way reversing the shift left that we did here we're shifting it to the right by 8 Bits this is the entire code let's go ahead and run it to make sure that it works and as you can see on the left yes it does it looks like the memory complexity isn't better at least according to leak code but that's really not the case and we know why because of like the way Big O works if you found this helpful please like And subscribe if you're preparing for coding interviews check out ncode IO thanks for watching and I'll see you soon
Image Smoother
image-smoother
An **image smoother** is a filter of the size `3 x 3` that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). Given an `m x n` integer matrix `img` representing the grayscale of an image, return _the image after applying the smoother on each cell of it_. **Example 1:** **Input:** img = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** \[\[0,0,0\],\[0,0,0\],\[0,0,0\]\] **Explanation:** For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 For the point (1,1): floor(8/9) = floor(0.88888889) = 0 **Example 2:** **Input:** img = \[\[100,200,100\],\[200,50,200\],\[100,200,100\]\] **Output:** \[\[137,141,137\],\[141,138,141\],\[137,141,137\]\] **Explanation:** For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137 For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141 For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138 **Constraints:** * `m == img.length` * `n == img[i].length` * `1 <= m, n <= 200` * `0 <= img[i][j] <= 255`
null
Array,Matrix
Easy
null
1,371
Scientist Favorable Meaning Sandeep And In This Video Showing How To Solve Problems Subscribe and Subscribe This Lungi Subscribe Seervi Don't Forget To Subscribe That Sex Recorders Underwear Naseeb Akhilesh Yadav Example String Events Is Loot Ko Disgrate So Let's See What Is The Length Of The Longest Railway Platform Where Is Broken Up Lines Shifted This Particular Spring Valley WTC 9th Pure Olive Oil Back But Even Number Two Time Waste Oil Conference Subscribe Button Take And Thanks A Lot For This Will Be That 12345 Dispatch Seductive Solution This YouTube Channel Subscribe Button Take And Distance From Pearl Lived subscribe and subscribe the Channel and Share subscribe And subscribe The Amazing Points 100 Pimple Near Basically Assigned The Video Is Qualification And The Best Mobile subscribe Video Subscribe Times Points Information With Times And Times Only Information Needed At Times And The Sunday Times And Times In 0 Times And Times Subscribe My Channel Thank You Yesterday Morning Anomaly Hai Wa A Goal You And Water Possible States Which They Can Be Forgiven For Subscribe Like And Subscribe Total A Hua Hai Main Sirf Total Station Nothing But A Multiplication Of All Is Well As All The States And Different Feature Suite Will Be Loot The Correct Surya Virudha Panch Suvidha 32nd Sibal Stats Hain Correct BSP Mlas And Hans When Is That Was Full Of Present Day State And they can solve this problem using bittu sarpanch secretary vinay definitely on properties and concept from this roadways is always the effects of climate with clt20 fluid 2018 is this particular graph has grown from now android to prevent this implies that it will be similar agni then drive and Element Hair Ki Chaturdashi Rahgir 100 Only and Fuel Filter Element with 0 Elements of Obscuritism Person The Video then subscribe to the Page if you liked The Video then subscribe to the Page That Person Who has 400 1800 Vighn Subscribe Now Properties of Elements of Obscuritism One Haseen desi bf and no not at it's most attractive sales of these fruits of this to visit or game the waters admin surendra gate se bigg boss ka game agree to avoid all characters subscribe to the Page if you liked The Video then subscribe to the Light This Main One - 04 Minutes Just Press Screen Key Set Main One - 04 Minutes Just Press Screen Key Set Main One - 04 Minutes Just Press Screen Key Set Select Cell Aisi-Aisi Mobile Subha Select Cell Aisi-Aisi Mobile Subha Select Cell Aisi-Aisi Mobile Subha Hai Wah Medium To Ab Ve Can Very From This Video plz subscribe Ek Pariksha Ne Hair Set Means All The Position Love You Step After This Is This Range The Head Intermediaries and Protection That's Why The Master Same Wave Equation In Pictures Elements With All Subscribe Time 2000 12 - - - That Me Lightly Than My Best Friend Item 13 Thursday Subscribe subscribe The Channel and subscribe the Difference - 2 Channel and subscribe the Difference - 2 Channel and subscribe the Difference - 2 Target Free - 03 Dominar 400 subscribe and subscribe the Channel Please subscribe and subscribe the service of this and Yasmin more wordpress hai to that means all values ​​but after this hai to that means all values ​​but after this hai to that means all values ​​but after this position but even more times in terms of view subscribe my channel by pressing subscribe button subscribe and subscribe the Nokia Mobile Site A Suite Of That Person 's Pallu And I Will Be Also Taken 's Pallu And I Will Be Also Taken 's Pallu And I Will Be Also Taken For Reduction Character Dandruff Just Smell It 4999 100 More Profit Value In This Regard With David Villa And You Withdraw Subscribe With U That Ab Singh Salute For This Difference Thursday Must subscribe and subscribe that Sudesh Aayi In This Is Canceled Because Nobody Number Time And This Is And Nadiyon CBSE Would Have Hopped For Main Net Means All Elements In Different From Here But Now Solid Evidence From Subscribe To The oil difference is really a number of times subscribe 10 subscribe The Channel and subscribe the Channel subscribe 11 - 0 11 - 0 11 - 0 That Which is a Game Friends Maximum Lanka Right Now Tell Me What We Have Similarly They Should Observe and the Best Possible Subscribe 10 Aaj Tak Vigyan Jaisal Being choked with over okay jaisalmer person which flat settle ball on bracewell is 2009 subscribe and subscribe the world will be jones and david warner hey what so f30c this is the best answer debit the receiver sim click morning first time deposit facility center length from Oil in hair position record hair fall is a picture of valve number 90 se zf hai or best platform god share food court problem solve all is well presented him with certain number slide 12485 Video then subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe the Channel Ko Hain Next Hydrate Uniform Length Objecting To One By One Adhikar Actors I Masking Against What Is The Liquid To Subscribe My Channel Subscribe Next Subscribe And Subscribe My Channel Subscribe Example and Time Complexity for this and Press Complexity Show Time Complexity 12% Pluto Spring Notification Play 12% Pluto Spring Notification Play 12% Pluto Spring Notification Play Store Google assistant and Simple Check Computers or Laptops and Computers Answer is the time complexity of complexity that this broke power M letter se zamin back vighna subscribe and subscribe the world will be a's journey need more number of characters narendra singh disassembly sendspace complexity obscene network for this problem improved to version problem is play list code 1915 se end list cold 154 2f subscribe to post in comments and videos Thanks Happy Valentine's Day that if rice is completely into Were
Find the Longest Substring Containing Vowels in Even Counts
minimum-remove-to-make-valid-parentheses
Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. **Example 1:** **Input:** s = "eleetminicoworoep " **Output:** 13 **Explanation:** The longest substring is "leetminicowor " which contains two each of the vowels: **e**, **i** and **o** and zero of the vowels: **a** and **u**. **Example 2:** **Input:** s = "leetcodeisgreat " **Output:** 5 **Explanation:** The longest substring is "leetc " which contains two e's. **Example 3:** **Input:** s = "bcbcbc " **Output:** 6 **Explanation:** In this case, the given string "bcbcbc " is the longest because all vowels: **a**, **e**, **i**, **o** and **u** appear zero times. **Constraints:** * `1 <= s.length <= 5 x 10^5` * `s` contains only lowercase English letters. It is the empty string, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string.
Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way.
String,Stack
Medium
2095,2221
297
everyone i'm going to show you how to solve legal question 297 serialize the serialize a binary tree it's a hard illegal question serialize is a process converting a data structure or object into sequence of bits so that it can be stored in a file or memory buffer transmitted across network basically what it asks you to do is that it asks you to give you a binary tree or input like this and they want you to write to uh output like one two three no four five basically it want you to serialize it and then also deserialize it meaning that it gives you or in pearl like this and you have to construct or same tree from it and um no restriction on how you seriously serialize or the serialized algorithm should work but you should you just need to ensure that a binary tree can be seriously into the string and a string can be deserialized into the original tree structure so it doesn't matter what kind of order that you want to do it and you just um do make sure that the binary tree can be converted and basically and also convert it back to the original um to the original tree so an order that easier to do that i can think of is i'm going to show you how to do this with the pre-order traversal so the pre-order pre-order traversal so the pre-order pre-order traversal so the pre-order traversal is pre-ordered pre-ordered pre-ordered let me write it here the sequence is basically the root and then left and then uh right so you know the pre-order it always start with the roon pre-order it always start with the roon pre-order it always start with the roon node for example here it gives you the one right as an example one two three and no and four five and i'm gonna um oh it's a pretty straightforward when you try to convert uh the tree that they give you just need to write a function it's basically your data search function and then you append the root value basically the node into the result and after you append that you want to run the data search on the left node basically append the value and run the different search on the right node and that's how you append the value the only thing you need to do is make sure to include a comma in between each different value this can be easily achieved by the join function in python and you just need to add the comma in between each string that's for the serialize and for the d serialize then you they give you this uh root whatever list that they give you just need to uh make sure that uh do some condition check at the beginning rollouts on edge cases and then you already know we're doing pre-order right already know we're doing pre-order right already know we're doing pre-order right so the first uh node are guaranteed to be the root node of this tree and then you run you're gonna run the left and left tree you're gonna run the um the de-serialize function run it the de-serialize function run it the de-serialize function run it recursively on the left side of the tree and then the right you're gonna run the wrong on the rest of the list and then you want to return the route in the end that's how you convert it back um i think it would be more straightforward if i show you how to do this in code so let me just um start with the serialize function basically um write this route into write this tree convert the tree into a list first so i'm going to you can see the type is all tree is all defined and everything encodes or tree into a single string right the string and you can i'm going to define a result basically that's the output i'm going to encode or something in that like this i'm going to define our data search function and run this on a node so if not node if node is empty it does not exist at all so um i want to append what i want to append it to the result is um you can do any this any value that you want to say any uh alphabet or whatever number you just do need to make sure that you use the same one to when you deserialize it you don't have to use none here i'm just gonna append the unknown here and i'm going to return this and then what this function does is actually append the node of all into the uh the list right know the wall but it's actually a string it's not an integer so you need to convert this uh no double into a string first and then make sure it append to the end result here and then you're going to run this function node.left recursively call this function node.left recursively call this function node.left recursively call this function on the node all right and basically continue to run this function right and that's it for the function and then i'm going to call this staffordsearch function on the root node and then once i call the function i have all the strings that's together but it'll look like one two three and all stick together so what i wanted to do is what i wanted to return is actually i want to divide them by a comma so then i'll do the join function for the python and then for the result so in that case it will add all comma in between uh one two three and everything will add a comma that's it for the serialize function if i want to deserialize it what i need to do is i'm going to write a same function deserialize i'll just spell it this way and i'm going to pass the end result to it first and if the result the first value in the result the string is equals to none if the first one is already does not exist all right i'm gonna resolve i'm gonna pop the uh the first value and then i'm gonna return none in this case because it simply doesn't exist right and then i'm gonna say the root note is actually the tree node and if you look at the definition here the class is tree node here object so i want to use the same uh class that they have defined for us and it's basically the result list first uh index zeros value that string is the root note for this um tree and i'm gonna rest the pop and i'm gonna pop the zero right after that pop the zero is root or left and i'm going to root the left equals to i'm going to d run the d series function on the same result and then root all right i'm also going to call this function recursively so that i can run this on to get the route all right as well and in the end to deserialize this tree i want to return the route that's how you return the entire tree right so then i'm gonna call this function so the result is uh data split so split is a python function to make sure that it um split uh the data is with the comma so then i want to call the so basically the root equals i'm calling the function to rounded the serialize function on the result and then in the end i'm gonna return the route to deserialize this tree and yep if you think this is helpful please give me a thumbs up and subscribe to my channel and i'll see you soon with more legal questions bye
Serialize and Deserialize Binary Tree
serialize-and-deserialize-binary-tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. **Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. **Example 1:** **Input:** root = \[1,2,3,null,null,4,5\] **Output:** \[1,2,3,null,null,4,5\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-1000 <= Node.val <= 1000`
null
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
Hard
271,449,652,765
1,482
hello everyone welcome to codescam hope you're all doing great and we are in our binary search series where in our previous videos we have seen how binary search works the template of binary search code and we have also solved few problems using binary research logic so here we are going to solve our fourth problem using binary search that is minimum number of days to make m bookish so the input given here is an integer array bloom day which represent on which day the flowers will bloom and we have to make yum bokehs with k adjacent flowers so now we have to return the minimum number of days we need to wait to able to make ambo case from the garden if it is impossible to make a bookcase then return minus one so let's understand this with an example consider our first example given we have to make two bouquets and each bouquet should have three adjacent flowers so consider our first bouquet should have three flowers so we have to wait minimum of six days to get our first flower so on our sixth day we will get three flowers so we gonna make one bouquet with that three flowers so we made one bokeh so now it's time to move to our second bouquet so to make our second bouquet we know we need three more flowers so for that three more flowers we need to wait for one more day that is our seventh day we will get three more flowers with that we'll make our second bouquet so the requirement here given is we have to make two bouquets so the minimum number of days we need to wait to make these two bookish are going to be seven so that is our output consider our next example which is very similar to the previous one we have to make two bookcase each should have three adjacent flowers so let's wait for six days to make our first bouquet of three flowers so our first bouquet will be made on the sixth day so with three flowers on sixth day so we have to make our second bouquet with three more flowers if we wait for one more day on seventh day one flower will bloom but moving on to the next flower that is adjacent flower to seventh that will bloom only on the twelfth day so we cannot use this 7 to make the flower because we should use three adjacent flowers or k adjacent flowers here 12 is not adjacent to 7 i mean 12 is adjacent but it will not bloom on the seventh day so now you have to wait 12 more days on 12th day only this flower will bloom so once on 12th day you will get this flower you've got one flower for the second bouquet and on seventh day itself two flowers has bloomed since they are adjacent to the 12th hour we can consider picking them on the 12th day so by these three flowers we made two bokehs on 12th day so the minimum number of days we have to wait is 12 here so clearly this example shows the difference between the previous example is that the flower should be adjacent though three flowers will bloom on seventh day according to the given example they are not adjacent so we cannot pick all seven on the seventh day and make one bouquet so how are we going to approach this so according to the values given the minimum days you have to wait to get a flower is the minimum value given in the array that is 6 in this given example and the maximum days you can possibly wait can be the maximum value given in the array that is 12 in this example so we clearly know the output or the number of days we need to wait is going to be between the range 6 to 12. so as always if we can figure out that our output exists between some lower bound and upper bound or between a range then we can directly go for binary search so here we are going to use the same template as we have used in all our previous videos if you are not familiar with the template you can check my first video on how binary search works and that will help you get you know to the final research template we are going to use the same template and gonna define our condition function and here the condition function is to determine whether we can make m bokehs with k adjacent flowers within the number of days we calculated as mid value that is every time we said the lower bound is 6 and a higher bound that is right value as 12 that is the maximum value in array we are going to calculate a mid value every time so based on the bit mid value and the condition functions result we are going to fix our search space from left to mid or from mid to right so this will be determined by our condition function the condition function will send us a boolean value true or false based on whether we can make yum bookcase with k flowers by having mid days that is mid here denotes the number of days we need to wait so if my mid days are enough that is if we can make enough bokehs then we set our search from left to mid or if we cannot make enough bookcase with waiting mid value waiting for number of days as mid value then we set our search space from mid plus 1 to right so we have seen how we are going to use the condition function to fix the search space now let's see how our foundation function works let us name our function as can make so we are going to iterate through our array and if we find k consecutive bloom days which is less than the mid value then we increment the number of bokehs so consider we calculated our mid value as 8 and we have to take three flowers consecutively so let's hydrate through the array so starts from six so here in the bloom day if we wait for six days we'll get one flower so we are going to have a variable count and increment every time we find number of days less than eight so now the count is one so moving on to our second day which is also six so now our count is two moving on to a third day which is again six now our count is three so now we found three adjacent flowers which is actually the k required number of flowers to make the bouquet so in this case we are going to increment our bouquet by one so now the book is made so far is going to be one so again make the count to zero because we found three flowers so again we have to start counting from first now count becomes zero and start counting from the next value in the array so if it find again three more adjacent flowers it will increment the bokeh likewise it completely iterate through the given array and finally arrive at number of bokehs we have made from the given bloom days and within waiting for mid finally it checks whether we have made m bokeh within mid days then it returns true if not it returns false so consider it starts counting from the value seven the count now becomes 1 and moving on to 12 is not less than 8 which means we did not find our adjacent flower so now again reset the count to 0 because we should start counting from 12 again we cannot consider this flower at day 7 to form our bouquet so this is how this function works so if we can make m bokehs within this mid value then we fix the search space less than eight that is six to eight and try to reduce the number of days and check again whether we can make jumbo case if not we couldn't make embo case in this case we fix the value from 8 to 12 and increment the number of days we need to wait and check whether we can make mo case and return the final value so before getting into code as binary search reduce the search values by half every time it requires big o of log of max value in the given array time complexity and for every mid value we gonna call our condition function can make which is again gonna take big o of n time complexity so overall the time complexity of this algorithm is going to be big o of n log m so now let's see the code now so if you see the second example the number of bouquets we need to form is three and the flowers we need is two so overall to form three bouquets three into two six flowers we need but the total size of bloom day is five that is we have only five flowers we don't have the sixth flower to form three bokeh so it is not possible straight away we are returning minus one so we are going to check that condition first if m star k is greater than bloom day dot size then return -1 and the rest i'm gonna have my same binary search template where i'm going to assign my lower bound value as the minimum value in the array and the upper bound value as the maximum value in the array bloom day so now we have our basic binary search template and finally we return the value at left so now let's spend some time on writing the function can so here we are iterating through the values in the given array bloom day so if the mid value we calculated is greater than the bloom day then we increment the count and if at any point we found k adjacent flowers then we are in decrementing the bokeh because we have made one bouquet and resetting the count to 0 to count further k adjacent flowers and if at any point we have made m bokeh then we are returning true if not we are returning false the same way as i said if we cannot find k adjacent flowers in between some value is different then we are again resetting our counter to zero to count k flowers in the future days so let's run let's submit yes a solution is accepted so thanks for watching the video for more binary search series videos you can check the links in my description if you like the video hit like and subscribe thank you
Minimum Number of Days to Make m Bouquets
how-many-numbers-are-smaller-than-the-current-number
You are given an integer array `bloomDay`, an integer `m` and an integer `k`. You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden. The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet. Return _the minimum number of days you need to wait to be able to make_ `m` _bouquets from the garden_. If it is impossible to make m bouquets return `-1`. **Example 1:** **Input:** bloomDay = \[1,10,3,10,2\], m = 3, k = 1 **Output:** 3 **Explanation:** Let us see what happened in the first three days. x means flower bloomed and \_ means flower did not bloom in the garden. We need 3 bouquets each should contain 1 flower. After day 1: \[x, \_, \_, \_, \_\] // we can only make one bouquet. After day 2: \[x, \_, \_, \_, x\] // we can only make two bouquets. After day 3: \[x, \_, x, \_, x\] // we can make 3 bouquets. The answer is 3. **Example 2:** **Input:** bloomDay = \[1,10,3,10,2\], m = 3, k = 2 **Output:** -1 **Explanation:** We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1. **Example 3:** **Input:** bloomDay = \[7,7,7,7,12,7,7\], m = 2, k = 3 **Output:** 12 **Explanation:** We need 2 bouquets each should have 3 flowers. Here is the garden after the 7 and 12 days: After day 7: \[x, x, x, x, \_, x, x\] We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. After day 12: \[x, x, x, x, x, x, x\] It is obvious that we can make two bouquets in different ways. **Constraints:** * `bloomDay.length == n` * `1 <= n <= 105` * `1 <= bloomDay[i] <= 109` * `1 <= m <= 106` * `1 <= k <= n`
Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element.
Array,Hash Table,Sorting,Counting
Easy
315
290
hi everyone in this video we are going to solve a Lead Core problem the name is word pattern and the question number is 290 so let quickly see what this problems say given a pattern and a string as find if s follows the same pattern so here we are given with one pattern and one string and we have to check whether this pattern follow this particular string or not so guys how we can check it see here we are getting a so e is representing dou in this history and next time we are getting a different character and we can see V is representing K and the next time we are getting B that has already been occur in the past so we can see that this must also follow that particular word which the last word following so we can see that this character as a folder same word so last time B is following cat so this time it's also following with the cat that means till now this pattern is following the next character we are having a and this time also we can say that it should follow though because the last time also a was pulling to do so now we can see that all the creatinum pattern are following to the respective words so this is a true so we are going to return true now let's see the second example here we are having a pattern is equal to abva and the string is do cat catfish so a is pointing to do okay B is pointing to cat right now we are getting a b that has already occurred in the past so it should also point to cat right so you can see that it pointing to cat now the next character we are having a which is also occurred in the past and the last time it was 22 so this also should point to do so let's quickly see that no this is 22 fish that means it is not falling to the pattern so we can see that here our condition is not matching so we are going to return false so you can see that we got fast and here we are having a true so this is what question says to us so now how we can solve this particular problem what does such a we are going to use in this problem let quickly see so here we are going to discuss about the logic now so logic is guys we are going to check every character with respect to that particular word so first of all we will take all the word from that particular stick and we will store in an array or in a vector or we can see any list so that thing we are going to do first of all after that we are going to check length so we will say length of pattern should be equal to length of this particular string I am talking about string which contain all the words in a respective index so here you can see that here we are having 4 and a also four so we can say that there may be chance that they can follow this pattern but if length will not be equal then definitely this will not follow the pattern right so the first condition will be length must be same with respect to word now the second condition guys we are going to use a data structure that is hashmap you can call it hashmap in its Java map in a C plus and dictionary in the python all right guys so now let's quickly see how we can solve this particular problem so we have a pattern let's say A B A here in the first example we are having this pattern and the string we have is toe cat 2. so let me write here okay now guys we are going to start iterating over this pattern we are at zero index that means a character before iterating to this pattern we have to create two dictionary the first dictionary is going to be let's say per traditionally P additionally and that is empty and also word additionally that is also empty so we have this two string and once we at it once we start itating over this pattern so we are at zero index and a exist on Zero's index so we'll say quickly check whether a exists in a pattern display or not so you can see that it is empty so a does not exist in a pattern dictionary now we will move to the vertices we will say the respective word that is dou does it exist in a word dictionary no it is also not accessed in a work additionally so we will say just write pattern dictionary of a pointing to do and what dictionary inside of word dictionary you can say dog pointing to a so we quickly write this thing now we will move to the second character that is B we will quickly say does B exist in our pattern dictionary no and also we are going to check does this respective work can exist in our word dictionary that also note exists so we'll say now B is pointing to a cat in our patent history and Cat pointing to our B character in our word dictionary okay now let's quickly move to the next iteration that is B so now we will again see does B exit our patent is so we'll quickly say this cat is equal to this cat right both are same word so we'll move to the next citation we are not going to check in vertically now last time we are at a index we will say does a exist in our patent dictionary yes it exists you can see a 0.22 so we'll exists you can see a 0.22 so we'll exists you can see a 0.22 so we'll quickly match the stock with this particular word and both are same so we'll move to the next citation and here you can see that we complete this particular pattern so once we complete this particular pattern we can return a true so we will return true here so now guys let's quickly move to the second example here we have fish so let's quickly remove this dog and write fish here so what I'm going to do guys it will follow the same pattern till third index once we reach at third index we'll see does a exit evolutionary so axis in our pattern dictionary and that particular pattern is do so we are compared with this dope with fish right now and we'll say this dog is equal to fish no so this time we are going to return files return first I hope you understood the logic how we can solve this particular problem by using a hash map or dictionary or we can see map so let's quickly move to the implementation part and let's solve this particular problem so now guys first thing what we have to do we have to take all the words from this particular string and in Python we can use by using a split function so I'm going to say words which is our list now and we are going to say S2 displayed with the white space character so it's going to split all the character and will store in a list now once we done this we can see that guys check whether length of this pattern is equal to the length of these words so if it is not equal then we create a file so directly just say if it is not equal then you can return directly fast all right now guys we are going to declare two dictionary here the first is pattern dictionary and this is empty right now and the next reason is going to be word dictionary all right now we are going to Traverse this particular pattern so we will say 4 I in the length of pattern we are going to take character from that particular pattern with respect to that particular index so we are going to say CH is going to be pattern of I means currently we have this CH character right now we are going to quickly check whether this character exists in our pattern digital node if CH in pattern dictionary that means what we have to do so we have discussed already if we found a character in a patent dictionary so we have to quickly compare that particular bud with respect to the current one so we are going to say if patent dictionary of that particular character which is going to return us a word is equal to our current words means words of I then we can say it is fine it is following the pattern but if it is not equal so let's quickly it is not equal then we can return fast or like now guys if that particular character is not exist in our pattern dictionary then we have to check if that particular word words of I accidentally over dictionary and if that particular word exists in our word dictionary then we can see that it is also not full in the pattern so we can return here directly first but if it is also not exist then we have to do what we have to store our pattern as well as character in a word and parent dictionary so we are going to say in parent dictionary also we are going to store PT of that CH is going to equal to verse of I and also WT of that particular version of I is equal to that particular character okay once we have completed this Loop we can return a true as well so this is how we are going to solve this particular problem now let's quickly see whether this is working final node or we are getting any error here you guys can see that it accepted all the test cases now let's quickly submit this code and guys here we go it's successfully accepted our solution now guys if you like this video If you learned something new in this video don't forget to hit the like button and subscribe my channel meet you in the next video
Word Pattern
word-pattern
Given a `pattern` and a string `s`, find if `s` follows the same pattern. Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`. **Example 1:** **Input:** pattern = "abba ", s = "dog cat cat dog " **Output:** true **Example 2:** **Input:** pattern = "abba ", s = "dog cat cat fish " **Output:** false **Example 3:** **Input:** pattern = "aaaa ", s = "dog cat cat dog " **Output:** false **Constraints:** * `1 <= pattern.length <= 300` * `pattern` contains only lower-case English letters. * `1 <= s.length <= 3000` * `s` contains only lowercase English letters and spaces `' '`. * `s` **does not contain** any leading or trailing spaces. * All the words in `s` are separated by a **single space**.
null
Hash Table,String
Easy
205,291
225
hey everybody welcome back and today we'll be doing another Elite code two to five Implement stack using queues this is an easy one Implement a last in first out stack using two queues the implemented stack should support all the function of the normal stack post or pop empty so the push is just a pending value stop is just taking a peak empty is just returning a Boolean pop is different in these four data structures cues and stack so we have to use a queue and Implement a stack so whenever we pop in a queue we get the very left element you can say the very first element first in first out and stack is last in first out the in stack when we both we get the last element which was going in the stack and that's it so now let's scroll it down so what we'll be doing is just making a cue first you and pushing is just appending values to the stack no not stack we are using a queue and implemented the effect of implementing the effect of Stack so we'll passing a tax because that was our integer pop will leave it for later and because the other ones are much easier to understand so they will just take a peek this is how you take a peek and Peak is just taking the reference at the very top or you can say the reference of the very last element in the queue or the stack this is the same also so empty is just self Dot length of Q if it is equal to zero and length if there is something in the stack or the queue it will return true and otherwise it will return false so what is uh why is pop different so let me explain pop is different like for example we have these elements in our stack we have to remove five as we are used to suppose to because we are using Q to implement the effect of a stack so we have to remove five but with cues we cannot do this for queues we have a popular left function which will just remove the very first so what we will do but we do not want to remove the very first element so we will push it back to the queue again and doing this till length minus 1 because the length minus 1 will just take the value at the very last to the very first if we keep doing this and when we reach this point we can just say pop left and we have done we are done with our you can say pop method so for i n range of length minus 1 length of the original Q minus 1 and we'll be calling the cell function a self will be calling the push and again uh now what we will do is just pop left and after doing this we can just return self dot Q dot pop left and we are done uh yeah we are done so what is happening here is we have five at the very first because we just popped the element from the very left and push them back to the queue and now we can just pop left in our return statement which will just remove the five from the very first which was at the very end uh and we are supposed to remove it because this is how stack um stack pop works and we are using a queue and that's it let me see if there are any errors or something in this code this works fine and let me submit it and yeah that's it
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
935
hey everyone welcome back and let's write some more neat code today so today let's solve the problem night dialer this is a pretty interesting one I actually like this problem a bit of backstory in the game chest there is a piece called the night and it can move in a sort of unique way it can move in an L shape it can kind of go in four directions initially at least it can go two spaces in either of those four directions and then it kind of branches it can either go one space in like the perpendicular direction to the first one or I can go the other way and in doing that you realize that there's about eight different ways to move as a knight assuming there's enough space in the grid now the problem we are dealing with is different we definitely don't have that much space so we can't make eight moves with the Knight and we're actually in this problem dialing a phone number so I'll make a little space here cuz we're going to use it now we are dialing a phone number that is n digits long that's the only parameter that were given so of course if we only have a single digit to fill in how many phone numbers could we possibly dial that's the question that we're trying to answer and with one digit of course you can only do 10 phone numbers but in this problem as we add more digits it's going to get more complicated because the rules of the game are that our night can start at any of these 10 positions and then to dial a phone number we are only allowed to make valid moves with the Knight so valid of course means we can't go out of bounds it also means that we can't land on anything that is not a number or digit so the first thing you might notice is that five can't really go anywhere I mean theoretically it could move here and here these are valid night moves but we can't land on either of these spots and the Knight can't really move anywhere else the grid is just too small right but what about the other spots like zero is also a bit unique in this case but it can actually make valid moves it can move to the six or it can move to the four and similarly like the diagonals are actually pretty symmetrical this one can either move to here or it can move down here this one is kind of similar it can move there and it can also move here and each of these will be able to move somewhere and the sides I call kind of these the crosses or like the Left Right top bottom these ones are similar in that there is some symmetry between them like this one can go here it can go here bottom one similarly can go there and it can go here there's actually a bit of a difference between the tops and bottom and the left and right because the left and right are special they are the only ones that can go all the way down here to the zero and the six can go to the zero as well now if you're anything like me you're probably looking for as many patterns as you can you want to simplify this if you know a bit of geometry you can kind of tell obviously that there's so much symmetry going on that there's not a lot of difference like there's no difference whether we're on this diagonal or this one so you might try to simplify the problem and that's not a bad thing to do but the problem is simple enough that we actually don't need to do anything we can very much in my opinion Brute Force this problem you might not consider it a Brute Force solution but just because our solution is not going to be inefficient in my opinion doesn't mean it's not like a Brute Force because we are going to think of it in this way for every digit we can kind of build you can think of it like the decision tree that we usually make or even like a state machine if you are familiar with those basically we will for every single digit any digit can be the starting point we can start at one two three four five Etc I won't draw all of this out because it's going to be pretty big but one it can go to the eight it can go to the six cool so let's write that down eight and six each of these will have something like that to can go to seven and nine and we could of course fill in the rest of these and you kind of will need to solve the problem at least with this solution I'll show you but I'll also show you the approach that takes advantage of the symmetry of this problem five of course can't really go anywhere and I won't fill out the rest of this but basically for every number there is a mapping of the other numbers it can land on so what we are going to do is we are going to for every digit we're going to count the number of ways we could land on this digit like as we build that decision true you can imagine it's going to be big depending on what our n value is and we obviously want to count how many phone numbers we could create with that in terms of like the sequence or an individual sequence you can think of like the phone number one and then maybe the one goes to the eight and then the eight goes to the three this is one possible sequence maybe another sequence would have been instead of three from eight we actually end up going back to one but mainly what we want to know is how many ways could we land on each number at the end for example I think four will lead us to three as well and to get to four maybe we started at 9 or something like that so maybe there's two different ways we ended up getting to three we want to keep that in mind so that's why I'm having this uh data structure we can use an array or a hashmap but basically for each number we want to know how many ways can we get to that last digit and initially since we are starting with just a single digit any of these can be the starting point which is also the last digit so far so like for how many ones do we have a single so far how many twos do we have a single for all of these of course I'm not drawing out all 10 digits cuz I just want to show you the intuition of this we will code up the entire solution of course though now we want to know how many ways can we land on one if we had two digits how do you figure that out well you kind of have to think about it a little bit in reverse the question is how can we land on one which digits will take us to one basically eight will take us to one or I believe six will take us to one so far we know that six probably also has a one here and eight does as well I won't draw that out if we have two digits how many ways can we end with a one two so here we'll put a two value which is eventually going to replace this and we're going to fill these values in for every single one so how many ways can we land on two well two is here we can go from 7 to two or 9 to two the values for seven and 9 would be one if we had them filled in here which right now we don't but basically we take those one plus one add them together put two over here so that's the idea and you can imagine like at some point we might get like a bunch of random values here maybe a five here six I'm just making this up by the way four five if we get to the point where now we want to know like for the next digit now we have additional digits the next digit how many ways can we land on one we would take the value from whatever it was six and8 and then take those add them together and then we get the new value here and we're going to do that row by Row for every single value in here and we're going to do that for every single digit and by the time we get to the end what we would do is aggregate all of these together take the sum of all of these cuz Okay we had this many phone numbers that ended with a one we have this many phone numbers that ended with a two we have this many phone numbers that ended with a three etc and the number can be really big so they do tell us to mod it by this number so that's pretty much all you need to know to solve this problem now in terms of time complexity since we are iterating over this guy it's going to be 10 how many times are we going to have to iterate over this whole thing n times one for each digit so overall time complexity is just going to be Big O of n space complexity is just going to be Big O of 10 which is constant so not a lot of extra space needed for this problem now let's code this up so there is one case that I'm going to explicitly handle because it makes just coding this up easier if n is equal to 1 we're just going to immediately return 10 and the reason is because when n is one we actually include the middle which was five in like the phone numbers but every other phone number is never going to include five if it's ever longer than one digit we will never be able to include five because five is like a dead end we can't go anywhere from five next I'm going to declare this guy which is just going to be 10 to the power of 9 + just going to be 10 to the power of 9 + just going to be 10 to the power of 9 + 7 and now here's the part where I'm going to represent the jumps this is like our state machine you can think of it as for zero I guess I will open up the side panel just to make it very clear I won't go through all these but zero over here can go to four and six so we're going to map it to this and when I say zero I'm saying that because this is index zero one can go to I believe 8 and six so let's have that here and I'm just going to copy and paste the rest of them you probably don't want me to type all of these out so let me do that now and notice here that the five just has an empty list because it does not map to anything okay now to do the implementation we are going to initialize an array I'm going to call it DP but it doesn't really matter this is technically dynamic programming though we didn't really talk about it in the drawing explanation because I don't think like the recursive solution is really that helpful for understanding this here I'm going to have an array of length 10 it's going to be initialized to all ones remember from the drawing explanation that represents how many ways we can land on each digit so I will leave a quick comment ways to land on digit I or I guess I digit would be probably uh more descriptive now we just need to fill in the rest of the digits so that's what the outer loop here is going to be maybe I shouldn't use I because I just uh used it in the comment above so I'll put an underscore here but for underscore in range n we're actually going to do n minus one because the first digit was free every single one of these could be like a starting point theoretically even though we know five does not go anywhere and this empty list will actually handle that so here we're going to do n minus one we just need to fill in the rest of the digits except the first one now we are going to declare a temporary array I'm going to call it next DP it's going to be initially all zeroed out and we're doing this because we don't want to overwrite this array before we end up getting to use like the original values from that array okay now we are going to go digit by digit so we're going to go for n in range 10 n is going to represent which digit we are currently at so for this nth digit instead of calculating the number of ways we can land on this digit let's use this digit to map to what other spots we can land on so like this jumps at index n and for these jumps let's Loop over them because then for J in jumps we can compute the number of ways we can land on this digit so we can say that next DP at index J is going to be equal to next DP at index J plus DP at index n what does this mean remember DP of n is the number of ways we could land on like the nth digit and now from the nth digit we are allowed to jump to this spot so we're just taking from here adding it to here because if we could land on N this many different ways then we can definitely land on J that many ways as well like uh looking at the example here we know that zero can land on four and six so if Zer can land on four x many ways then we should add that x to the count of four and that's kind of what we're doing here I know that like codewise this does look a bit different than how we talked about it in the drawing explanation I think that's just kind of the nature of the way like these jumps work and the way to code this up more easily is to kind of take advantage of these we're nearly done the last thing we have to do is if we have next DP we definitely don't want to forget to assign it to the original DP before we go to the next iteration of the loop that's more or less the entire code now we can get away with doing this in Python the last thing we just need to do now is just take the sum of DP and then mod it by mod and we can get away with this in Python but the reason I wrote this line out fully is because in most languages you will not be able to do that most languages are not like python they don't have arbitrarily large integers so here I'm going to take this put it in parentheses and add the mod here and when we calculate this could theoretically overflow in other languages so a better way to do this would be to have like a result variable here initially it's zero then for uh let's say n in DP uh take result set it to result plus n and then mod that as well and then we can just go ahead here and return result so this is pretty much the entire code let's run it to make sure that it works and as you can see on the left yes it does okay so here is actually a slightly different approach and this one takes advantage of the symmetry of like the problem statement though I will say this is not necessarily more efficient I mean it technically is cuz we have like a smaller array here that we're managing but I wanted to just briefly go over some of the intuition of this my naming was a bit different from the way leak code explained it so I did kind of add these letters here ABCD that's how Elite code was explaining it which is why I have it but I wanted to just quickly show you this we have actually groups when I talked about the diagonals and how they are pretty much identical what I meant is that here we have four diagonals right and each diagonal can move to what I call the crosses which is like the top bottom and left and right so from four different diagonals we can land on eight different spots half of them will be the top and bottom and the other half will be the left and right now from the bottom it's a pretty simple one we can only land on the left or the right we basically are putting these cells and forming groups with them the diagonals go into one group because there is symmetry between them you might think isn't there symmetry with the top bottom as well as the left and right why can't we put those in one single group and that's because the top and the bottom they can move to diagonals each one can go to a diagonal but the left and right are unique they also go to diagonals but they can also move to the bottom cell they're the only ones that can move to that zero so that's what's unique for these ones we just take this information of course the middle one can't move anywhere so I have that here as well but we basically take this information and do a similar thing that we were doing earlier just without all the looping because we can just form formulas with these now cuz we only have four of them we probably could have done this as well with the other 10 but it would be hard to kind of write out 10 formulas even these four formulas were kind of annoying to write out but I won't go like super in-depth into this I won't go like super in-depth into this I won't go like super in-depth into this I think honestly Elite code's code might have actually been a bit cleaner because they did not have an array here they actually just used four variables so I'll actually just copy and paste that here in case you're wondering why they did this all in one line cuz it does look like a little less readable it's because of the same reason I kind of did these here the same reason I created a temporary array because you don't want to change one of these before you get a chance to change all of the other ones so that's why leak code has all of these in one line assignment if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
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
455
happy New Year everybody uh all right I mean I'm in New York technically it's a little bit early there's still like two three hours for the actual New Year's but still it's the do that counts and either way probably you are actually having a happy New Year so have okay uh this is day one of the year uh of January the Cod daily challenge hit the like button hit the Subscribe button join my Discord and let's do problems together this year uh there's also um the weekly problem which I will do afterwards so we'll but that'll be in another video I guess anyway let's get to it 455 assigned cookie this is a easy one to start of the Year assume you what is this for sentence but that's pretty uh I don't know it's nice assume you are an awesome parent and want to give your children some cookies but you should give each child at most one cookie your child eye has a greated factor G ofi where which is the minimum size of a cookie that the child will be content with and each cookie J has size s subj if s subj is equal G subj we can assign the cookie your goes to maximum so it's kind of a sort of um a matching problem but of course this one is a very um uh a standard one to a degree where it is just um greedy right and you kind of prove greedy by in this particular problem um with the exchange um argument I keep saying exchange argument I don't know if I'm using it quite correctly but the idea is that let's say you know use greedy right um and I know that this is easy and in a way it is easy only because your intuition is greedy and your intuition in this case is correct um I think the number one maybe number two uh top two say Pro question that I always get asked and to be honest this is something that I struggle with as well is how do you know the greedy solution is correct right and yeah when it's correct it's easy but it's not you're like well that was not right and of course in other in some other problems there are multiple Dimensions to be greedy on and even with a greedy solution uh it might not be the way that you think greedy would work anyway so this is where proofs are helpful and proofs are not always easy for greedy problems in general there is like this uh you have to prove the sub uh was it sub Metroid thing uh and greediness and um and not a sub problem I've been doing too many dynic dynamic programming problems but just like you know a smaller uh um incremental State builds to uh or I think the way that they always say just like logo Optima builds to Global Optima right so eh that's like a very specific thing anyway the way that I at least I gone over a little bit to begin with is this idea of an exchange uh argument right and this say exchange argument is kind of uh easy to remember because it is just in the name so basically the idea is that okay so let's say you uh you sort and you greed give everyone the next biggest cookie that can fit right so in this case you have 3 2 1 and you have one let's say I sorted reverse order right for which one is so G is the chosen okay yeah right uh and then the idea here is that um this is not a great example but let's change the bottom to say 2 one right so one possible matching of course is just this 2 one and this is example two so but also it's just very intuitive or easy to see why this is the optimal pairing right um and the exchange argument is basically saying that if we exchange this we can if you exchange in general any two elements or something like this I mean it the actual details depend on the problem but for this particular problem if you change two elements you can only get to um a worst case and you could and it kind of is this thing that builds uh what is that called man I don't remember anything today or this year uh well I guess depend on what year but induc uh induction is what I was going to say uh but yeah if you can if you could show that it doesn't work in this case then you can or if you show that The Exchange argument um that you cannot exchange then and um uh then in this way you can use induction to kind of prove the rest kind of right um of course in a lot of these cases The Exchange argument is going to be uh the way that I do it anyway they're probably you know smer more mathematical way of doing it but the way that I do it is just really exhaustive and this is for any given let's say XY or maybe a b and then s is just some c and d in a more General case and let's say that in this case a is greater than C or um yeah a is greater than b a is greater than C it has to or equal to it has to for it to match of course and B is greater than equal to D then in this case um this case let's say you exchanged it to U AB uh DC right um then in this case of course um oh I missed a thing where C is greater than or equal to d right um because that just say that we have it right but in this case well now you can kind of think about all the possible scenarios right so the one scenario is that a is greater than equal to d right let's let me just label this as scenario one um and B is greater than is equal to C and the other things don't really matter you have two matches right and then scenario two is similar but you have um cuz D is smaller than C right so this thing is still true um then now a will always be greater than or equal to D in this case but there's a chance where B is not uh I don't know how I don't know if that's quite the emoji for it but you get the idea right B is actually less than c um just due to how you know like and you can plug in real numbers so there's two scenarios in this case there's one match so now you're going from two guaranteed match two matches I guess maybe it's here actually sorry two matches to either uh same optimality or even worse so therefore by The Exchange argument you always want the greedy Solution that's kind of the idea about it I mean you can actually do this a little bit more rigorously but that's basically the template of for me anyway of like okay so this is why greedy Works um the other thing is that and for this particular case it is just that um yeah uh it just proves that um if you H have something that Strays from this and of course uh if you sort everything in a we were sort my mouse is a little bit weird sorry hang on my key no my mouse pads a little bit but yeah you can show that you know if you sort this then this will always be true for another like you know uh maybe I should have used different rable names but yeah for but for more rbl on G or S you can kind of pro this in a you know you can do it for every pair and of course you know all the things look the same and therefore you can prove that this is you know optimal just by uh almost exhaustion I guess I'm always exhausted anyway that's basically the idea that's a very long way uh I just want to kind of give you the tools a little bit I mean just I don't think this like I said you know this is a quotequote Yeezy and a lot of you probably already know how to do it wouldn't be surprised so um so the code is actually not that interesting I don't think maybe um and then now uh count isal Z right or CIS isal Z maybe I don't know so now for or maybe uh okay so this is kind of like the you know the two finger algorithm so maybe I have gi is Si is equal zero while GI is less than link of G and Si is L of s and you need both of these to be you know to have an item um then now um H so now so the other thing about this is that the beauty is that um I guess this is kind of part of the proof as well is that um if you have a g that is bigger than the biggest s the biggest G is bigger than biggest s then by definition no cookie is going to fit that person anyway right because if you can already consume the biggest cookie then or if you there no cookies for it to consume uh you know yeah just the size of the cookie I guess that's what I was looking okay fine right so basically if G of GI is greater than S of Si then what happens that means that no cookie for GI so then we do GI increment by one and then we continue otherwise um then now this means that g of GI is so that means that this cookie is good so then we eat the cookie oops and increment and that's pretty much it uh I mean this is what I get a mistake 17 1371 day streak but yeah I mean like I said this code and even this idea is not very hard but you know I just want to give you a little bit of a basis a little bit of a template for the code uh all right um this is going to be n log end time of course because of the Sorting um yeah or you want be more precise uh where G is the length of G is n the length of s is m then you have n log n plus M log M um you can also maybe bound that a little bit if you like for example um you can maybe even bound that by like n log M or something like this using a heap depending on what n and M is but not going to and the other way around as well but uh but in a simple case in this particular code let's just say there going to be nlog M plus M log M uh and of course uh this is going to be n plus m space because disordering does require extra space uh I mean I wrote the way I wrote is you know whatever but anyway that's all I have for this one happy New Year everybody let's do this year together uh I don't know if I'm going to do the entire year but I'm going to do at least for a little bit so uh we'll see how long this streak ends up going ends mental health I'll see youall later and take care bye-bye
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
315
hello everyone welcome to another short video on solving elite code problem with ipl in the last video that you can find links to in the description we solve this problem 1365. how many numbers are smaller than the current number and i noticed there's this similar question step which well shows similar questions and this one is supposedly it's a heart problem 315 count of smaller numbers after self and it's very similar to the one we just solved and so i thought that we could give it a go even though we have been solving the easy problems first and so what this says in here is that sorry about that we have this array of numbers and we have to return a new array of counts and this array of counts is defined in such a way that each position of the counts array gives the amount of numbers that are smaller than the corresponding number to the right why can't i speak english what do basically what we are going to do is we are going to traverse this array of numbers and for each number we look at its rights and count the numbers that are smaller that's what i want to say so here looking at the five so we are at the five we look to its right there's the two the six and the one so only two numbers here are smaller than five and that's why there's a two there and for example if we look at the six to its right there's only one number smaller than six and that's why there's a one in here so this is what we want to do and like i said it's similar to the other problem we solve and for the other problem we have this vector let's do it so five two six one and for the other problem the solution was this we have an outer product and the key here is the other product doing all the comparisons for us now if we look at for example this row looks at six at the number six because it's the third row so it's the third element of v looks at the six and checks for which numbers six is greater than the elements of v and we see here this corresponds to the five this corresponds to the number two and this corresponds to the number one but the problem is these numbers these ones they correspond to numbers that are to the left of six so we do not want to take them into account and so what we can do is build a boolean mask to remove these that we do not care about and this boolean mask with this pattern this is really easy to create and it's something i've been using a lot lately and it's also with an outer product with one of the comparisons so you just pick the correct one for your situation and then you do an iota with the tally of v and you can see here that this builds a triangular matrix so there's ones in here above the diagonal and we can take this and we can multiply it with this matrix over here and what this will do this multiplication here or if you prefer you can make it a logical end what this does here is it only allows for numbers that are it only finds occurrences of numbers that are greater than and sorry n that are also to the right of the actual numbers so we can do this and we can see that the ones over here these were like this they disappeared because they were masked out by this and then what we do is we sum it across the rows again and we can see here two one zero this is the solution for this and the other test cases here really are really not that good so but we can show it works so if we're in this again there's the zero that we would expect so we can see here how we took a fairly simple solution that was this outer product in this summation and then we just patched it fixed it so that we only took into account the actual intermediate results that we care about so we can look at this other product as computing a bunch of intermediate results and then we use a boolean mask to filter out the ones that we do not care about so this is a fairly common pattern in or at least i find it a fairly common pattern in apl so thanks a lot for watching as per usual you can comment your alternative solutions or you can make pull requests or open issues whatever you prefer on the github repo that i'm using to list all of the solutions that everyone shares and other than that i'll i will see you in the next video so bye
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
1,881
hello everyone welcome to coderscamp so in this video we are going to cover this problem check if word equals summation of two words and it is one of the easy category problem which is asked in lead click on test 243 here the input given is three strings the first word second word and the target and we have to return if the first word plus second word is equal to target so here they have given us each character in the word will be assigned with the integer like a starts with 0 and goes till 25 is it and if we add the values of first word and second word which should be equal to the target in that case we have to return true otherwise we have to return false so let's consider the first example given acb cba and cdb so if you convert the first word acb then it is going to take 0 to 1 and as the 0s in the front can be ignored and the number is 21 and then the next character or the next word cba can be represented as 210 and the target can be represented as 231 and if you add 21 and 210 it is going to be 231 again so our output is going to be true so first let me write a method which converts a string to a number let me name it convert and it takes a string as a parameter and returns an integer value as a result so i am declaring a variable integer variable result and i am going to iterate my given string so inside that i'm gonna calculate my result so which is nothing but we are going to convert each character to a number first so this will actually convert each character to a number so every time we convert it to a number we are going to append it to the last of the result so which is nothing but result plus result into 10 so it will multiply a 10 and add this number at the end so finally the result will have us the complete converted number so we are returning the result so now in main method we are going to call this function to calculate the number form of these three words so directly i am going to return convert of first word plus convert of second word is equal to convert of target word so it simply compares and return the value accordingly so let us run and try so yes let's submit yes the solution is accepted hope i made it clear and it runs in 0 milliseconds so thanks for watching the video hope you like this video if you like the video hit like subscribe and let me know in comments thank you
Maximum Value after Insertion
closest-subsequence-sum
You are given a very large integer `n`, represented as a string,​​​​​​ and an integer digit `x`. The digits in `n` and the digit `x` are in the **inclusive** range `[1, 9]`, and `n` may represent a **negative** number. You want to **maximize** `n`**'s numerical value** by inserting `x` anywhere in the decimal representation of `n`​​​​​​. You **cannot** insert `x` to the left of the negative sign. * For example, if `n = 73` and `x = 6`, it would be best to insert it between `7` and `3`, making `n = 763`. * If `n = -55` and `x = 2`, it would be best to insert it before the first `5`, making `n = -255`. Return _a string representing the **maximum** value of_ `n`_​​​​​​ after the insertion_. **Example 1:** **Input:** n = "99 ", x = 9 **Output:** "999 " **Explanation:** The result is the same regardless of where you insert 9. **Example 2:** **Input:** n = "-13 ", x = 2 **Output:** "-123 " **Explanation:** You can make n one of {-213, -123, -132}, and the largest of those three is -123. **Constraints:** * `1 <= n.length <= 105` * `1 <= x <= 9` * The digits in `n`​​​ are in the range `[1, 9]`. * `n` is a valid representation of an integer. * In the case of a negative `n`,​​​​​​ it will begin with `'-'`.
The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary search to get the nearest possible value to goal - x in the first part.
Array,Two Pointers,Dynamic Programming,Bit Manipulation,Bitmask
Hard
2108,2162
460
Welcome back to the stylish YouTube channel, so today's problem is this question of 460 hard level, so in the description of our question we have been told that we have to design and implement data structure for list frequently used L of UKG, so for this They have given us a class, Rakhi F U K G class, so there will be a constructor inside this class, okay, inside that we will have parameter called capacity, so the meaning of capacity will be this, which is our raw memory, its size will be okay with that. They have given us a function, gate, there will be a parameter in it which will be that if the value of our key is in our memory, then we have to return the value of that key in the case, if it is not in our memory then it should be returned. In this case, we have to return -1, okay, along with a In this case, we have to return -1, okay, along with a In this case, we have to return -1, okay, along with a function and by putting it will have get and, it will have key and value, so if we already have that key in our cache memory, then we have to update it, if not. We have to insert it and also when we put the value in our cache, if it is equal to the capacity count of our cache memory, then in that case we will have to check the list frequency of it and we will have to remove the value. We will have to remove it, we will have to insert it and in this case, if the list frequency of both our values ​​is same then list frequency of both our values ​​is same then list frequency of both our values ​​is same then we will have to see it in the case, we have to keep the list of recently used keys and the rest which is the first one. It must have occurred to us, we have to remove the value. Okay, if we develop this course, the time complexity of the get and put functions should be average, that is, we should work on constant time and complexity, then this is our The description of this question was, if we look at its solution, then for the solution I have created three Hash maps here, okay, the first will be my catch, okay, I will store it inside the sketch, I will store whatever my key and value is, I will store it okay. I have the key and count inside this, the key that I have is okay and the count of that will be the count of how I have done it, how many times has it been called, okay, the third one is in this, I have It will be that I have a count, okay, there should be a link list running with the count, okay, this link list will tell me how many updates have been inserted in this count, okay, it will keep track of that thing. So let's look at my question, what will I have in the question, what will be the capacity, which I will install inside the cap, which I have, okay and I will create a variable minimum, what will it do for me, which will count the minimum values, okay this. The minimum is going on, we have it ok, what will be the initial, it will be -1, ok now what will be the initial, it will be -1, ok now I will put 1 and 1, ok, I came, the value of van was van, so it was inserted that it has to be updated in the account also, ok van. And its count will be Van only, okay, it will come in frequency because I know how much will be its account, then its value will be Van, okay, now after this, what will come to me to be put, okay, and when I got Van, this is the minimum. There will be a number, what will I do with it, I will update it from the van, okay, now after this it will be passed, you came, okay, I have inserted you here, okay, how much did you count, van happened, okay here. If there is a pay van count, then I will add it inside it is also okay on 2nd, it is added, that is, what will I do after that, here I will update the value of min, how much will I do, will I set the van, if there is already a van, then updating is not shown. Anything is ok now I will get it ok I will get it then at the gate I will check if I have the value of van inside if yes then I will return the value in it if not then I will get the value then I will just get the value what is the value van then From here I will return 1, okay and the account I have will be increased by WAN. Okay, now if its account is increased then I have to update this value. In my frequency, it will be WAN. Okay here, this van is mine, so the van will go here, it will be removed from here, okay now, if we go to that second, what comes second, we have a statement, the put person, then let's get the put done, okay three and three. We will get it added but if you look at the size here, what is the size, if the size I have is more than the capacity, then I have to remove the equal, I will remove the one which is my minimum, which is my list frequency unit or the most recent list unit, I will remove the one. Okay, so look at this, which one has the lowest frequency? I have the lowest frequency. I have a van, so sorry for you, so I will remove the value of 2 from here. Okay, remove it from this. Remove it from this. Okay, this is also removed from this. It has been removed from here also and it will be removed from here too. This value has been removed and what was the minimum that I had with me, what was the van. Okay, I have removed the van. Now see what is the count of the value of this van that I had. What will I do if it goes to zero? I will increase this van channel. Fix that when I have that list that I have min if that min's values ​​that I min if that min's values ​​that I min if that min's values ​​that I have here inside that. The count is equal to its value, that is, the count that came to me is fine, the count that is the value, if I do min plus van, if it is equal to the end, which is the frequency one, which is it, if it becomes null, then in that case, I will return it, okay, so I have returned it is okay, updated the value from here, now let's go, we have to get you, do we have it in the memory, you are not there, earlier we had removed it, what will happen from here. -1 is ok, 3 is there, what will happen from here. -1 is ok, 3 is there, what will happen from here. -1 is ok, 3 is there, we have three, so what will we do, we will return 3 from here, returned it, now we have to do this, we have to increase the end count of the same, ok, I had not added three here, so You do it, okay 3 was 1, then what will be its pick count, it will increase by 2. Okay, so how much A will go here, we have A okay, it will be removed from here, now what will we get after this 4 And 4 will come, okay, get four and four inserted, now check in this, whose frequency is less in my count, see, the frequency is equal to both of them, you are the count, okay, so we will see who in this. Our C value is the one that happened first, we will remove the recent one, we will check for that, okay, so first of all, we will check for that, here you will go to the one, okay, we will come out from the minimum, okay, if you came, then you check in this. Which one got to me first, then it is going on in this order, meaning first van came, then three came, so we will remove the van, okay, then we will remove the van, it will be removed from here, okay, it will be removed from here also. Will it be removed? What we have at this frequency, if we make this frequency equal to our meaning count, then this equal will be inserted inside it. Four count van will go here inside the van. Our four is fine and this will be the minimum count. What will happen, this van will be ok because we have the minimum, what is the van, ok now then what will we do, get the van, what will come here - 1 will come, ok van, what will come here - 1 will come, ok van, what will come here - 1 will come, ok because we do not have the van, because it was removed. First okay brother, we forgot to remove from here, then we will get three, if there is three, then update three here, okay, let its frequency be bigger than here, what will happen to you, it will become three, okay in the account with frequency. Go three, write here, our 3 will be of 3, from here it will be brick, okay, now after that we will go to 4, check 4, is four, we have a, 4, take return brother, so four, we will increase its frequency here. Will give from the van, you are ok, four will come to our place here, will be replaced from here, ok, so these are ours which will be from here, these will be our answer, ok, we have to do this, so let's write the variables we will need #map ok This will be our kernel so #map ok This will be our kernel so #map ok This will be our kernel so wait will be the name of the face which will be our pass which will do for us wait map and along with this we will have variables capacity is ok new hashmap ok now with this we have that account and also account Our account will be created The value in our frequency map will be WAN, okay, so let us get it set, so the frequency gender is set, okay, so all our things, we will check whether we have that value. The key that we got is the same or not. If our key count does not contain the contents then return it to case -1. Okay, okay, now what after this? Now our key is inside it, so now we have to What will we have to do in this, we will have to increase the frequency in this also, what frequency should we increase in that also, so let's work on it, okay, so we will take it out first, where will the brown come from in the count, which is our key count. Tell us that the value of count dot get will go to account three. Now after this we will check what we will check. We will get its account inserted inside ours. So, okay, then the value of account dot key and plus van will go to the shirt. What should we do which is our Account is the value, meaning we have to remove the account that we have from the frequency one. Okay, so let's remove it. In our frequency map, we will first get the count. Okay, now we will remove it from it. We will remove the key. Do it, remove it from brother, okay, now after this we have to check that if our account is not minimum, if it is equal to the minimum number and if the link list of that account is in our frequency map. If its size is zero then it is okay to increase the minimum number. So if mine is then min value is min equal then what will you become equal will mine be equal to the account which is the one with count which is the link list, what is its size? It is not zero, it is okay, we have also checked it here, it is okay to increase the minimum account in it has increased, now what do we do after this, we have to add it inside the frequency map, then if we have to add it inside your frequency, then we have to First you have to check if this value is not there in your frequency, that is, it is not there, then we have to insert it in it, so if my fickens sip dot contents are correct, which is the count of contents plus van, if this contents. If he doesn't do it then what should he do in the case, then add a new one from here, frequency map dot food, okay, what will the put do, it will put, our count plus van value is set, after that we will return it here, work. What should be our put method? We have to have the value inside it. If we already have the value then what do we have to do with it? If it is not there then we have to insert it. Okay and along with this we also have to check the capacity. Okay. So our first check will be this if our cap is given if it is equal to zero then it means that we have to add the value inside it, so what do we do directly from here, okay now what do we have to do if We have that value, if we already have it, then what do we have to do with it? If we have to update it, then if I have the catchy memory, okay, let's say get sorry, which of the contents do we have, then what do we do in it? We will update it. Okay, so how will it go with the put? We will send the value inside the key. Okay, our value has been updated, but what do we have to do? Now we have to update the frequency also, so for that we will go to different courts. It is above, we directly pass it through our gate method, okay, so here I pass it directly inside the gate, the code with our frequency of updation is happening above, okay, it will be updated from there and From here we will do the return. Okay, this was our case in which we have to update. Now whatever case comes to us, we do not have that value, that is, if we have to get it inserted, then we will get it inserted. We will have to check that if Whatever insert we get, it is okay, we have to check whether its capacity is more or not, okay, so if in this case, what is its required size, if it is equal to our capacity, then what do we have to do in that case? We have to find out the minimum number in the list and get it removed. Okay, if we find it, then the ID will be the same as the minimum frequency. So, what is inside the frequency? Out of the map of frequencies, which one will we gate? The one in the position is okay. Amin, what do we have in the link list? Which variable will be inside the link list which is in the first place? Okay, so let's go to the position, then we have to remove the iterator. Okay, remove this one. The smallest frequency is what we have, I am in sequence, okay, this is one of these, we have to do this from the accounts and also from Kshem, so do the accounts account dot remove, then do it here, min frequency is okay, it has been removed from the account, which one do you have to do? So in catch a dot remove the frequency is ok. What is our frequency removed? Now what do we have to do? Now we have to get it inserted. Okay, so we will get the insert done here outside the if. Okay, if we have the capacity, if it is correct then we have to directly insert it. If there is more then only we have to remove it, then we get it inserted here, then inside the raw, we directly put these six dots, what is the food and the value is OK, the end value has been added, now what we have to do is to increase its count also. So whatever count we have to put it in this also, okay, what will we put, what will be the end value, van, okay, the value is van, now we have to add it in the frequency map also, so who will dot our frequency map, if van At the position which we have already defined, first of all we will do what will happen to us, it will become our van. Okay, so this was our code, so let's run it, now let's run it and see the syntax error, so it is not a syntax issue, it is okay. There is a syntax issue, I had said that it is not included in the account, only one account is fine, our code has been successfully run, so let's submit it and our code has also been successfully submitted, so in today's video, so much. If you liked our video, then like the video. If you have not subscribed the channel, then subscribe the channel. Such videos keep coming, then see you with another video. Till then Bye
LFU Cache
lfu-cache
Design and implement a data structure for a [Least Frequently Used (LFU)](https://en.wikipedia.org/wiki/Least_frequently_used) cache. Implement the `LFUCache` class: * `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure. * `int get(int key)` Gets the value of the `key` if the `key` exists in the cache. Otherwise, returns `-1`. * `void put(int key, int value)` Update the value of the `key` if present, or inserts the `key` if not already present. When the cache reaches its `capacity`, it should invalidate and remove the **least frequently used** key before inserting a new item. For this problem, when there is a **tie** (i.e., two or more keys with the same frequency), the **least recently used** `key` would be invalidated. To determine the least frequently used key, a **use counter** is maintained for each key in the cache. The key with the smallest **use counter** is the least frequently used key. When a key is first inserted into the cache, its **use counter** is set to `1` (due to the `put` operation). The **use counter** for a key in the cache is incremented either a `get` or `put` operation is called on it. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LFUCache ", "put ", "put ", "get ", "put ", "get ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[3\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, 3, null, -1, 3, 4\] **Explanation** // cnt(x) = the use counter for key x // cache=\[\] will show the last used order for tiebreakers (leftmost element is most recent) LFUCache lfu = new LFUCache(2); lfu.put(1, 1); // cache=\[1,\_\], cnt(1)=1 lfu.put(2, 2); // cache=\[2,1\], cnt(2)=1, cnt(1)=1 lfu.get(1); // return 1 // cache=\[1,2\], cnt(2)=1, cnt(1)=2 lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2. // cache=\[3,1\], cnt(3)=1, cnt(1)=2 lfu.get(2); // return -1 (not found) lfu.get(3); // return 3 // cache=\[3,1\], cnt(3)=2, cnt(1)=2 lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1. // cache=\[4,3\], cnt(4)=1, cnt(3)=2 lfu.get(1); // return -1 (not found) lfu.get(3); // return 3 // cache=\[3,4\], cnt(4)=1, cnt(3)=3 lfu.get(4); // return 4 // cache=\[4,3\], cnt(4)=2, cnt(3)=3 **Constraints:** * `1 <= capacity <= 104` * `0 <= key <= 105` * `0 <= value <= 109` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Hard
146,588
98
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 98 validate binary search tree given the root of a binary tree determine if it is a valid binary search tree is defined as follows the left subtree of a node contains only nodes with keys less than the nodes key the right subtree of a node contains only nodes with keys greater than the nodes key and both the left and right subtrees must also be binary search trees so let's look at an example is this tree here a binary search tree well typically we you know want to check these three conditions so for this node 5 here which is our root of our tree is its value greater than all of the nodes in the left subtree yes because it's greater than obviously one here so that first condition is met is the right subtree is it greater than all of the nodes here uh sorry less than all of the nodes in the right subtree no because we can see that five is greater than four which is not allowed and it's also greater than three but it's less than six so these two nodes here violate this second property and also remember that all of its children must also be valid binary search trees so if we looked at this tree here this is a valid binary search tree because the node four is greater than three and it's also less than six so even though this subtree is valid because five is greater than four and three here this is not a valid binary search tree so all three of these conditions must be met and that's the reason why this tree is not a valid binary search tree so for the purposes of this exercise a node that is a leaf is a valid binary search tree because technically it doesn't have any children so this part is fine you know an empty binary search tree is a binary search tree and because the nodes are empty then this part also holds true so a leaf is actually a valid binary search tree so the way that we do this in a dfs manner and we're gonna go all the way down to the leaves and we're gonna ask ourselves okay so obviously we know that a node by itself is a valid binary search tree if it's a leaf so that means that three is a valid binary search tree and six is a valid binary search tree so now we go up to 4 and what we want to do here is pass in the largest value that we saw coming from you know this left side which was 3 and also the smallest value we saw which was also three and on this side what is the largest value we saw six and the smallest value we saw was also six so now at the four we need to ask ourselves these three questions right is three a binary search is the left side of binary search tree it is so left is a binary search tree is right a binary search tree it is and also is our value four is it greater than the largest value we saw on the left so is it greater than 3 and is it also less than the smallest value on the left so is this hold true it does so that means this here which we verified earlier is a valid binary search tree because it matches all the conditions now what we want to do when we return to the next level is we're going to return that you know we had a valid binary search tree from the right side here of this five so we would return true that the right side is a valid binary search tree and we also want to return the smallest value that we've seen uh here so the smallest value is going to be three and the largest value we've seen is six then we want to do the same thing for this one so this one is a valid binary search tree so from the to the five we want to return true that we have a binary search tree that's valid the largest value the sorry the smallest value we've seen and the largest value in that path so what we want to do now is at five we need to check okay is the left side a valid tree binary search tree sorry yes is the right side of allied binary search tree yes now we need to check whether or not our conditions for the tree hold true so what is the largest value we saw in the left subtree one is five greater than that yes so that part holds true but is five also less than the smallest value we saw on the right tree three no this value is not this part doesn't hold true therefore this entire thing is not a valid binary search tree because we have violated the um the right subtree requirement so that's how we want to do it we're going to do it in a bottom up manner and basically pass up whether or not our you know previous uh you know whichever side we were going from was a valid binary search tree the smallest value we've seen and the largest value and then we need to make these checks so let's actually go to the code editor and see how we might write this out because there's a few kind of edge cases that we need to consider namely what happens if one side is defined but the other side is actually a null node right that presents a little bit of a challenge for us but no worries we're going to solve it let's go to the code editor and see how we now need to validate our binary search tree and we have to write the code to do that so remember that we want to use some sort of function which is going to tell us whether or not a binary search tree is valid and we needed some extra information to make that decision namely whether or not the node that we're asking for is a valid binary search tree so we're going to get either true or false then we're also going to get the min value that we need in order to make the comparison of whether or not you know these conditions are met at a given node and we also need the max value to make that same comparison for that right subtree so we're going to have some helper function which returns this tuple and when we call this on the root the return will be whether or not the actual entire tree is a binary search tree but recall that this is going to be a tuple and we're only really interested in this first value for the actual result here so what we want to do is we're simply going to return so we're going to say return self.bst helper we're going to call it self.bst helper we're going to call it self.bst helper we're going to call it on the root and remember that it returns a tuple and the first element is going to be whether or not it's actually a valid binary search tree so we're just going to return that first element here which is that index zero now for the fun part we actually get to code the bst helper function so we're going to say def bst helper and we're going to take in a node now what happens if our node is null obviously a null node is not a valid binary search tree so we want to return false here so we're going to say if not node we want to say return false float infinity as the minimum value float negative infinity as the maximum value and this part doesn't really matter because we're going to handle the case where we actually have null nodes separately we just need to return something because if we hit a node that's null and we don't return anything it's going to mess ourselves up we simply need to return stuff we're not actually going to use these values so what we want to do is just return something so our function doesn't blow up but the values that we choose here don't really matter because we'll handle the case where a node does not actually have a left or a right child so remember that we said that even though an empty you know a null node is not a valid binary search tree all leaf nodes are valid binary search trees because they don't have any children so technically they are valid binary search trees so let's handle the case where we're actually at a note at a leaf node and the way that we check for leaf node remember is that if a node does not have a left or a right subtree left and right subtrees both have to be empty so we're going to say if not node.left and not node.left and not node.left and not uh node.right uh node.right uh node.right basically we are at a leaf so leaves are always valid binary search trees so we're going to return true and we're going to return so what is the smallest value that we've seen so far obviously there's only one value in this binary search tree which is the node's value so we're going to turn node.val as value so we're going to turn node.val as value so we're going to turn node.val as the minimum value that we've seen and the maximum value we've seen similar to the minimum we've only seen one value so therefore it's just whatever the node.val is node.val is node.val is now if we're not at a leaf node we need to actually process um you know the left subtree the right subtree and then make a decision of whether or not we have a valid binary search tree using the information from the left and the right and our current nodes value so we're doing this in essentially a post order traversal we are going to the left subtree then the right subtree and then processing that information alongside with the parent so remember that our function returns whether or not a given subtree or i guess a tree is a valid binary search tree it returns the minimum value we've seen on that path and then the maximum value that we've seen in that tree um if we go you know to the left or to the right respectively so let's define those functions those variables sorry so we say left is bst and then the left min whoops the left minimum the left maximum is going to equal to self dot bst oops helper so we're going to call it on node.right node.right node.right no dot left sorry geez what is going on with me today no dot left so we're gonna explore the left subtree and check whether or not it's a valid binary search tree and we need to do the same for the right so we're gonna say r is bst and we're gonna say the right minimum and the right maximum is going to be self.bst helper self.bst helper self.bst helper and we're going to call it on the right this time and now we need to do our checks so there's a few cases that we need to do here and we need to check all of them the first case is that for a given node it has both a left and a right subtree and those are both binary search trees in that case we just need to validate whether or not these two hold true and if it's true then we can return true to the next stage so we're going to say if the left is a bst and the right is a bst so that takes care of this condition and remember that we need to verify that our current nodes value is greater than all the nodes in the left which is going to be represented by lmax so if we're going to say lmax is less hey less than our current nodes value and remember that the right subtree has to be greater than the value of our current node so the smallest value in the right subtree needs to be still greater than our current nodes value so if this holds true basically this here if our node's value is greater than the left max and the right minimum which means that our node's value is greater than less than all the nodes in the right and greater than all the nodes in the left then this tree here formed by taking our current node and the two left and right children is a valid binary search tree so we can return to the next level so we're going to say return true and remember that the smallest value we've seen is going to be the l min and the largest value is going to be the r max so we return that to the next level now we handle some other cases where let's say the left is a valid binary search tree but we actually don't have a right child because it's empty for example you know say if we're at this 4 and it had a the 3 here but this 6 actually wasn't defined then it would not matter because this is still a valid binary search tree even without the six so we need to handle that case where the right child doesn't exist and we need to handle the case where the left child doesn't exist so let's do that so we're going to say else if left is a binary search tree and not node.right so the node dot right and not node.right so the node dot right and not node.right so the node dot right on our current node doesn't exist and um our current node.val um our current node.val um our current node.val is greater than the left minimum then oh sorry the left maximum apologies uh if it's greater than the left maximum then this is still a valid binary search tree just because one of the nodes is missing on the right is fine it doesn't matter as long as the left side holds up its end of the bargain which is that the left sub tree contains only nodes less than the node's key and then both the left and the right sub subtrees must be binary search trees if a tree is empty that's fine we don't have to worry about it's still allowed so in this case we can also return true we can return true and in this case the smallest value is still going to be the left minimum and the largest value is going to be node.val and the reason for going to be node.val and the reason for going to be node.val and the reason for this is remember for it to be a valid binary search tree no dot val needs to be greater than all the values in the left tree which means that the largest value of the new tree that we're forming by taking the left subtree in our current node is going to be the node.vowel because that going to be the node.vowel because that going to be the node.vowel because that right subtree is empty therefore we're not getting any sort of r min and r rmax for us to use okay now that we've done that we need to do the reverse case where node.write is the reverse case where node.write is the reverse case where node.write is defined and it's a valid binary search tree but the left is not so we're going to say else if r is vst and not node.left and this time and not node.left and this time and not node.left and this time node.vowel is going to be less than node.vowel is going to be less than node.vowel is going to be less than whatever the smallest value in the right subtree is similar to how we had up here except this time we don't have to compare with the left because the left doesn't exist in this case it's also going to be to come true so we're going to turn true we're going to return in this case node.val because this is now the node.val because this is now the node.val because this is now the smallest element in our new binary search tree because remember node.vowel search tree because remember node.vowel search tree because remember node.vowel needs to be smaller than all of the values in the right and we're basically conjoining those two and therefore no dot vowel would be the smallest element and then what is the largest element it's still going to be whatever the right max is otherwise in this case these are the three cases where we would have a valid binary search tree either the left and the right are both bsts and we have you know this condition being met or the left is a binary search tree the right node doesn't exist and this condition is met or the right is a binary search tree the left doesn't exist and this condition is met anything else is not a valid binary search tree because it invalidates one of these three invariants so therefore we can simply return false and in this case we don't really care if we're returning false we can basically return anything we want for these values because once we see a false in one part then basically the entire tree is off and we don't really care at that point we are really only concerned with trues the second we have false that's it game over the entire tree basically needs to return true for this to become true let's just run this so we make sure we haven't made any syntax errors and we should be good to go to submit so cool we are done there so what is the time and space complexity for this algorithm well like i mentioned earlier the way that we're solving this is going to be a bottom up depth first search and we're doing this in a post-order manner where we process the post-order manner where we process the post-order manner where we process the left child then the right child then the parent but that's just you know fancy way of just saying we're doing a depth first search here so to do a debt first search through this tree is going to cost big o of n time because we need to touch all of the nodes in the worst case and space complexity even though we're not actually defining any data structures here we need to take into account that we're doing a depth first search which is going to be a recursive call and we have to account for the recursive stack frames some interviewers will want to count this as big o of n space because in the worst case you could have a very slanted tree that you're given and you could end up storing the entire tree in your kind of stack space there in which case it would be big o of n if you don't want to count the stack space it's going to be big o of 1 because we're not defining any data structures here so we're going to say big o of 1 if not counting stack space right so that is going to be how you solve this problem i think this is a really good question a lot of problems on leak code are going to follow this pattern where you need to basically validate some sort of property of the binary search tree some of them require you to kind of do some summations based on uh whether or not you know a path is a binary search tree uh or something like that but this is going to be i guess like a common template and these are going to be your edge cases that you're going to want to take care of and you know make sure that you've handled all of them so that's how you solve this problem hopefully you enjoyed this video if you did please leave a like and a comment it really helps with the youtube algorithm if you want to see more content like this while you're preparing for your on-site interviews please subscribe to on-site interviews please subscribe to on-site interviews please subscribe to my channel i do a ton of videos on lead code questions and i plan to make a whole lot more so subscribe so you don't miss those otherwise thank you for watching and have a nice day
Validate Binary Search Tree
validate-binary-search-tree
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_. A **valid BST** is defined as follows: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[2,1,3\] **Output:** true **Example 2:** **Input:** root = \[5,1,4,null,null,3,6\] **Output:** false **Explanation:** The root node's value is 5 but its right child's value is 4. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,501
1,518
hey guys this is just how's everything going this is an easy problem because water bottles were given uh some full water bottles we can exchange for some uh empty bottles for full one yeah we need to return the maximum waters we can drink so we have nine here we drink them it will be nine empty one we can exchange three right three for one so we got three new full bottles and then we can drink them three and then we can change for one and drink right now this would be the same um so yeah we could just do this iteratively right just do it over and over again we drink it and we just change it so every round what do we get in every iteration we will i think we just uh set these full bottles to empty one and then uh divided by the number exchange and i'm exchange and they get the new footballs and the new empty one right so the full iteration would be update the full bottles with drink and exchange right so what we got so this was stopped when the number of full bottles and that kibby are here food bottles and empty bottles both the sum of them is smaller than exchange so even we drink them all we couldn't exchange for a new one so that's the time timing where we stop uh the iteration right so we need to keep track of the uh full bubble count equals numbers empty count equals zero right initialize to zero and while full bubble plus so the total count is enough for it in exchange we will do the exchange right so what we do first we will set the uh full bottles to empty ones right so we plus a full bottle account and then we need to update the full bottle account to the new one so equals man more empty one let me exchange and then we update a new empty one right it should be num exchange so this is it so every round we just sum up the full bottle ones right set go result equals zero we will update the result to full body account and then finally we will try the result so that's it let's try if it works 12 ah oh no ah okay i made mistakes so for a case like this we actually could drink one to exchange for one more for this case i forgot to drink right okay so the problem we should be um if there is full bottle we will drink them and update it ah i made a mistake thirteen nineteen five three oh six two yeah that's right so okay seems right submit accept it cool so that's all for this one is easy one hope it helps i'll see you next time bye
Water Bottles
total-sales-amount-by-year
There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle. The operation of drinking a full water bottle turns it into an empty bottle. Given the two integers `numBottles` and `numExchange`, return _the **maximum** number of water bottles you can drink_. **Example 1:** **Input:** numBottles = 9, numExchange = 3 **Output:** 13 **Explanation:** You can exchange 3 empty bottles to get 1 full water bottle. Number of water bottles you can drink: 9 + 3 + 1 = 13. **Example 2:** **Input:** numBottles = 15, numExchange = 4 **Output:** 19 **Explanation:** You can exchange 4 empty bottles to get 1 full water bottle. Number of water bottles you can drink: 15 + 3 + 1 = 19. **Constraints:** * `1 <= numBottles <= 100` * `2 <= numExchange <= 100`
null
Database
Hard
null
287
hey guys it's iran and today we're going to solve another coding interview question the question i chose for today is find a duplicate number it is lit code 287 which is labeled as a medium difficulty and i'm going to give you a bit of a spoiler here the optimal solution will be floyd's algorithm for cycle detection but i don't want to just show you the solution like it came from nowhere i want to show you the entire thought process leading up to it and because i didn't want this video to be too long i decided to split it into two parts in this part i'm going to explain how to even get to the point where you know that you have to use floyd's algorithm to solve this so we're going to do all the incremental optimization steps leading up to the optimal solution and then in the next video i'm going to explain floyd's algorithm in detail i'm going to explain why it works how it works the whole thing so let's get straight into it so the description goes like this given an array of integers nums containing n plus 1 integers where each integer is in the range 1 to n inclusive there is only one repeated number in nums return this repeated number you must solve this question without modifying the array norms and use only constant extra space so let's look at the examples to make sure we fully understand the question in this example we get this array of five elements and the output for this array should be 2 because that is the number that appears more than once in this example the output should be 3 because 3 appears more than once in the array and by the way it is possible for the repeated number to appear more than twice uh i mean this is also a valid input uh and the output in this case should also be three okay let's start to think of the solution and i want to start by completely ignoring uh these constraints right so if i could use some extra space what would i do so the simplest way to solve this with some extra space is to keep a hash set that will keep track of the scene elements right so in c plus this would be an unordered set it will contain integers and i'm going to call it c now for each element in the array we're going to check have we seen this number before do we have it in our set so if our set contains num if it's in our set we know we've seen it before so it must be the duplicate so we return it otherwise we insert it into our set because now we have seen it and i'm also going to add a return minus one here even though we're never going to reach it because we're guaranteed to have a repeated number in the array but i'm going to add it just for uh completeness and this should work let's try okay good so the space complexity for this solution will be o of n and the time complexity will be average of n now a nice small optimization that we can do here and this is a really important technique because it comes up in a lot of different questions would be to use an array instead of a hash set this will improve the time complexity from average of n to worst case o of n so because we know that all the numbers are in the range 1 to n you can easily just keep an array of booleans of size n to keep track of the same elements so we would just replace this set with an array with a vector in c plus and it will be the size the same size as the input array initialize to false and then to check if we've seen an element before we just check the relevant position in the array if this is true then we know that we have found a duplicate so we return the number otherwise we want to mark the relevant position in the array as seen and this should work let's try to submit this okay that is a really good improvement already now what can we do next we want to completely get rid of the extra space right that was one of the constraints in the question uh so we want to get rid of this scene array so what we can do is try to mark the input array for scene elements instead of using an extra array now notice that if we're going to mark the input array it means that we'll be modifying the input which is not allowed but i'm going to continue to ignore this for now because these are all incremental optimization steps that will get us to the optimal solution so because we know that all our numbers are in the range 1 to n we know that they are all positive so one way to mark the number as being seen is to just negate it right so what we could do is just first of all let's take out the scene array and what we can do to mark scene elements is to just negate it like this and now this check becomes if the relevant position is negative that we know that we have seen this number before so we return it now because there is a chance that this value is now a negative value we want to take the absolute value of this right because otherwise this would go out of range so we take the absolute value and this should work okay good so this solution will have a time complexity of o of n and a space complexity that is constant so the one last constraint that we have to meet here is to not modify the input array so in order to do that let's try to see what this code is doing step by step with an example so we have this input array nums in our solution we start by looking at the first position so we look at the first position the absolute value in the first position is one so we go to position one and check if it contains a negative value it does not contain a negative value so we negate it and move on to the next iteration we look at position one the absolute value in position one is three so we go to position three and check if it contains a negative value it does not so we negate it and move on to the next iteration we look at position two the absolute value in position two is four so we go to position four and check if it contains a negative value it does not so indicate it and move on to the next iteration we look at position three the absolute value in position three is two so we go to position two we check if it contains a negative value it does not so we negate it and move to the next iteration we look at position four the absolute value in position four is two so we go to position 2 and check if it contains a negative value and this time it does contain a negative value and what that means is that we have seen this number before we know that we have found a duplicate so we return it now what i'm saying straight away is that we've created a linked list right and then there is a cycle here that starts at position two which just happens to be the duplicate number that we're trying to find and i can tell you that cycles almost always mean something so what i would do at this point is do another example and see if this is a recurring pattern so let's get rid of this code here we don't need it for this so in this example we again start at position 0 that is the head of the list and we treat the value in the cells as if they were pointers to the next cell in the list so according to that logic cell zero points itself three cell three points itself four cell four points itself two cell two points at cell three and again we see here that there is a cycle and it starts at position three which is the duplicate number that we're looking for so at this point i suspect that the list will always have a cycle and that the duplicate number will always be the entry point to that cycle but simply suspecting is not enough what we need to do next is convince ourselves that is really the case let's start with the first question will the linked list always have a cycle so let's think of it this way if the array size is four then we have four cells one for every index and all the values are in the range one to three cell zero is the head and cell zero cannot point to itself because zero is not in the range one two three right uh so it has to point to one of these three cells let's say it points to cell one also has to point to one of these cells it cannot point here because zero is not in the range one two three and you cannot point anywhere else because these cells are the only ones in the range one two three right now if it points to itself then we get a self loop which is also a cycle and we're done right we have our cycle but let's say it points to cell 2 also has to point to one of these cells if it points to itself then we get a cycle here and we're done if it points to cell 1 we also get a cycle and we're done so let's say it points to cell 3. now again cell 3 has to point to one of these cells because they're the only ones in the range 1 to 3 and no matter where it points a cycle is created right if it points to itself then we get this loop if it points to cell 1 we get this cycle and if it points to cell 2 we get this cycle and see this has to happen because none of the cell can point outside of these uh three cells and in the general case where we have uh the array size of n plus one all the cells will have to point to one of these n cells right there are no now pointers so there is no way to exit that means the linked list will always have a cycle and the head cell 0 will never be inside the cycle because no one can point to it the next question i want to answer is will the duplicate number always be the entry point to the cycle so let's look at our example again notice that the number of incoming edges a cell has is equal to the number of times the index appears in the array because that's the way we define the list right the reason cell 2 has two incoming edges is because 2 appears here and creates this edge it also appears here and creates this edge we also know that there is only one duplicate or repeated number in the array right if i move this part here for a second we will see that it says that in the description all the other numbers will appear at most once which means they will have at most one incoming edge so that means the duplicate number will be the only cell that has more than one incoming edge now because we know that there is exactly one cell that has more than one incoming edge we know that it has to be the start of the cycle because in order to be the start of the cycle a cell would have to have one incoming edge that comes from the pot before the cycle you know this part here and we know that this part exists because zero cannot be in the cycle right uh so it has to be in the part before the cycle it will also have to have a second incoming edge that closes the cycle uh so it needs to have at least two incoming edges and the only number that can have two incoming edges is the duplicate so the repeated number in the array will for sure be the entry point to the cycle and now the problem becomes find the entry point to a cycle in a linked list and this problem can be solved with floyd's algorithm for cycle detection also known as the taurus and the hair and just a side note here if you've never seen this algorithm before i highly doubt that anyone can just come up with it during an interview like on the fly but i will explain the intuition and why it works and how it works step by step so from now on you will have it in your toolbox because i decided to split this video into two parts we're going to do all that in the next video so thank you for watching i will see you in the next one
Find the Duplicate Number
find-the-duplicate-number
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. There is only **one repeated number** in `nums`, return _this repeated number_. You must solve the problem **without** modifying the array `nums` and uses only constant extra space. **Example 1:** **Input:** nums = \[1,3,4,2,2\] **Output:** 2 **Example 2:** **Input:** nums = \[3,1,3,4,2\] **Output:** 3 **Constraints:** * `1 <= n <= 105` * `nums.length == n + 1` * `1 <= nums[i] <= n` * All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times. **Follow up:** * How can we prove that at least one duplicate number must exist in `nums`? * Can you solve the problem in linear runtime complexity?
null
Array,Two Pointers,Binary Search,Bit Manipulation
Medium
41,136,142,268,645
277
how's it going guys today we're gonna be going over leak code problem called find the celebrity this is a question right now that's being asked by Facebook Pinterest and Microsoft accordingly code and the problem scription says suppose your Idol party with end people and among them there may exist one celebrity the definition of the celebrities that all other n minus-1 people know him or all other n minus-1 people know him or all other n minus-1 people know him or her but they don't know any of them so now we to figure out if there is a celebrity and if there is one who they are right so the only thing we're allowed to do it tells us is ask hey ad know B and this gives us information about whether a knows B or not and so we need to find out if there is a celebrity and if there is we need to basically do this by asking as few questions as possible so we're given a helper function called nose which tells us whether or not a nose B and given this helper function we need to implement a function that will either return the celebrity if there exists one or return negative one if there is no celebrity and we need to minimize the number of calls to news cool so given that we have this helper function right we need to figure out if there is or is not a celebrity and if there is one returned who the celebrity is so with this nose function we can return we figure out two things right so with a nose be a can't be the celebrity and if a doesn't know be a could be the celebrity so I think that's kind of like the main takeaway from this helper function so given that we can kind of start formulating a solution right so if we find two pairings where a does know B that means that B can be a celebrity so they're kind of like a candidate right there's someone who could potentially be a celebrity for us whereas vice-versa if a doesn't know be whereas vice-versa if a doesn't know be whereas vice-versa if a doesn't know be a could potentially be a candidate for us so just kind of using that logic let's find a candidate so let's have a variable called in candidate and we'll just set that to zero just to say you know to start okay zero is our candidate and now we can loop through so for in I equals one because we're starting at zero or rather we're setting our candidate so start at zero so we get started 100 I is less than n I plus and we're just going to check if the candidate knows I then our candidate is going to be updated to odd right so if our candidate knows I that means that I could potentially be a celebrity right and the candidate can no longer be the celebrity because if they are the celebrity they shouldn't know anyone at the party cool so now after this loop we have a candidate and so now what we really need to check is everyone else knows our candidate and our candidate doesn't know any of them so we need another loop to go through all the people again so we'll say for in I equals 0 I is less than n I plus again this will let us go through all the people and now we want to check is if I is not equal to candidate right because we don't want to check if the person knows themselves and knows candidate I or not knows I candidate so here we're checking if the person is not themselves right so if we're not going to compare whatever person wrong to the candidate that we currently have and the candidate knows the per but candidate knows the person we're on or the person we're on does not know the candidate if that's the case we're gonna return negative 1 right because if our candidate knows the person or the person doesn't know the candidate then there's no way the can that can be a celebrity so if we get through this entire loop and we've never returned negative 1 we can actually just return our candidate let's make sure that this works awesome it does let's check out our details here our details tell us that we passed 171 out of 171 test cases and we're in the 73rd percentile in terms of run time so that's the interview question find the celebrity in Java I hope this is helpful guys if it was be sure to leave your thumbs up and subscribe for more videos good luck on all your interviews and I'll see you guys next time
Find the Celebrity
find-the-celebrity
Suppose you are at a party with `n` people labeled from `0` to `n - 1` and among them, there may exist one celebrity. The definition of a celebrity is that all the other `n - 1` people know the celebrity, but the celebrity does not know any of them. Now you want to find out who the celebrity is or verify that there is not one. You are only allowed to ask questions like: "Hi, A. Do you know B? " to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). You are given a helper function `bool knows(a, b)` that tells you whether `a` knows `b`. Implement a function `int findCelebrity(n)`. There will be exactly one celebrity if they are at the party. Return _the celebrity's label if there is a celebrity at the party_. If there is no celebrity, return `-1`. **Example 1:** **Input:** graph = \[\[1,1,0\],\[0,1,0\],\[1,1,1\]\] **Output:** 1 **Explanation:** There are three persons labeled with 0, 1 and 2. graph\[i\]\[j\] = 1 means person i knows person j, otherwise graph\[i\]\[j\] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. **Example 2:** **Input:** graph = \[\[1,0,1\],\[1,1,0\],\[0,1,1\]\] **Output:** -1 **Explanation:** There is no celebrity. **Constraints:** * `n == graph.length == graph[i].length` * `2 <= n <= 100` * `graph[i][j]` is `0` or `1`. * `graph[i][i] == 1` **Follow up:** If the maximum number of allowed calls to the API `knows` is `3 * n`, could you find a solution without exceeding the maximum number of calls?
The best hint for this problem can be provided by the following figure: Well, if you understood the gist of the above idea, you can extend it to find a candidate that can possibly be a celebrity. Why do we say a "candidate"? That is for you to think. This is clearly a greedy approach to find the answer. However, there is some information that would still remain to be verified without which we can't obtain an answer with certainty. To get that stake in the ground, we would need some more calls to the knows API.
Two Pointers,Greedy,Graph,Interactive
Medium
1039
1,094
hi i am ayushi rawat and welcome to my channel today we will discuss the september lead code challenge day 21 problem car pooling now let's have a look at the problem statement you are driving a vehicle that has capacity empty seats initially available for passengers the vehicle only drives east that is it cannot turn around and drive west okay given a list of trips such that trips of i equals to number of passengers start location and end location contains information about the ith trip let's see what each one of them means number of passengers that must be picked up start location is the beginning location that we need to pick them up and end location is the location where we need to drop them the locations are given as the number of kilometers due east from your vehicle's initial location okay return true if and only if it's possible to pick up and drop off all passengers from all given trips okay now let's consider an example let's say example number three here input is trips and capacity trips is a list of lists and capacity equals to 3 trips is 215 list and list 357 it returns true i'll explain this example to you while we code make sure you follow along the constraints are trips of length is less than equals to 1000 trips of i length equals equal to 3 1 is less than equals to trips of i zero is less than equals to 0 is less than equals to trips of i 1 is less than trips of i of 2 is less than equals to 1 000 i is less than equals to capacity is less than equals to 1 lakh there's a hint sort the pickup and drop of events by location and then proceed them in order okay i am going to use a dictionary here to store the capacity of a car at each point of time now let's quickly head over to the coding section initially i am going to define trip capacity as a default dictionary next i am going to run a loop over length of trips now as we know trips has three sub elements number of passengers start location and end location so i'll store number of passengers inside num start location and start and end location and destination so number equals to trips of i zero start equals to trips of i1 and destination equals to trips of i2 so here we are considering example number three so for first case number of trips is two start will hold one and destination will hold five now i'll run another loop from start to destination now i will add the number of passengers to a dictionary okay so now let's understand what we have done so far in the very beginning we define trip capacity as a dictionary so we have an empty dictionary at the beginning then we are running a loop over trips is nothing but a lists of lists in our case we have two sub lists here when i at the beginning is this first list so trips of i of 0 is 2 start it strips of i of 1 that is 1 and destination is strips of phi of 2 that is 5. so now we have these three values in place next we are running a loop from start to destination that is from 1 to 5. when j is 1 in the beginning then we are setting trip capacity of j plus equals to na that outputs us with our default dictionary as with key 1 here and 2 as the value so we have 1 2 value pair here next when j is iterated to 2 then our default dictionary is also updated and it runs till 4 when j is equals to 4 and we have our dictionary which will look something like this once we are reached here now we'll set off to increment i and now once the i is incremented we'll follow the same process for the second sub list in that case now num will be 3 start will be equal to 5 and destination will be equals to 7 and capacity remains same that we have 3 which was passed in the beginning as a parameter for a function here now we'll increment j which is equals to five now and keep updating our dictionary lastly we have j equals to six now dictionary will look something like this we are using trip capacity of j plus equals to num that is strip capacity of j equals to trip capacity of j plus the number okay now we will check if the trip capacity is greater than the capacity then we'll return false otherwise we will return true at the end trip capacity of j if greater than capacity then we are returning false otherwise let's return true here now let's try running our code it seems we have an editor it should be r now let's try running a code now let's try submitting it and it's done you can join my discord server and telegram channel for regular updates you can find the code at my github repository link is available in the description box below if you wish to connect with me on other social platforms the link is mentioned in the description box below if you have any queries or suggestions please feel free to ask if you like the video hit the like button and subscribe my channel thank you for watching
Car Pooling
matrix-cells-in-distance-order
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location. Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_. **Example 1:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4 **Output:** false **Example 2:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5 **Output:** true **Constraints:** * `1 <= trips.length <= 1000` * `trips[i].length == 3` * `1 <= numPassengersi <= 100` * `0 <= fromi < toi <= 1000` * `1 <= capacity <= 105`
null
Array,Math,Geometry,Sorting,Matrix
Easy
2304
1,192
hello everyone it's april 24th ah we get a little bit early today well i'm doing this because i really want to engage in a new data visualization library that i found it's called deck well it has a python wrapper it's called pi deck it allows you to do really amazing visualization over maps and i currently have some data that i want to see on that well technically speaking the data doesn't have to be shown on maps but it's kind of just like i want to you know ever since i just start doing streamlight i really want to turn every data visualization into an interactive app i think i'll make things a lot more easier to explain but in this case i think about the data it's actually not going to look any better when i use pi deck even if i have uh a map in the background they kind of look cool like okay you know where the data comes from but overall i don't think this one would really help i mean just based on how i'm thinking about it but anyway it does not really matter because i just want to do this for fun so before i get into that i want to finish recall because i think when i start getting the flow for that thing for the pie deck i probably won't snap out for a long time anyway uh let's check this somebody commented this i remember i wrote comment yesterday uh actually not this one what is this one no nobody commented on things i wrote yesterday i doesn't matter alright so today is uh saturday i've been nervous critical connections in your network oh i've done this using oh lord what's the library's name uh graph python what's the no graph this no create graph no what's the one i use that's not plotly it's the oh man graph theory i don't know i'm just let's try this graph here no that's going to graph theory man what's the library i use for plotting graph uh what's the name graph network python network graph network what's the library i use i think i might have it here uh data science no i don't see it man i don't see it at all holy moly i forgot what it is uh let's try google maybe it has better luck so network python library how about this oh i graph that's the one yes i used that to do a lot of graph when i was learning the social network it was a good library i actually kind of forgot how to oh look at this interactions in the background i know that yeah i think this is the python eye graph yeah that's a lot that's the wrapper that i use it's quite nice uh so this is one of the problems that we had in this class trying to find which link is the critical one using i graph i think this can be done very easily oh my god i forgot already there are some um parameters right some metrics we can calculate based on a graph like the importance there are a lot of different um values that can be used to calculate the importance of each link and they just find the one with like the highest importance something like that i shouldn't really talk too much about this anyway let's take a look uh so okay connected by undirected server to server connections for my network okay connections i represents a connection between a and b any server can reach any other server yes a critical connection is a connection that if removed will make some server unable to reach some other server turn all critical connections one 3 is the critical connection yes i have 10 to the fifth then i is not equal to connection i1 which means there's no self loop no repeated connections okay uh basically what i think this is uh i'm going to do just have i done this before i mean there are going to be a lot of ends and a lot of connections all right we'll have a lot of connections how do we determine like if we sever the connection then we cannot go back which means some connections are critical like if i have another one here right and then these two local i think it's called clique something like that and then they're only connected by one and if we sever it now something cannot get into the other um we'll get start from anyone then we can visit right and then we can visit it's initially it's all connected right i think initially it's all connected and uh ooh i shouldn't remember something from outside in like the what's it called a sword top all topological sword well this work with topological sword i don't know i mean if anything has one link right uh yeah i think topological sword basically or we can sort based on the number of links thing has critical connection is a single connection if removed will make such a single connection right who do topological sort actually don't even know what this sword actually does topological sword i think what it tells us it's just like we pick something and then we lift it up we can try to traverse from one node to this node and then we can get it from here what's topological sort of a directed graph a linear ordering of its vertices such that for every directed edge from u to v u comes before v in the order of the graph they represent tasks to be performed and the edges will represent constraints but one task must be performed before the other but in the technological is you just a valid uh sequence for the task crowd has no interrupted cycles okay let's see an example many valid technological sort uh that's not the one that i was thinking about right visual top to bottom left to right there's another thing that i've had in mind but i don't know uh maybe some other source will be more helpful but this is for that what we have is not a dag every directed edge that is u comes before v in the ordering five four ah yes two so these two are the there's nothing pointing to them and then two by four two and three and one yeah so far to two three two one and then zero on one order yep now i don't think this is a topological store though critical so we go from this coming in i have no clue i took a class on this but i forgot it completely um it's critical that means if we sever it then something cannot be reached right how do we determine that as we traverse and we cannot just like keep traversing right i mean if a node can be reached in two ways now is if an edge is needed when you visit a certain null then if an edge is needed when you visit certain nodes like that's the only edge so like for two to visit two we have two edge right and there's a zero will have two edge one we have two but three we only have one edge that's why three is critical which means if we cut it and three cannot be reached but i'm drawing some other graph just kind of think if how can we reason this right so if we have two edge connecting but there will always be an edge that has only one but um critical okay critical do we have a critical if we have if oh then it's going to be empty right four notes and then let's go a three and zero let's put another link three and zero right let's see this shuttle turn or empty is not a valid type uh because i forgot to add this maybe empty is empty yeah so it's no critical okay and we go through right i mean in this case um i'm trying they have like a dry photo no i don't drive for you it's critical but it's not counted number of links because this will have like three links this will also have three links it is from message going from here to here right i'm going to start from every single node i'm trying to tr start from a node we're trying to traverse right and then until everything trying to traverse we just don't go back right and then as we traversing what is a critical note a critical node is in a graph as that's the single link connecting two graphs to sub graphs that is a critical link right that's a critical link which means if we can find anything um think how do we find a link that is i was thinking like if you traverse right to reach each node i'm going to count how many times a link is hit right how many times the link is hit i mean ideally say as you traverse from one node to the other node without going again like every time i'm going once right but now they are they all they're all traversed no it doesn't feel right to me i mean we have how many we have a lot of connections what if we say we just say break a connection all right if we break a connection like um like we have say here we have one to two or connection one to two if we break one or two now we want to know if from one can we reach two how do we do that well we need to find neighbors of one three and zero neighbor of two but they could be like further apart right they can be far apart i cannot do it's 10 to the fifth so it has to be like oh n or something like oh and log n something like that man i have no clue um this one can reach this so the break and then we're trying to find out if the two can still be reachable how do we do it i'm gonna say that's reachable by here i can traverse graph is my weak point that is for sure we have a link and this is not helping man this is not helping how do we find a link i don't know where to go it should be starting from any note right and then we traverse and as we traverse i mean we can visit each node right traverse reverse and we reach no we can like we can have a pass right we can have a pass from one node all the way to the other node now we don't want so that's but also do right if we find a path like we can find a path that can connect every single one a path and if we cannot go back so that's a bad path so we go from here and here that's a bad path here and here that's a good path right so we do this as a good path now once we find a path we can try sever the connection doesn't feel right to me man if we sever a connection and we need to know it's still reachable to everyone and there could be like tons of paths right it'll be a lot of path to connect each one any from any point right we have this and we say we don't know if this is a critical point or not we assume this link is a critical point and we assume that this note cannot be reached from myself then we try to see if we can reach it how do we do that we have to traverse right the traverse and let's say we traverse and we find it now we know this one's not a critical link and then we say we're going to cut the other one then we have to traverse again i'm like we wouldn't say these two are not connected we cut this one and when you traverse again no that doesn't feel right man that doesn't feel right have a breath first search for my node i can go to all my neighbors and from all my neighbors i can go let's see let's say from a node and go to all my neighbors right and then for my neighbors i can keep going and if that go and go into one of the node in this on the same level that means we have a triangle and that's a fully connected network graph that means none of those are critical does that make sense if we start from any node and we do bfs right breath first so it's spread out and after it spreads out i then check every single one and spread out and everyone can further spread out if during further spread out one of the spread goes to a node that we have seen before then like either on the same level or on a level above it now let's first talk about on the same level right on the same level it's like here right we go three pass and then we go take a look at here and this one we don't go back right we cannot go back so we take a look at the node that it has which is zero and zero is on the same level now this one comes here and we also know this is on the same level as two that means if i can if this we have a connection between this and these three are in a triangle so if in the triangle none of these are correct right none of these are critical and then check this is the same and connected two so it's not but in three there's nothing right there's nothing connecting to nothing so we say that is a good one i mean we can also say we have levels right now we can have a level connecting all the way back to the top now we can say when the top here and whatever links linked and then we have a path as well which means this is not critical because i can go all the way the other way around so basically we're trying to see is from the first whatever we pick the first and we want to say actually if we link all the way back then we have like a it's not a triangle but like something here right same with this one link all the way back to some note here and unlike previous level and what happens is from this previous level we descend and actually am i not connecting to this one hold on we um have this descend the sun the descend but there gotta be a path leading to this right level even to this and this one connecting back right yeah there will be a path that will there will be a path if this one if i go here and this one connecting back and there will be a path or be a path and during this path it means it's a cycle right if we have a cycle that means any link in between any link if we break it and that's fine right none of them is critical because we're talking about breaking one right not breaking multiple if removed will make some sensors enable so it's just a single all right i want to test the theory yes definitely it's a single because if i do both and this is then b2 this is a single it's a single connection then none of those won't matter right if i can connect this node either on the same level or any other level above that i'll form a loop whatever loop it is our form so the none of these are critical if we cannot find right if we cannot find so we have a path down and like if we can find that mean what happens if we can find that means uh none of the connections among those nodes are critical right if i have a node connecting to the neighbor or connecting above then all of them are immune right all of them are immune then we simply don't consider it anymore right once we find it we can keep going yeah we need to keep going so we keep checking we visit every single one of them once and we look for a node that do not have any connection to the things above okay let me try on a different example i mean the example i'm thinking about is we have triangle here we have another triangle here right that's the example so i'm drawing on my own paper so if we start let's just start one two that's a zero that's three let's go four and five so we start from one right same thing one we can go up and let's not start from let's start from zero it'll be interesting to go from zero from this point so zero i'm gonna go out one and two and from one we can go to two right so one is fine and from two we can go to one that's also fine but from one we also can go to three right so i'm gonna go to three and two to go to one that's it next one's three coming out and three come out three can go to four and five and three go to four and five and cannot go back three doesn't have anything on the same level and three doesn't connect back so that's why three when we look at three and look at the things it can connect to then we know the link is critical angle four can connect to five that's why that's is not critical okay i might have a solution it took us a long time to reach this stage i'm going to just you know take a shot am i confident definitely not i mean i'm pretty far from being confident in this sense but i do want to give it a try maybe this is the correct solution who knows right who knows so what we have is i'm going to turn this into because these are links i want to know nodes right so from 0 i need to know who it goes to so a dictionary will be fine what about the values and top values like a and b what is a and b i think it should be from zero so i probably can get away with just uh i don't know the a list of lists all right so when i say graph equals right and this four in range and right and then when i say four uh note one note two in connections graph no one dot append node two and graph node two dot append no one okay so now we have the graph then we just pick i just pick from zero right and then i'm going to do dfs we're going to say q equals this right and let's say actually q is not equal to this q can be equal to zero but no and we say while q right and then we say what do we say we're going to find out what node what you have right one node does it have so current node equals q that pop right so node is zero now i want to find out the children of zero right and then either we push the children into zero and into it uh we also need to know whether zero has i mean zero is a special case right zero is a special every time when we check a node right we check its next connection like if it's on the same level or if it's uh on a level uh above us right how do we know it's a level above us we need visited right we need visited is going to be a set which is actually going to be 0 has been visited right so uh maybe this is not it's going to be a set let's do set add dot all right so evan node and then i have a bunch of them and then when we check each one when you see if this one has any connection to above or to the same level right that's what we want to see either up or to the same level if it is not up or to the same level how do we check if it's the same level well we push it in the next level and then we check if they are on the same level or it just means if it has a connection to the thing that we have seen before except from the one that leading it to it right that is the key so for example we have a zero right zero come out we have two and one and we don't consider zero because that's the that's just the beginning or we can just do a dummy node right we can do a dummy node and then we'll connect to zero and a zero have something to connect back so zero will have so zero down to two and one right and then from we push 201 into the queue and next one coming out it's gonna be that's the q right that's the queue and to pop out i'm going to see two next right and then we go through and know that to link to and then we see link to zero but that's the one how do we tell that's the one that's come that where'd it come from we didn't know yeah how do we know that's the node that you come from we don't know where do we come from which means when we push to the queue we need to know our parent right we know our parent and zero's parent is none so let's say we have a parent is gonna be none zero all right and then visited is zero and we're gonna say parent and node equals this and we say if so apparently then we're gonna check yeah i'm gonna check its children right so when i say for child in graph node right so we have child in a graph node and we're going to see if the child if child is not equal to parent right if child is not equal to parent if the child is not equal to parent which means it's not pointing back right a child is not equal to parent and the child is on the same level if not if the now so if the child is in q right man q is maybe q has to be visited i mean we already have the queue man hold on what i want to know is if there is a way to so on and come out i want to know if my node can reach any of the ones in the current which means i mean the queue and we need a level i want two things right we also oh man we need so many things but that's actually visited right that's actually visited but we haven't visited yet because i'm not visiting this yet so this is just at this level right for child a heart i am so uh if a child oh my god i feel like i'm almost there but this if a child yeah so one and two will be in visited already so if this is its child is one and zero right if his child is in visited but it's not the parent that means it's good right and if that happens then it's good and then we don't have to put it in so say if child is not equal to parent and child is in visited right then it's just it's good right that's good uh else it's not parent and the child is in visited which means it's either equals parent alif just eldest child is in childhood not invisible right child is not invisited then we're going to say visited dot add child right and q no not q every time we do q we have to do a next level equals this right so when you say next level dot pen it's going to be parent which is note and child right so we go through everything and we just say i want to see right we want to see well q then q out keep going on the next level going and going shouldn't we have another one on the outside i'm confused yeah i think we have a wild q on the outside as well right i have a wild q on the outside as well and then we have basically two level we have to go this was a consuming queue popular in the next one and then next level is going to be here and then we get every single one out check his child and the child does not then we're good and if it is not in then we push him to visit it and once we finish the child this nodes child so we have a node and we go through all the child once we finish we're going to see if it's good so let me say hash critical equals let's say false because true has critical equals true and as long as one of the child that can connect back then we say has critical is false right and then after we're done when a check if has critical then that means from this child to from this child right from this no from my current node hold on what are we doing what we're doing is on a note we're trying to look for his child and if his child doesn't connect back or connect to the same level then we say there then we say the child let's see the node and its parent is critical so when i have a result it's going to be this so it has critical then we say rest.pen gonna be parent no right parent unknown and then after we finish after q is all being popped then we say q or equal to next level right now we go back up okay so as we are doing this uh this one is actually we can use a deck just pop in the front but that's fine so what we have what will happen to the first one to the zero right so zero comes in parent is none known as zero right and then it has a child but none of the child has been visited before so this one will not so child is not invisible and coming out as a critical and so f has critical and parent is not none then we do this and we're going to return the rest all right take a look i'm not confident at all i feel like this is correct and i hope it should be correct and then the answer is one and three okay and now we actually have another test case that we conjured up ourselves oh well i have a four in the front so for this one will give us an empty because we do not have any critical in this one okay so create another one the one that i want to do which is uh this and we're going to add just a few more right so what we have is three and four and three and five and so three four three five four five right so we're gonna have six nodes this one should have one three as well so we use this as well so we have three test cases six this oh no oh what the hell okay not selected huh and then this one has one three as well okay all right uh we have n connections then this one is critical and connections run it dick object has no attribute add you don't have to be this is not necessary so it's going to be a pen this is also going to be append they all pass okay i mean we might get away in this one using a deck actually i like to use deck collection is import deck then i just say deck equals no still q equals deck right and then we just say wow deck while q why always say wild deck we don't need this right and then we can just say equals q pop left then the same thing then we just say next level this is going to be q dot append yep give it a shot what i'm afraid is this going to time but give it a shot pending judging come on i think we're timed out oh we have a wrong answer i'm going to take a look that's not correct i think the logic is wrong and it's impossible too you have ten thousand is impossible to figure out expected is nothing jeez what type of graph is that and i say all of them are bad wow okay one zero let's try it one okay one zero two zero so two zero that's three one uh actually one this is three one four three five zero six one seven three all of them are critical at the current point eight five nine eight what's your deal man uh hold on which means as i'm going through but oh connect back to one who connects back to three they are connecting to three oh my goodness this is not gonna work i feel like even if it works just gonna time out oof that's a lot of things right there and then copy and paste this thing to a new one because we want to collect this oh yeah there's a tons of them ten thousand of them and there's no way i'm gonna do something like this we have to find a manageable level that's manageable ain't gonna work ten thousand a laptop is die why is there because it's a zero one they cannot find another one so click on zero i can visit all of the others right from zero i can visit everybody right which is fine and i visit one and from ah yeah i see because i was just looking at one level from one i was looking at like three six whatever that's connected directly to one which if you take a look here i think connect to one is just 367 but oh god something is now working oh i have to quit it yeah i have to do it again and we are not going to test this one because it's just vastly reasonable oh my god are you doing this one more time i'll just close you yep all right yes the problem is if i take a look a one is only connected to three six and zero right so when i do one its children definitely is not visited so that's why we i kind of you know i already say zero one is bad but eventually i think 3 6 they will connect they'll keep going ah so we cannot do immediately now what which means we have a very deep right from zero coming out and punch and iphone one and coming out we also have a bunch and they don't immediately go back but it just so happens that as we go deeper someone linked back it should be as long as someone linked back that everybody on this path are good how do we find a child in me and then if the child is not visited i would just keep adding until a child is in a visited right now i have a child that is in the visited that means the entire path from the one that's visited all the way to me and this path is all good what are these paths i go back like someone has to go back right 53 go back to one right so when we hit one would go to 53 right so when we hit one hey go out go to 53 right and then none of these connects back to of course they do not connect back and then they do not connect to each other and as we keep moving somebody will connect 53. for instance someone will connect to 53 who connects to 53 someone will connect 53 and then when they connect to 53 connects back to one all right and then that's good which means we just go from 1 to 53 and then we go layer and go another layer and one of the layer the node right one of the nodes 53 of course another one with another one and someone will go back well if they go back it will be incorporated at the beginning already so this idea is actually not correct right if i start from the beginning and i branch out of tons of branches out and then for each one also franchise it's impossible for me to go back right why would i like go back it's not possible to go back because if i go back and that one will be visited already right if i have a node that i go back and this node will be visited already if it's children going back it will be like and that will be on the same level yeah so it will always be on the same level so what type of network that we're talking about here like a simple solution first so let's say zero one two three zero one three two and two zero just thinking out loud let's see what this one gave us yep there we go that's a minimum incorrect example for me so before yeah that's the one that we cannot solve right now it should be empty case okay because from zero this is just a rectangle so from zero out we go to one we go to two and from one we go to three and that's it so nothing goes back all right and nothing goes to two so nothing goes to two and then from two we also got a three and from how do we resolve this yeah if we have a giant then from them we do bfs and then the next one is three right then if it already has connection then we're good if it does not have connection now we go to the children the child and they will have connection if the child so all we want to know is if a node has any way to connect to its neighbor right if i have the net direct connection with good if it does not because i am coming down from top down right top down if i cannot i already have connection to the parent level so what i want to know is if i have any connection with my neighbors on the same level right if i do that's good then there's no critical for me if i don't and there are two situations one is i cannot link back from me going through my child right i cannot link back because there's no direct path another list even from a child i cannot reach back so we can record these as say potentials right the potentially bad and i keep going right go to the child and then and we have a bunch of potentially bad because i can imagine this one just keep linking right thinking all the way down and then eventually somebody will meet right so basically you're saying we're branching so we're branching and then we just don't see any connection none of the layer no none of the layers none of the levels has i mean some might have right some might have and then we can just eliminate those but a lot of them don't right a lot of them just hanging there so we have tons of these that we currently cannot find connection with each other so eventually we will reach a level right when they do connect so one is children and the other's child right as a child and then this child it connects right some child connect on the same level right if a child connects to another child on the same level then we say their patterns are connected right and then their parents are connected and there so we just bubble back up right so when now we find a connection whenever we find a connection on the same level then everybody up right everybody up will be connected think about it again we are on the same level we find a connection that means everybody leading to them are good and we have a path from top down right leading to this and we just go from their parents they're good their parents are good so all of those are good so it's these links are good but the links are good so every time i find one then the link that we save all these links the link from here there's this child that's another link it's like going from oh my god from top down i have all these links and then we have a link every time we visit a child there'll be a link connecting to it there'll be a single link connecting to it because if there's another link connecting to it then we have a circle that we're good right so from top we have the single link to this child if we have anything connecting to another one in the same level then those links do not continue otherwise the link continues right continue until we find one that connects once they connect then their child would starve from a new link to start from a new link that idea might work so go back to this example right so zero to one we have a link zero one right and then zero to two we have a link zero two and then from one there's no cross link therefore from one go to three when we reach three has two links zero one and zero three right and then from two i go to 3 as well and from 2 i go to 3 as well and then from perspective of so on one we push three into it from two i don't put because from one i push three and every time i push i already put it in the visited so next child so zero gets one and two right and then one gets popped out they put it and then two gets popped out and two's children i see it is already in it right it's already in it which means it's on the same level and then 2 does not push it in right so and two goes to three and we don't push it but one doesn't push it to three and then three comes out and three comes out three has link zero one and a one three right that's when we push three in because well why do you push three in now that's fine yeah three in so when three comes out a little bit confused zero push into one and this is a child right zero have a child that's one and then uh every time i have a child when the c if the child has been visited already then we have a loop right and we then what do we do if a child has visited already if a child because it's only be on the same level right so i have a child in this child so we have a child and we're considering this right on the same level we have this and if it has a child that has been visited already then that child don't continue yeah that child don't continue because it's on the same level it's been visited already what if we visit that child has to keep going yeah because that's we finish a loop here but that child has to keep going so that one has child it's five so it has a child so here one right one we have a child and when we see one as it is child it has not been visited before so we put us in right we put this in and two we have a child you should put it in as well right we should put this in as well as the next level right it's visited but you're saying here like two just don't push it because it's in already so from two we don't push it so there's no more from two it's only from one so from one then we'll go to three from three's perspective it does not have child right so i mean three does three has one the three has two right yeah so from zero to one two to one and two and then uh one will go to three two does not go to three and three sees that and child is visited hold on why would this one give us we start from zero right and then from zero child is one and two and this is one a is not invisited so that's it only visit one cued out a pen one zero and a one all right and then two should be zero and two one cup the parent current is none so we can do it back up so this is zero and one the child is note one once child is three is not so we visit three right and then two dot append is one and three and that's it coming out critical is false right so but now we say we hold on to it hold on the path and then we'll go to two right so the next one two will come out two will have a child this is three and three c is already visited right so that means from perspective of two we already form the loop on the two so we don't visit three right so now come back to three pop out and three has two child three has one it's the parent and then three has two and then three take a look at two has been visited before so from three's perspective i have uh also reached so that's the end there'll be nothing and in the result what will happen when we have the result is we have one path all the way down and then we go to a node like this continuously there's nothing right so thinking about here right this path is two to one that's a path that's a link one to three that's another link and from three nowhere to go so are you saying everybody on this link hasn't has any trouble that's not technically true because one two is not a critical thing like when somebody so like zero to two is equal to one right and then from one equal to one two already is so we just remove right so like the history of this got removed but when we remove the history here this one still contains the history it contains so from one right from one we can go to the next one we can go to the one that's contained inside and we have a path towards one right we have a path towards one and from one we have children's and then we need to go through one's children find one right that has been visited before and we can find one that has been visited before then all of his children will start fresh if we cannot find one that started before that all of the children have to carry the same weight carry the same path right so they'll all carry the same path it's like one path and then branch out then every single one of them will be critical this would be critical this is separate yeah but if later on right then this child is become visited then i was saying all of their paths from top to bottom is becoming good no it's still not it's still as from that node's perspective it's child is on the same level right that means that mean that actually depends right that depends on so we just have if it's on the same level right we're on the same level depends on where that thing comes from and that can depend oh my god this is not helping let's take a look at a hit we're gonna i might have heard of his name tajong strongly connected components algorithm strongly connected around five strongly connected components of a directed graph where the linear time maximum time down blah takes directive graph as input and produces the partition of the graphs vertices into the graph strongly connects the component each vertex of the graph appears in exactly one of the strontium components any vertex that is not a directed cycle forms astronomically by itself and verticals in degree and algebra is zero or any vertex of an egg silic graph okay let's take a look so this one goes here right here that's one here that's here uh okay so basically use this algorithm to find the strongly connected what do you mean by strongly connected if every vertex is reachable from every other vertex ah yeah we find the strongly connected and the two every verdict is reachable from every other verdict isn't that isn't the entire thing is my lord that's long uh that's as strong as let's find another implementation if there's a path between all pairs of vertices a strongly connected directed graph the maximum extremely connected for example there are three strongly connected right but ours is uh not strongly connected but like if you run the argument shouldn't it be everything will be the same let's see what's the illustration of this approach initially what is this reversal that's not helping me but disk and the low values relate to both directed and direct graphs so in both picture we take an undirected graph all right what is uh one dfs tarjan dfs search produces a dfs tree for strongly connected components from form sub trees of the dfs tree that's true if we can find the head of such sub trees we can print store all the nodes in that tree including head that will be one as cc okay there's no back edge from one scc to another it can cross edges but cross sections will not be used while processing graph to find the head we calculate disk and a low array low indicates earliest verb visited verdicts minimum discovery time that can be reached from subtree rooted with u a node u is head if what's disk is the time when a node is visited first time while dfs traversal okay we have shown a graph and it's um it's one of the dfs tree it could be different dfs trees on the same ground depending on ordering which edges are traversed in the of the tree continue arrows are tree edges and dashed arrows like back edges ah so this one is uh a back edges and it's a matter of black hedges or not so disk is the time and know it was first time low take us forward from ancestral node to one of the descendants and note c so okay so this is all one so this one step how is a is one what's this time point one two three four five six no one two three four oh no so one two three four five six seven eight nine ten the first time they are visited and low is to one of its descent for example from node c three edges can take us to node g node i c is here until node g and node i what from ancestral military to once again no c three edges can takes note i know j okay back edges take us backward from the center node to one of its ancestors for example from node g like e c a right but not d e c if we look at both tree and back edge together now we can see that if we start traversal from one node we may go down the tree via tree edges and then go up we have back edges for example from node e we can go down to g okay and go back to e and then up to c okay i forgot this e g yeah to see uh where am i similar from e we can go down to i or j and then go up to f low value of a node tells the top most reachable ancestor with minimum possible disk value via the subtree of that node so for any node low value equals to its disk value anyway let's read that sentence again low value of a node tells the top most reachable ancestor via the subtree of that node indicate the earliest visited verdicts that can be reached from the sub-tree that can be reached from the sub-tree that can be reached from the sub-tree rooted with you the earliest that's one okay c that's one d is one e well we keep going down earliest from e can reach is three and c e can reach c so only one back right is that what you mean there's only a one back f is all i also see g is c h which can be pointed to f i to f j to f okay again low u indicates earliest visited verdicts okay earliest visited verdicts the verdicts with minimum oh that's what discovery the minimum discovery time that can be reached from subtree rooted with u from a subtree that's rooted okay so we rooted that e and then when i go from e which would ignore everything that's going to e is the root so we can go to f and then go to g and you will go to c is the previous as the earliest visited verdicts that can be reached from subtree i mean i cannot say from this one where everybody can reach a okay triad just takes it forward back i just take it backwards right if we look at both tree and back we can see that if we start traversal from one node and go down the tree and then go up via back edges below e we can go down to g yes and then go up to c e can go down to i j and then go up to f e we can go down to i j and then go up to f so i want to allow one up right what means only allow one up low value of a new hotel is the top most reachable ancestor the minimum possible discovery value the other subtree of that node so for any node low value equals to its disk value anyway a node is an answer to itself then we look into its subtree and see if there is any node which can take us to any of its ancestor if there are multiple back edges in subtree which takes us to different ancestors then we take one minimum if we look at node f it has we look at node f has two subtrees so through node g and subtree with node h take us to e and c right into the e and c so it's just it's sub tree that's the root number subtree let's see what's the sub tree can take us the other sub tree takes it back to f only here topmost sensor is c reaching so low value of s is three based on above discussion it should be clear that low values of b c and d are one as a is topmost for any node u when dfs starts it will be set to its discovery first and later on dfs will be performed on each of its children v one by one low values of you can change it in two cases case one tree edge if no v is not visited already then after dfs of v is complete then minimum of low v and will be updated i don't understand jesus i'm lost here oh no i'm lost here for any node u when dfs starts low will be set to its what does it mean this one disk first discovery first later on dfs will be performed on each of his children v one by one low value of u can change i think it says low value weights itself and then lower i can change in two cases if note v is not visited already then after dfs of v is complete the minimum of low u and low v will be updated to low u well if v is not visited already now we're gonna visit v and oh yes this is correct because v might get to a node further back than u so we should update low u with low v that's true back edge so the v is already visited then that's a back edge the minimum of low u at disk v will be updated below u that is also correct h2 can we take low v instead of disk v uh let's say no okay we take a low disc v discovery v yes and low u and discriminate can we take low v instead of this v no because we only allow one package yeah because if we take low v instead of discover v then because low v is from v to going back right from v to go back so that is not i think this probably say that's not a sub tree rooted there all i can say is you can only you're only allowed to take back edge once i mean otherwise i don't know like because you cannot do two times you're only allowed to do one time back edge tree edge forward edge cross edge oh some low and this valley helps solve other crowd problems track the sub tree rooted at head you can use a stack keep pushing no while visiting when a head node found on a head node found pop all nodes once that until you get head out of stock to make sure we don't consider cross edges when we reach a node which is already visited we should process the vision node only if it is present in step i also didn't know the node i don't understand the last part but what is saying this we do dfs on each node right we do dfs on each node and in his children the children if it's not visited we do dfs on it if the children is visited but like in this case and in this case it's a legitimate like which one is the critical and there's no critical in this one but that's what we produce right i mean everybody is a back edge how do we use that i mean we can just go right go and then this one we have connecting here that's also okay all connected right all connected max also back so if we connect it back then the low value of this will become one right the low value will become one and then we also connect to this and this one connects back and now visited before this will be whatever is in the value is and this one will connect back it's children so this one that low value will also be one right a low value means all of these can connect back so basically we use low value we can find a node that they can all connect back to right they can all connect back to so isn't that the thing that you're thinking about like the one thing that everybody can connect back to so once we can connect back to a node so like all of these kicking that back to so we're going to say all the all of these can be reached there's no critical among these and then uh so you can go here right here and then from this one we say this here and then we have to go here right then this one here and then this one reach back right this one this is something that has a visible fall right so this but actually because we are all going this way so this actually when this one goes go here that's vision back and go here this one moving back and then this one just keep going have two ways to go like this one this way and then from here it will it has a visitors before so we go here that will go here right and then this one already visited right and then say this one connecting back how does that help us i don't know how this one helps us like this i'm kind of think trying to think that all of these are just an edge undirected all right so from c we can go to e from c we can go to g but it's dfs so we go to e and e we can go to f or go to g right it depends on which way you go first let's just say we'll go to e and e go to f let f go to h right h go to i let it j and j go back to f so now j has this right and this one also pointing here how about h well h we go here to see this point here so this h definitely a point into this as well so now all of these are pointing here right all of these are pointing here they are pointing here and this one can go g right and then from g we can go e right and then from e we already visited and then g would also go c so g one point dot to c right and then which means f will also point back to c right f also point back to c okay now what we have the low value which means these are the nodes that everybody can go back to c can go back to a f can go back all right so let's say e f g they all go back to this these okay i'll go back to here which means we have a loop we have like all these and go back here so you're telling me like the critical points are these are the critical points it still doesn't solve the problem i mean basically just define the strongly connected components how does that help us 0 and go to 1 and from 1 and go to 3 would go to 4 and 4 would go to 5 will go back to three so we say four five they all link back to three right because they're only one run right four five all go back to three right child five it's child has been visited before so it's the minimum of the three no just three discovery three and a minimum there's a three and a year itself now if i visited and then it's going to be the child is this is the tree edge minimum view and the minimum this right so this will become they are all rooted to three so we know three four five alluded to three and then it's done so one over the three and three is a three edge so just it's probably by the b would be itself anyone the low is it just itself then three the lowest itself just like here one the lowest itself right so three the low is itself so that's the head right three is the head because using this we can say three edges just around three we go to four right and then when it's done four pointing back to three and three so three the low three is still three and then we'll go to five three go to five's already visited now a low u and five that's terrible so it's gonna be three so three is ahead three is a local head and a one i have to visit three this three is an edge i haven't visited before so we're gonna be the low u low three s three and low one those three is whatever the value it is and low one will be whatever it is and now we're gonna take basically it's actually gonna be one itself because three doesn't go back and then i want to go to two is higher than before two and i'll go to zero right the zero is visited right so it's going to be discovery to be a back edge right it's visited so we're going to be discovering that would be zero right so two will be zero and a one was actually going to be zero right so we find zero is another one that's not one it's a zero is another head right zero because it's back to zero so zero is the head and three is the head so basically we're saying whoever is the head right zero is a head three is another head so whoever is the head needs to well like a link between it and enough whoever linked to three and then three have many links right has many links let's say one two three a back link if we always go from small to large right from each node or go oh it goes small to large and from large to small is always a backlink right then if we find it ahead that means everything under it is like we traverse and then we find something we go back right so one link go back right so that's the path right we'll have a node and we traverse first whatever traverse we do and then eventually if something linked back and once you link back and update everybody so they all link back to that one right they'll link back to that one now that one if it also links back if that one is not a head which means it also link back that means it's not critical it's not a starting point so we need to find the head will be like nothing goes to it yes what does a head mean head means nothing goes to it head is the head right nothing goes to it so that's the key we need to find the head of during a dfs traversal we can find the head all right and then we pick the head then the link is the head goes to some something but what exactly is the link right what exactly is the link i mean we have a head we know that nothing goes to the head is the start of the current whatever it is right a hole goes to the head now we know when we find a head that from that node when we traverse they always go to the bigger ones so it's only going to be the one that's smaller than it that's the note and link to it but if there are two link into it then are all the nodes that's smaller than the head are they going to be all considered as critical note so if it's a head right the criteria of being ahead is nothing is it cannot reach anything before it that's the criteria level of being ahead is from whatever traversal from the head it cannot go to anything above the forward right so if there's any link right is any link from a node before my current note that towards me then that is a critical link because there's no other way for me to reach that to reach above me yes i think i know how to use tarzan this is not correct uh we need to keep this right and then i'm not looking at implementation so i'm trying to solve it myself we're going to use dfs right so we have a node right and then we're going to have two we think we're going to have a disk it's going to be uh zero times n right and then also low is going to be uh zero and then starting so same and then and have a node right we have the node and uh that's it the emphasis is just a node i mean we need visited right we need visited equals just the set and this one doesn't return anything okay um we can sort it that will be better anyway so we're doing a node right so node and not visited before the visitor node and then we did when we visited node oh we need a count and we're going to count so we need a step is going to be int node is actually going to be in as well right so we have a step in undo disk node equal to step okay whatever step that it has to take uh yes whatever step we have to take and then after that we're going to check its children so the child in graph node right check for the children if its children has been visited before by if child in visited and then of course visited that no right if the child is visited that means it's a back edge going backwards so we can say uh when we first visit right we're gonna say listen and a low note costly for the step when we first start when we first visit a note that's the case and if child has been visited right then low note should be the minimum of low note itself and the child but the child has to be discovery child because we only allow one back edge right and then they'll group together that's like a whole group if we need another one and i just messed things up one group one back edge about else if child has not been visited right then we're gonna do dfs child step plus one right dfs the child after finished dfs then we're gonna upload no it's gonna be minimum my low and my child's low right then we end right we terminate now we're going to do dfs when starting with zero and a zero step that's what i like zero steps and after that the disc and low will be populated i'm actually going to take a look no just keep going now we want to find out the head right ahead so we just take a look on going through distant low and see uh which one is the head it has to be disk and the low will be the same so when i say 4 i in range and if i this guy equal to low r and i is not equal to zero because we start from zero cannot count zero right then that is a head that is head that we have to take care of now the c right then we can have a result right then we just see all the nodes that's smaller than me that's connecting to me so i'm going to say right on the sort we'll just go circle that's fine so we just say uh 4 3 in graph i if pre is smaller than i then rest.append pre right and we'll go through all this now i'm going to return this run it dict has no ad visited is a set by dick now we pass this try at least we fail only first i think it only returns empty set okay that's fine we uh take a look at what we have so i'm going to print disk and print low okay something is not correct uh that's i think that's this one right take a look so we have from the zero right so zero and then we'll go to one right and from one we go to uh two and three okay the discovery is fine now they all connect back to zero right but three the one can connect at zero so one right and then one another two go back to zero that's a back edge and a one combination zero true this is all correct put three and one will go to three right and while i am at three my low note shall equal step which will be two right and then a child oh it also can it cannot be parent uh yeah because i am taking into account the parent no like the back edge cannot go directly back to parent how do i enforce that uh i have to do a parent there right let's do a parent so parent pa parent i know karen is going to be linked right then if child uh invisitive and child is not equal to parent then we do this else actually if child is visited no look at this aleph child not invisible that would do this so if child is equal to parents that we don't do anything and when we visit this it's going to be child right that's the current node parent is the node right node and uh that's that so dfs let me just pass the minus one right that's parent whatever it is right and let's try this one now we pass right and try all these they all pass i want to try the big one the giant one this one see if it can run judge in finish take 336 milliseconds take a look uh this is based on the hint of using tajons i'll go all right let's see if this one pass pending judging my come on oh my god oh it's accepted how long does it take oh wow that's not bad at all why am i laughing i didn't solve this uh i need to give it like it should be success fail and this will be like uh cheated let's achieve it well this is not my solution i didn't come up i did not come up with this all by myself the i got stuck and the hint suggested that i take a look at tarjan's alcohol which i'm going to link this article and then it's good right tajong's article tarzan's article is algorithm the central point of tarjan is that we find the head of a graph we find the head of the graph the definition of a head in a graph is that is a node which uh can not which i should say that which is the root of the is the root of which is the root of the subsequent of off as a root of the sub that this node does not connect back oh yeah this node does not connect yeah it's uh has a rough head definition of a head inside a graph is a note which does not have any back edge towards a node that has been visited before in dfs uh yes in other words a head is the root of a sub-tree inside a graph sub-tree sub-forest whatever you want to sub-tree sub-forest whatever you want to sub-tree sub-forest whatever you want to say inside it's actually a sub tree inside a graph from the head we can only traverse forward we cannot traverse backward uh not counting the edge leading to the head yeah okay that traverse back with other edges so in this problem tarjan is used on directed use on dag we can apply although our although though our graph is undirected we can simulate it as a directed by traversing from small node to big node right in other words a forward traversal is follows an edge going from a small to a big node back backward a backward edge is from a big node to a small node using tarjan we create two arrays one is called disk discovery and the other low the lowest note that can be reached uh with one back edge it is important to stress that only one back edge is allowed to traverse backward when computing the low array yeah and one can be allowed while we're computing the lower right once we finishes dfs we have a we will we populate the disk and low arrays right to populate these two arrays we each the i value in let's just say disk i is the number of steps needed to reach i in the dfs low i is the uh is the most previous node right the most previous node is actually not the most previous node it's the let's yeah it's another is the step is the number is the step to reach the most previous node is this points to the is the value of disk j where j is the most previous node reachable from i using one back edge with one package a head is a node k where disk k equals low k which means uh which means from node k we cannot reach any other node before it our goal is to find all the head node k in the given graph and the critical and critical edges are the edge connecting out the edge directly leading from a smaller node to k run the o n it's actually the dfs is on and this is check everyone actually is not longer than om because well because we have find it and then we go through the nodes actually i shouldn't say i don't know this is complicated to calculate this i just say the run time and time gets us 2 1 88 milliseconds surprisingly give us an nine 89 ranking that's pretty hard i mean admit it i don't think this is a now this is like a hard question i'm pretty sure this is a hard question this is a good article though i shouldn't say this took me a while to understand i thought like i've done something like this before like how come this is a heart like i don't understand but yeah it's a hard one i bet there are better solutions than this oh yeah i've done this before oh my goodness oh i had a better wow no way i started 21 right couldn't it couldn't do it just couldn't do it and then tried it again on 25th couldn't do it i think i gave up i did it try it again what language all python and two years later yeah i think this is i think this one just for fun why did i do that i don't understand all right done it before but i can't do it dfs detailed ah i remember this question all right let's take a look find out this theorem on a comment graph an edge is a critical if and only if it is not in a cycle yes so if we know how to find cycles and discard all edges in the cycles then the remaining connections with a critical edge that's true how to find edge of the cycle and then remove i kind of bring back memories i already liked it see i bring back memories a fine and we find cycles if we go back to a node that has been visited before then we have the edge i know we cannot have it then we have a cycle so whether or not an edge is in a cycle if we dfs and then we go back we hit a note that we've seen before and then those edges are all not good right define rank of a node but that's often known during dfs oh that is the disk discovery only the nodes on a current dfs path have none special ranks in other words only they know that we've started visiting but haven't finished visiting high ranks have started visiting but haven't finished it right if node is not visited yet has a special rank if you fully completed the visit of the node it has a special rank okay right help us remove imagine you have a current path of length k doing i s the nodes on the path has increasing rank from zero k increment by one surprisingly next finds a node that has a rank p whereas before what does that happen aha you find a node that is in the current search path that means congratulations on a cycle yes but only the current level of search knows it how does the upper level of search knows it so backtrack of the return value returns minimum rank at five during the step of search from node u to enable v if this returns something smaller than equal to the rank u and you know this neighbor helped it find the cycle back to you or use ancestor so your nose can show the scotty edge you to v which is in a cycle after doing the efforts all edges in cycles are discarded so the remaining edges are critical uh how do you discard again dfs of back depth by the scar and the scar we have the right of the sky the function for this car know the neighbor oh it's this plus this we have using rank reordering one array the rank is very different from maximum result by collecting non-critical edges result by collecting non-critical edges result by collecting non-critical edges after the dss in my current search okay uh it's still slightly different from my understanding right what i did is q arrays and then i find the low and we find a head right so i'm not making any i'm not removing anything i'm just finding the head and after i find the head i declare that the ones connecting to the head are the critical edge he uses rank right so as we go through we'll increment the rank visiting or visited rank now it's larger than zero then either visiting or visited so initially it's a minus two and then i've got a depth so let's rank the depth main back that's as n and now we'll go for the neighbors if ranked neighbor equal to that's minus one that's the previous one special value in case that's equals is zero right that's x minus one that's the that's your parent continue that's why i have to pass patent as well and then back depth equals dfs neighbor so the neighbor and that's plus one so i want to know the back depth uh yes the back depth just like when we hit someone that's smaller than me right and then we say the back depth is smaller than my current depth which means my for my neighbor i can go to a node that's smaller right smaller i find the minimum depth actually yeah find the minimum depth and then if it's smaller than the depth then that means the from node to my neighbor no to my neighbor and i can relate to something so it's in the within a cycle so i can remove it okay and then the main depth of me will be the depth of my child so i as one more note i go to my mini child and they can all go back right they all go back if they can then i just pick the smallest one and that means this is where i can go if i want to go back right then right node equals to n and return minimum depth and as it goes through it's discarding that's the scotty i didn't even consider the this needs time as well oh but it sets it to map that's why but he needs time to do that's oh well okay i see what you're doing that's using rank to find very well target so if you want to do tajin while doing this how will you do it well i would say i can do it here as well right so if child in visited yeah if a child is visited and it's not a parent that means that's a loop yeah we have a loop right so from a node to child and the child is then from node to child they would go back everyone know the child that is so from a note i have a child going back right then that link is in the loop so i can just discard it right and uh i still record i still do i still record so i go back right and then if i go back and go from a current node then i go backwards right i go back then i say this node i deleted all right how about my parent like if i go here if the children have not been visited i'll visit it after i visit it then i need to check its it's no yeah it's low and check it's low and uh yeah check is low and the low will tell me uh which one that i has done before right the child so like if i can return i need to return what do i need to return the earliest node that i can return back to right so if i can return back to this node that is returned that value so i can say here i can return the load of the child which is the earliest i can reach and then i compare these two as the load of the child is uh the low current node right a lot of my current know load of my current knowledge which one i can reach and go through every one of them if i can reach but i keep going until i find the smallest and then i just remove it if it has filleted i remove it immediately if it has not been visited if as visited right then i can just go say low note can equal to discovery child but now in the current case it's a loop right it's a loop so i can actually say low child it's fine i can just say low child i mean it's different from tarjan now right i can just remove it but i'm gonna update my current low note i mean as long as my low note is now i need to know where is the earliest note i can go back to from me but has to be this child though it has to be disk child minimum depth right the minimum i can get back to from the dfs from the child each child we can go back and it depends if we have visited or we have not and if they're visited and trying to find like the difference between these two we have steps right and then what we're doing is every time visit no we increment the step and then if we find a node we have visited before but you need to know how many steps it takes to reach there and that's the disk right that's the disk is how many steps it takes to reach there and once we find that we remove the link so we know we the child is go back there's a loop so this one we don't need anymore so we remove this right we remove this and we say from my current the earliest i can find is this right then we go into everyone so we find each note the earliest note i can reach back to right the earliest i can reach back to from one back edge the earliest i can reach back to so i know this and then here everyone if it's yeah that's i think i'm gonna implement this one more time graph and mark the order let's record how far but i'm going through you must something like the lowest order that can reach every time you find it you can remove it main of the phone but it's a next function i'm currently stuck in this so i will try to use that person's solution for this yeah this one shall be in the hair uh at the list now this is a nightmare but even if it's nightmare we are going to do another solution it's expected right i know yesterday i said that today might be hard it is hard okay so basically copy and paste almost exactly the same thing but just with you know minor differences so i have the graph right so we're going to call it the we can reach back that's just the low the lowest we can reach wow no we're gonna return value with the lowest so we can reach from each one and then we're gonna do is just steps discovery yeah that's the discovery right and we do visit which is fine and we need to turn connections into interconnections when they remove you remove connections into a tuple right into a tuple how do we turn that into a tuple resolved uh no can you set rest.append.app rest.append.app rest.append.app uh i'm gonna say min and one and two and one all right oh right now step right so we're gonna do is uh no equals this that's good we don't need this is it not it's good so child and child if child injury that child is not equal to parent right then we say what do we say so it's visited all right so we say min step the back that reach right back to reach can be m right so travis visited then we say back reach equals min and discover child and when it happens well honestly uh that's actually not how it's going to be because i think if child and child is not equal to parent right then we say child back h equals this child right else if it's not visited then we are going to retur a child back reach equals dfs no available if a step current step can reach me is smaller or equal to child back age right which means a child can either reach myself or i can reach higher that means loop right then we can remove and say rest dot remove uh from me to my child right so remove from me which one is me no that's me node and child right so we're gonna remove this and back reach my back reach actually why do you do a hyphen back which can just yeah my back reach is equal to min uh backreach and child about breach once we're done we're gonna return my backreach right child in this i'm going to say if child equals parent continue right and then they say if i give you this if child in visited else gonna do this dfs i want to change the name the child back reach and visit back all back which can be back right back this is the earliest uh this is a step uh where the earliest no can be reached hard to explain what this path is back is the number of steps right the number of steps to reach the earliest uh the earliest node reachable from the current node i make sure that this explanation makes sense so if it's equal to parent now we don't do it otherwise child back if your child if child is visited else equal to this right uh and then run this and then come back and we'll never turn a list of s and that's it all right so in the solution too and it's ah because i haven't deleted this either fail uh okay that's that makes my understanding is not 100 correct that's fine let's just take a look i think i included everything nothing is removed step a smaller you go to child back well have we even hit here i think we hit here no we haven't even hit here why is that so this node you always go to the step right and then i keep going back as n then for each child back is going to be if child visited before else we're going to do dfs right look at the child and after this is done let me check my current stuff if it's smaller oh how no large equal actually even better child staff that's smaller equal to calling stuff wait what the hell right child back how come both something is not right what oh my god i forgot it's called dfs ah we have issues here oh yeah so node and child has to be min no child max mode yep and then this has to be not like this uh actually that's fine list are or are invest there we go yep i actually like this one better it's cleaner visited result remove loop exists right you can remove current edge i'm pretty sure even if i return a rest a list rests it shows shall make sense anyway so uh when i write something here this is a reproduction of the answer in this post i'm pretty confident that this one will work right here it has similar sense as tarjan but better but i think is better suited for this problem basically we dfs and if any node can lead to a node that has been visited before any child right any child can lead to has been visited before then we are confident that there is a loop that the edge from node to child current node to child is in a loop and it must not be critical we remove it and that's it that's the essence of the solution very neat i like it a lot so we're gonna do i am not going to memorize all this what i think i can do is i mean the idea is quite neat it should be able to figure it out right shall be able to figure out that's about the same time that's okay i mean and she'll be able to figure out basically what it does is just to detect whether a loop exists if a loop exists we simply move the edge all right i'm gonna change today's title to cheat it but it did do it uh took us a long time almost three hours but it's not saturday it's good for a little bit brain exercise all right that'll be it for today i'll see you guys tomorrow adios
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
1,178
okay guys let's take a look at lead code 1178 number of valid words for each puzzle so the prompt is we are given a list of words and we're given a list of puzzles and for each puzzle we're going to output one number for each puzzle and uh what that number is going to be representative of is the total number of words which meet the conditions for that specific puzzle and the two conditions are the word must contain the first layer of puzzle so if you look at this puzzle the first letter is a so in order to be considered valid the first condition is that the word over here in this list must contain an a and also the second condition is that for each letter in word that letter is also in puzzle so for something to be valid for above ease the word in this list must con um yeah so like a s both a and s must be in abovies uh which is not true for able to be considered a valid word um a b l and e must also be in above ease and that's not true right so i think the only one that worked for above ease was aaaa because a is all four letters a are in a bubbies so what's the naive approach then the naive approach is just for each puzzle um you would just go through each of the words again um and check if those two conditions are meant so that's n squared time so will that work um i don't believe that's going to work because our time constraints are 10 to the 5th so usually when something's 10 to the 5th it's not going to be able to pass n squared so what's another approach that we can take um it's probably not that intuitive but uh the approach is we're going to first create a frequency tuple slash count slash bit mask i'll kind of explain the frequency count and then how you can turn it into a bit mask but basically you'll have a frequency tuple a 26 index tuple that you know stores the number of frequencies of each character um and you'll generate that tuple for each of these words and then you'll go through each puzzle and you'll create all the possible sub sequences slash subsets for each puzzle and the reason this is not going to time out is because the max length of a puzzle is seven so this will never grow so if you want to generate all the subsets for something of length seven that's two to the seventh right so two to the seventh is 128 so we can actually treat 128 as a constant so if we look at that then it'll be so for each puzzle we'll have to do 128 and then the length of the puzzles is 10 to the fourth so our time complexity will look like 128 times 10 to the fourth which will be fast enough to solve this problem which is just like of n i guess if you will and yeah so let me go to the whiteboard and kind of show you uh the approach so let me kind of show you um so basically we have a list of words we have a list of puzzles so word one word two word three blow up puzzle one puzzle two blah okay so for each word we're gonna go through this list once and we're going to generate the frequency tuple for each word uh so this is just oven time right so you'll have a frequency tuple that looks like oh jesus how do i spell that so wrong so tuple is you know the number of a's or i guess it'll just be whether or not that a exists or not it does they don't matter it doesn't matter how many times the a is contained in that uh word right like you see that four a's doesn't mean you need to have four a's and above ease as long as there's an a in above ease and vice versa then it's okay so it doesn't really matter the frequency but basically you'll just mark whether or not you have that a or not whether or not you have that b or not whether or not you have that c all the way until z right so that's what this tuple will look like but a better way to do it that will take less space and just be more efficient overall is to use a bit mask so in my previous problems what i did was um i did bit mask a few bitmap problems in the past uh two or three videos but i used the bit mask for a different purpose right in those videos i was marking uh i was marking which indexes or people id numbers were being used or bike id or whatever right so this was the zeroth index first and next second and next third and next fourth index right that's what this bit uh this that's what this mask was representing in this case we're just going to do pretty similar a pretty similar thing except uh each one is going to represent a different letter right so um right so we'll essentially have 26 bits um this will be as long as 26 blah right so that's what this new bit masking is going to represent in this problem that's how we're going to use the bit mask in this problem okay so once we've created a bit mask for each of these words um you know we'll have some sort of map that has the mask right the key is the mask and then the value is the number of times the number of occurrences of that mask right because we could have multiple words that are the same right this could be these two could be the same word so we should mark that in our mask twice um because we want to count the total number of words that match that condition so if two words match that condition we should count both of them okay so that's the first step right so we go through this list in oven time and create the masks okay second step is we're going to go through each puzzle and we're going to generate all 128 subsets so you know as we generate the subsets let's say maybe this subset was valid so we returned one here this one wasn't valid so we returned zero it wasn't valid was valid right so something like that so this so there's three ones so this would return three for this uh um puzzle right so it would in your final output you would just have a three right so you do the same thing for p2 right you'd go through all 128 subsets subsequences whatever and then count how many were valid um or the way you count if it's valid is you just check if that masking for this subset was in your map right because we generated all the masks for all the possible words in word in this word list right so you just check to see if the current masking matches something in the map if it does then that means it was valid okay so let's see how do you generate the subsets that's pretty it's a pretty standard thing uh you know that's just kind of like a take or don't take uh kind of approach i guess i can draw it out for a better visual but let's say you have the word phone or something phone uh pretty much you'll just have some recursive loop or some recursive function going through and you know you'll have a pointer i starting here and you can either take the p or you don't take the p let's say you take it so your current string is p right list but we'll be representing this string as a mask right we'll be representing this as a mask so you know you'll have your mask is looking like bit you know blah this is the p position then blah okay and then let's say now you can either take or don't take this h now so let's say you don't take it so your bit stays your bitmap stays the same then you can go here to the o you can either take it or don't take it let's say you take it then your o a c e f g a b c d e f g h n o p so o would be here so yeah basically you get the point so you'll just update the mask um if you decide to take it and you'll you won't update the mask if you don't take it right so that's just creating subsets is just uh you know you always have two possible uh choices right you can either take the p or you don't take the p and then the next one you can either take the h or you don't take the h right um all right so yep that's why there's two to the seventh equals 128 different possible subsets uh subsequences right so yeah um let's see i guess i'll go to the code now um oh one more thing i guess i should talk about just the general idea behind bim mask if you missed my other videos you should definitely watch those because i explained bit mask twice already but for those of you who want to just get a quick reminder of how it works in order to check if a current bit mask um to check if a current bit mask or no so i guess we're not even checking we're only using the or in this situation in this uh problem so basically uh in order to insert a so let's say you have a current bid mask of 0 1 0 and you want to insert so this will represent that you only have a c right a b c this is what this represents you only have a c and then let's say you want to insert b so you decide to take a b and you want to insert it into this uh spin mass string right what does the b look like the b representation is 0 1 0 right so that's what represents b and a way to figure out how to create this string in the first place is to just do one left shift and then you'll take the order of the current character uh minus the order of a right so the order of b minus the order of a is one right so you do one left shift one and you know so one left shifted by one will give you this right so you'll have zero one zero that's what this is okay so this is going to be your friend this is the formula you're using to find the uh um the bind the bit mask string right in the other in the previous problems for campus bikes and this uh whatever question the number of hats you did like one left shift the bike number or something right um in this problem the way to generate that mask is doing this one left shift by order of character minus order of a okay so now once you have this masking for b the way that you will insert it into this bitmask with the c the way you'll combine these two is you'll just order these two together this is the ore it's a pipe and so zero one zero ordered with zero one zero that gives you zero one zero all right so now this zero one zero represents that you have something at a that represents that you have something at c and b okay let's take a look at the code real quick so should be pretty straightforward so the first thing we do is we create a map uh and then we create all the maskings for each word in this word list right that's what's happening in this first loop here and we add it to a map and then we'll go through for each puzzle will generate the 128 different sub sequences subsets whatever right so actually one thing to remember is that of the two conditions one of the conditions is that the word must contain the first letter of puzzle so we might as well just start our masking with that first letter of that puzzle right so for puzzle zero that's above these right so a we should just start the mask with an a um and same with a broadies we should start with an a blah and same with gas w we should start with a g so i'm just putting that i'm just kind of presetting that mask to have that first character and then also setting the index to be one because we're already processing that first character right so instead of doing like the take or don't take at the zeroth index we're always just going to take the 0th index because we need to have it and actually for some reason it doesn't even work if you um if you don't take the 0th index so um yeah so that's why i have this line here and then you know i go into the actual recursive generating subset this is pretty straightforward it's like a very common leak code pr question where you generate all the subsets basically you know you just go through for each index in this string like above these you just have a index and once you reach the end of the index then that you terminate so that's what's happening here but also when you reach the end you should also check if that current masking is in your map if it's in your map then return the number of words that had that same masking and then also here's the take or don't take and then here's the take right if you don't take then you're you just move the index one and don't change the mask if you decide to take it then you know you have to update your mask to insert that character into your current masking right so that's all i have for this video hope you guys learned something new hope you guys enjoyed it uh tell me if you have any feedback for me tell me what questions you want me to answer next and thanks for watching
Number of Valid Words for Each Puzzle
valid-palindrome-iii
With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied: * `word` contains the first letter of `puzzle`. * For each letter in `word`, that letter is in `puzzle`. * For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while * invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle). Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`. **Example 1:** **Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\] **Output:** \[1,1,3,2,4,0\] **Explanation:** 1 valid word for "aboveyz " : "aaaa " 1 valid word for "abrodyz " : "aaaa " 3 valid words for "abslute " : "aaaa ", "asas ", "able " 2 valid words for "absoryz " : "aaaa ", "asas " 4 valid words for "actresz " : "aaaa ", "asas ", "actt ", "access " There are no valid words for "gaswxyz " cause none of the words in the list contains letter 'g'. **Example 2:** **Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\] **Output:** \[0,1,3,2,0\] **Constraints:** * `1 <= words.length <= 105` * `4 <= words[i].length <= 50` * `1 <= puzzles.length <= 104` * `puzzles[i].length == 7` * `words[i]` and `puzzles[i]` consist of lowercase English letters. * Each `puzzles[i]` does not contain repeated characters.
Can you reduce this problem to a classic problem? The problem is equivalent to finding any palindromic subsequence of length at least N-K where N is the length of the string. Try to find the longest palindromic subsequence. Use DP to do that.
String,Dynamic Programming
Hard
680
682
Hello Everyone Welcome Back To My Channel Suggested Winters Shraddha Problem Special Game Very Basic Problem So What Were Given Switch Off To Tips For Baby Doll Game Witch Can Choose Game Consist Of Several Rounds Vyas Ko Off Pass Round Me Feature Right to the very minimum cream user name here giver list off and above and where novel came i is extremely operation you must apply to record and this ruin is falling on to index also fixed like share five to design teacher like basically which number 120 News Course Ki Beni Aur Badi Shaan Sunidhi Operation Means Responsibility * Add Defiance Pura Juice Dhundh Recording News Ko DSWO Previous Forever Previous Ko Roshni 200 Test Wickets In The Record And Scene That Just To Remove The Previous Ko Vatavriksha Courier Shatrughan Ki Aapke Anyit Last Minute Ghanshyam of all schools will develop ok baby I love you understood problem native with this test k basically overtime to ushe hai tu english me behavior qualification vector and elisto and list in python and sans susi pimples se vector and every maintenance costs in witch specific storing Scores 180 Initial Want Me To Telling That Like Share Bhi K Time Teacher And Fire Brigade 285 And Also Like And Keeping Size Available Which Will Be Keeping Abhi Winters Size Of The Current Vector Everytime E C Every Time E Don't Want To Do A Calculator Angry Is Function of the time taking a variable size issue so bank also f5 right will viewers singh samrat vikramaditya juice course festival justin 2005 will get mixed school and events like this that your nine what if you agree toe connect element is too short toe were converted into A teacher and student in the forest service between size just heard nine wickets in two also total seam is diet invalid previous to remove ink from record to water 10 minutes later it is easy will remove that sombody else seams remove diameter to fennel and will be removed S will be removed from twitter and sisters remove and size reducer 210 size will know welcome white hai naveen ko hai naveen reddy get some sleep set double previous ko breaking news ko so what is the previous ko reverse ko run scorer of science - one part frontal Element scorer of science - one part frontal Element scorer of science - one part frontal Element Size Minus One So Its Last Index Will Be Site - Point Only Vilaspur Site - Point Only Vilaspur Site - Point Only Vilaspur 788 Debit 10 And Distance Ilaaj Is The Force In The Stands Outside Ubuntu On Is Devi To Class Twelfth Class Welcome Vipin * * Sham The Best Quotes To What Will Be Vipin * * Sham The Best Quotes To What Will Be Vipin * * Sham The Best Quotes To What Will Be The Best course of science - Vansh The Best course of science - Vansh The Best course of science - Vansh Vilaspur and second last co 20 co raw and ka size - do not treat second class co 05 e will size - do not treat second class co 05 e will size - do not treat second class co 05 e will vote for co sudesh vij unmute co and used to win into a good news for recording user co software engineer Main Anil Incremental Size Hai Main To Shiv Vihar Travels Darkness Operation Here And If You Know What Mintu Return The Sum Of All Schools Andar Tight From One Side To The Other So Here I Will Sadol Isko 500 600 5032 Ki Rahit Very Simple Problem No Soldiers Were Traveling and getting what operation from this recording also we are doing turn off the phone light that sufi leadership former very good factor in tally basic list double in the respective taking size give us into its operation in dahisar twitter and defeat in addition night shift solution Tubelight The Best Course And Women To Site A On This Day E A Souvenir That Double Previous To Editing To The Scores And Agreements Signed A And Effective CSOM Reducing Size Alarm Copied From Distant From Them Away After 12th Class Element And Opted To Here Please For Two Right Then Member And In Its Will Comment It Na Here Of This Loop Condition Doc Features Of Which Will Come In And Out Ise Teachers 852 Example Oil Just Convert String Into Tears In Ets2 Function And Getting Reservation 10 Course Victor Sans Element Coming Swat This Doing And Calculating Samrat Morning-Evening With Me To Calculate AB Samrat Morning-Evening With Me To Calculate AB Samrat Morning-Evening With Me To Calculate AB Traveling And Isko Tractor Ke Lekar Excited Solvent Amazon Who Actor And They Will Find Some Bandhe Written Test Torch Light I Hope You Understand By The Which Were Very Basic Problem Solved CEO And Share What They Are doing his meeting with sacrifice right which bacterial taken so it will be chief an order besides being of vector and damini time choli hai ki virani vishnu to eighth bhi liye time and space 50% using back to off and on 50% using back to off and on 50% using back to off and on 111 problem and approach but he What I need at this point is I will help you for this site and subscribe my channel and thank you too
Baseball Game
baseball-game
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following: * An integer `x`. * Record a new score of `x`. * `'+'`. * Record a new score that is the sum of the previous two scores. * `'D'`. * Record a new score that is the double of the previous score. * `'C'`. * Invalidate the previous score, removing it from the record. Return _the sum of all the scores on the record after applying all the operations_. The test cases are generated such that the answer and all intermediate calculations fit in a **32-bit** integer and that all operations are valid. **Example 1:** **Input:** ops = \[ "5 ", "2 ", "C ", "D ", "+ "\] **Output:** 30 **Explanation:** "5 " - Add 5 to the record, record is now \[5\]. "2 " - Add 2 to the record, record is now \[5, 2\]. "C " - Invalidate and remove the previous score, record is now \[5\]. "D " - Add 2 \* 5 = 10 to the record, record is now \[5, 10\]. "+ " - Add 5 + 10 = 15 to the record, record is now \[5, 10, 15\]. The total sum is 5 + 10 + 15 = 30. **Example 2:** **Input:** ops = \[ "5 ", "-2 ", "4 ", "C ", "D ", "9 ", "+ ", "+ "\] **Output:** 27 **Explanation:** "5 " - Add 5 to the record, record is now \[5\]. "-2 " - Add -2 to the record, record is now \[5, -2\]. "4 " - Add 4 to the record, record is now \[5, -2, 4\]. "C " - Invalidate and remove the previous score, record is now \[5, -2\]. "D " - Add 2 \* -2 = -4 to the record, record is now \[5, -2, -4\]. "9 " - Add 9 to the record, record is now \[5, -2, -4, 9\]. "+ " - Add -4 + 9 = 5 to the record, record is now \[5, -2, -4, 9, 5\]. "+ " - Add 9 + 5 = 14 to the record, record is now \[5, -2, -4, 9, 5, 14\]. The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27. **Example 3:** **Input:** ops = \[ "1 ", "C "\] **Output:** 0 **Explanation:** "1 " - Add 1 to the record, record is now \[1\]. "C " - Invalidate and remove the previous score, record is now \[\]. Since the record is empty, the total sum is 0. **Constraints:** * `1 <= operations.length <= 1000` * `operations[i]` is `"C "`, `"D "`, `"+ "`, or a string representing an integer in the range `[-3 * 104, 3 * 104]`. * For operation `"+ "`, there will always be at least two previous scores on the record. * For operations `"C "` and `"D "`, there will always be at least one previous score on the record.
null
Array,Stack,Simulation
Easy
1720
459
welcome back friends today we are going to solve in code uh problem 1227 repeated substring pattern so this question is one of the frequently asked questions at google and amazon so please make sure you understand this question and so let's go through the description so given a non-empty string check if it can given a non-empty string check if it can given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together you may assume the given string consists of lowercase english letters only and its length will not exceed 10 000 right so uh this is the constraint so uh repeated substring pattern is as you can see for example in this string this pattern a b is repeated right so you can we can construct the string by repeating a b right so we have to return true here but here as you can see we cannot find any pattern which can be repeated here because a cannot be repeated a b cannot be repeated so we have to written false so let's take one of this example over here and we can discuss how we can solve the problem so uh as you can see like this is the string that is given to us so what we will do its length is nine right abc so what we will do it's like let's say just is n is equal to nine so we will uh have a for loop and our for loop will actually like uh do n by two right it will start with n by two which is equal to four here right so it will cut this string into four characters basically so it means that this is the four character string right abc a and it will check if four is uh can make uh you know uh divide this string into equal parts so 9 cannot divide 4 into equal parts right so we will just continue and we will decrease our i so i was 4 in the beginning so now i we will decrease to 3 right so we will now choose another substring which is now 3 9 can be divided into equal parts of 3 right so this one is condition true so now we will try to check if this three can be a repeated substring right so we will take this three abc and we will look through this uh string and we will try to like append it like then we what we will do is we will first we will get abc right first three means then what we will do is we will mult like we this nine divided by three is equal to three so it is three parts right so we will try to append it three times right basically and every time we will check if it is forming original string so now abc we again appended abc and now it's not original string so we will continue again we appended abc now here so now uh we found that the original string and this uh string which is formed by repetition they are equal string so in this case we will return true if you know that does not happen let's say after appending if it does not match the original string then we will just return false basically that we cannot form the original string and then we will still try keep checking you know so we have checked i first with 4 then with 3 then we will decrease the i to 2 right after that and after that we will decrease i 2 1 so 1 is our last point after this we will not decrease for example if we have a string let's say a right so this is a length 5 right so this is n is equal to 5 in this case so we first division will occur like 5 by 2 which is equal to 2 right so i will start by dividing this string into 2 basically so we will divide this string into 2 which is a now we will we cannot make equal like a partition with the 5 and 2 right because 5 is not completely divisible by 2 so our i will decrease to 1 and in this case we will just get this first a right i is equal to 1 means and then we will keep repeating this 1 so we will keep repeating one five times right and then we will form the string a and then we will just return true in this case right so that's why our i will keep decreasing until it reaches one so that is what the approach is to solve the repeated substring uh pattern problem so let me show you quickly the implementation here so we got the n which is length of a string and then we will start of our for loop which is i will start by n by 2 right n divided by 2 and it will continue until i is greater than equal to 1 we will decrement i in that point right and this one is just for the i was debugging but you know here we will check if we can make equal parts right by divi division of i right for example if i is equal to 3 in this case then only we can make equal part because 9 divided by 3 is equal to 3 right so it can make equal part but if we are using 4 then 9 divided by 4 cannot make equal parts of the string so we will not consider 4 in this case basically so that's what we are doing here by checking and after that we will just create the divided parts variable so we will know how many parts we are dividing for example if it is a nine length string and we are using i is equal to three then we will get three basically equal division divided parts will be three in that case and then we will substring zero to three right zero to i is equal to three then we get the substring and we will append that substring three times here right so abc that's what we are appending into string builder and then we will compare if it is forming the original string here right so that's what we are doing if it does not form then our i will decrease and it will try with a two length two basically right three we tried then it will go to two and then it will go to one like that it works basically and if we cannot find it in any of this sub strings then we will just written false at the end so let us just take a few examples and we can try so abc so this is the one that we just was discussing so as you are seeing uh it is giving us correct answer true and as you see i will first divide by two it will go to four so four it is not making equal parts so it will try with three right because four did not make equal parts so it will go and it will decrease it to 3 so similarly if we try another string so now this is 5s so if you run the test it will now again it is true and it will see the first it will try five by two is two so it did not make equal part so it will just decrease to one so that's why uh it is true so our solution got accepted by lit code so uh if you like this solution please hit like and subscribe to the channel your subscription will be really helpful so it can reach to more people and they can also use these videos for their preparation in java j2 interviews so please try to check out the different playlist for lead code solutions as well as java interviews there are lot of playlist on my channel please check it out and please subscribe to the channel that will be really helpful thanks for watching the video
Repeated Substring Pattern
repeated-substring-pattern
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. **Example 1:** **Input:** s = "abab " **Output:** true **Explanation:** It is the substring "ab " twice. **Example 2:** **Input:** s = "aba " **Output:** false **Example 3:** **Input:** s = "abcabcabcabc " **Output:** true **Explanation:** It is the substring "abc " four times or the substring "abcabc " twice. **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters.
null
String,String Matching
Easy
28,686
338
let's solve lead code 338 counting bits so the question goes like this that you'll be given an integer n and you need to find for every number between Z and N in their binary representation how many ones would be there so if say for example n is2 so you'll need to write return how many ones would there be in zero how many ones would there be in one's binary representation how many ones would there be in two's binary representation and return that in an array okay so zero index would have the number of ones in binary representation of zero one index will have the binary representation of uh number of ones and binary repres representation of one two's index will have number of ones and binary representation of two say if n is five then the same will be done for five number 5 + one numbers which is six five number 5 + one numbers which is six five number 5 + one numbers which is six numbers right 0 1 2 3 4 and 5 to solve this problem one way is for every number between 0 and N you figure out take the uh take the binary representation and add all the ones you get the other way is there is a trick to this the trick is that if You observe in here right there for every number for every even number it has the same number of ones as you have it in the half of their so four will have here four has got one so does two also has got one so does zero sorry that's it yeah so two has the so just check for the half of it okay and whatever the number of once the half of it has got you can use the same number so in case of here for index 2 if I have one for index uh for index 2 and for index one I have one that is because half of two is one so at index one I've got one right so that holds true for 2 4 8 and so on 8 uh after8 that would be 10 12 you just take half of it and find the how many ones are there and half of it and the same number of ones would be there in that for the odd numbers the same you can do the same take the half of it floor it because half of three would give you 1.5 but there's no 1 .5 so you take the 1.5 but there's no 1 .5 so you take the 1.5 but there's no 1 .5 so you take the one okay whatever you get at one and add one to it so for three since the since half of three is 1.5 I'll Flo it to half of three is 1.5 I'll Flo it to half of three is 1.5 I'll Flo it to one uh the number of ones at index one is 1 so the number of ones at index 3 will be 1 + one number of uh ones at will be 1 + one number of uh ones at will be 1 + one number of uh ones at index 5 would be half of five gives me 2.5 but I'll Flo that two has got 2.5 but I'll Flo that two has got 2.5 but I'll Flo that two has got 1 so 5 will have 1 + 1 that is two 1 so 5 will have 1 + 1 that is two 1 so 5 will have 1 + 1 that is two 1es 7 will have half of 7 that is 3.5 1es 7 will have half of 7 that is 3.5 1es 7 will have half of 7 that is 3.5 I'll Flo it to three has got two ones so 7 will have 2 + 1 1es that is 3 ones so 7 will have 2 + 1 1es that is 3 ones so 7 will have 2 + 1 1es that is 3 1es so the same I can show it here in this example I'll take numbers from 0 to 16 and show it to you so I initialize it with zero and for every number I check for one it would be half of 1 + 1 check for one it would be half of 1 + 1 check for one it would be half of 1 + 1 so half of 1 is 0 + 1 is so half of 1 is 0 + 1 is so half of 1 is 0 + 1 is one for two I go to the half of that index so half of two is 1 one has got one so this will be also one three is odd so I'll go half of it which gives me one and add one to it which gives me two for four it's even so I'll just go to half of it one for five it's odd I'll go half of it and add one to it 1 + 1 2 for half of it and add one to it 1 + 1 2 for half of it and add one to it 1 + 1 2 for six that would be half of six would give me three 2 right so this will also be two here you can see the binary representation confirm the output that I'm giving so this actually has two ones 7 half of seven would be three has got two ones so this would be 2 + 1 got two ones so this would be 2 + 1 got two ones so this would be 2 + 1 which is three for 8 half of 8 is 4 1 so one is a number of ones and eight nine half of nine gives me four again that gives me 1 + 1 gives me that gives me 1 + 1 gives me that gives me 1 + 1 gives me 2 10 11 12 13 14 15 16 so that's how you do it for it you can confirm from this now let me code this out right so what I'll do is I'll keep storing the answer for the previous ones and use it to get the answer for the next ones so I'll go from range I'll store my answer in uh an array the length of the arrrow would be n + 1 right 0 to n okay and would be n + 1 right 0 to n okay and would be n + 1 right 0 to n okay and I'll initialize it all with zeros and I'll keep updating it so I'll go from 1 to n + 1 so this will actually go from 1 to n + 1 so this will actually go from 1 to n + 1 so this will actually go from 1 to n and for every index for every I'll check if I is OD I'll update it to half of it flowed take the value of that from answer and add one to it and set it to the current index okay similarly I'll do for even if it's even then I'll simply half it and take the value at the index and set it to current uh numbers value and I'll return this answer okay let me remove all this commented out code and let's run this and see that worked let's submit it and that worked for all the use cases
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
328
hey there welcome back to this video now we're going to solve a coding interview problem even odd link list you are given a singly linked list group all odd nodes together followed by the even nodes please note here we're talking about the node number and not the value in the nodes this is the problem statement for example if we are given this linked list then we have to group all odd nodes such that the followed by even node here we have numbering this node 1 this node 3 and this node 5 are odd nodes and 2 and 4 are even nodes so we have to group the odd node such that they followed by even nodes so we have to return this linked list here we see these are odd nodes and they are followed by the even nodes and these are even nodes okay if we are given this linked list then we have to group all odd nodes that followed by even nodes here we have the numbering 1 3 5 and 7 are odd nodes and 2 4 and 6 are even nodes we have to group the odd nodes such that they're followed by even nodes so we have to return this linked list these are odd nodes and these are even nodes we see odd nodes are followed by even nodes hope you have understood the problem statement now how we can solve this problem now let me go through the intuition let's suppose that we're given this linked list and here we have the numbering this is our head node now we're going to declare a pointer little points to the head node alt then we're going to declare two pointer even head and even that will point to this node too now what we're going to do is that we're going to disconnect this link and then we're going to connect this link to the next dot next that means by skipping one node and here we're going to disconnect this link and we're going to connect by skipping onenote and it will connect right here and then we're going to move even pointer right here and the old pointer right here so this will be like this again we'll repeat the process the same project until we have even pointer pointing to a null node or the next node where even pointer points to is a null node here we see the next node of event pointer is not a null node and even pointer is not pointing to a null node so we'll apply the same logic here we'll disconnect this link we'll connect by skipping one node and it will connect here and we'll disconnect this link and we'll connect this by skipping one node and that will point to the null node then we will move odd pointer right here and event pointer to this null node then it will be like this okay now here we see that even pointer is pointing to a null node so we'll stop here now what we're going to do we're going to connect the next node where what pointer points to the even head okay so let's disconnect it and let's connect to the even hit then it will be like this and we'll return the head okay and here where we see one three five then two then four then now so we get this node and here we see the odd node followed by even nodes and this is how we can solve this problem for better understanding let's take another example let's suppose that we're given this linked list and here we have the numbering this is our head node so hit pointer pointing to this node two then we're going to declare a pointer or that will point to the head node then we're going to declare to pointer even head and even that will point to this node one okay then we're going to disconnect this link we're going to connect it by skipping onenote it will connect here and we're going to disconnect this link right here and we're going to connect it by skipping onenote so it will connect right here then we're going to move odd pointer here and even pointer here so it will be represented like this we'll keep doing this project until even pointer pointing to a null node or the next node or even pointer point to is a null node here you see the next node of this node 5 is not a null node and even pointer is not pointing to now load so we'll apply that process here let's disconnect it let's connect it by skipping one node then we're going to move even pointer right here and out pointer right here this will be represented like this again we see that the next node of this node 4 is not in our node and this node 4 is not a null node so we'll apply the same process so let's disconnect it let's connect it by skipping one node then disconnect it let's connect it by skipping one node so it will point right here let's move event pointer right here and would pointer right here okay this will be represented like this now we see that even pointer pointing to a node now so we'll stop here now what we're going to do is that we're going to connect the odd node to the even head so let's connect it to the even head this will be represented like this okay we have head node 2 so 2 3 then 6 then seven then one then five then four then null all right and we're returning this node here we see the even node one three five seven and here we see that the value two three six seven here we have two three six seven these are old notes followed by the even nodes one five four okay and this is the node value so we'll return this linked list and this is how we can solve this problem this solution will takes big of n time complexity or n is the number of nodes we have in the given linked list and it will takes constant space complexity since we're not using any additional speed now let's see that's through the code now let me go through the pseudocode first we're going to declare a function or even list that takes the head of a given link list let's suppose that we're given this linked list for sake of understanding then we're going to check if the head of a given linked list is now then we'll return now then we're going to declare a pointer odd that will point to the head node then we're going to declare to pointer even and even ahead that will point to the next of head node then we're gonna check while even is not equals to null or even the next not equals to now order next equals to even dot next or equals to or dot next even dot next to goes to or dot next even equals to even dot next don't worry i'm just reading here okay then we're going to add the tail of odd notes to the head of even node at the end we'll return the head okay now let's see how it works don't worry i'm not just reading here i'm explaining how it actually works initially we have this pointer head or even head and even then for first iteration of this while loop the linked list will be represented like this then for the next iteration of this while loop the linked list will be like this okay and here we're just connecting the tail of odd note to the head of even node and we're returning this node here to wrap your head around just to go through using this pseudo code with your own examples then you will see how logical it is here i break it down everything to make you understand this problem alright guys this is my solution to this problem this solution will take figure of n time complexity or n increase the number of nodes in the given linked list and it will takes constant space complexity since we're not using any additional speech all right guys if you happen to subscribe to the channel please subscribe to the channel like this video share this video thanks for watching this video i will see you in the next video till then take care
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
304
hey everybody this is larry this is day 12 of the made leco daily challenge hit the like button in the subscribe button join me on discord let me know what you think about today's prom uh and i usually stop this live so it's a little bit slow fast forward watch 2x whatever you need to do i didn't do the keyboard thing today because i think i don't know how much value it adds so leave me in the comments below because i get questions sometimes about shortcut keys and stuff like that but mostly i you see everything i do i don't you know maybe i move the mouse from time to time but uh i'm you know there's no shenanigans there but anyway so today's form is range some curry to the immutable okay mutable is kind of cool nice i guess yeah i mean i okay so actually uh yeah this one is actually kind of interesting because i've known how to do this and it's a little bit tricky to understand me or not understand what to come up with but i did i don't know probably learned it a long time ago and the fun fact is that i had a i had an interview um in 2005 maybe 2006 i think it's 2005 though where uh i did get this answer very quickly or yeah during an interview i got this problem during that interview i got it very quickly the person was like oh you've seen this before i'm like i guess a little bit but i've just figured it out um and i don't know it didn't it i feel like it was one of those cases where the interview went too well so like i don't know the guy was not happy with uh he just thought i've seen everything i'm like yeah i mean i guess so then why don't you ask like problems that people haven't seen but that's besides the point so it's a little bit of a rant it's a little bit of a history uh so this question does go way back um i am going to take this opportunity i guess i should have took this opportunity while talking to bring up paintbrush so that we can see so i could draw a little couple of somethings for you uh because i think that's probably a little bit slightly better hang on just technology stuff okay so now this is my paintbrush my mac but the idea is that okay you know if you have uh the idea of 1d prefix sum let's start with that right if you have one d prefix sum the idea is that okay let's say this is uh an array um and at every point um drawing is hard and every you know this is 1d version right uh let's just say the even is faced and indexed um so you know so you have a prefix sum so that the idea behind it is that and i'm going to change the color let's say you know so that we calculate at every point the sum between the zero point uh or the element with zero array elements to the x elements right so we could calculate the sum of the first k elements and then and so from that you know you want to get the sum between the i element and the j element that is just the difference between the sum of the zero to the j element minus zero to the i've element right um and we could do this in the formula real quick uh technology hang on so the idea is that okay you know prefix sum you know you have let's say f of uh let's just say index is equal to a sub zero plus a plus or a sub 1 plus a sub 2 plus dot plus a sub i minus 1 uh plus a sub i right and then where this is i let's just change this to i and then f of j is equal to the same thing except this is j and then now to get the sum between i and j you just subtract them because um you know because these cancels out let's say j is bigger than i then you know if you subtract f sub j from f sub i you know these things all cancel out all the way up to the point where you know let's just say let's add in some red con here um you know plus dot plus you know all this stuff right so all this cancels out um maybe you would subtract from a sub minor i minus one depending on if you want to do inclusive but basically all those cancels out and then you have the sum of the rest depending on how you want to find it right so that's basically the idea um and the 2d version of this that's just a little background hopefully i mean i know that was very quick but that's just to give you a little bit of uh intuition between before i go for the 2d version so 2d version is kind of the same idea except for obviously let me change this to white the 2d version is based off the same idea of okay you know now you have a square and for every cell let's say we take this cell do i change the color but maybe not clearly not oops now let's say you have this cell we can pre-calculate the sum of pre-calculate the sum of pre-calculate the sum of all you know all the um just the matrix even though this looks like a square but it could be a rectangular um from 0.00 to xy um from 0.00 to xy um from 0.00 to xy and then now well the question is how do you figure out you know for an arbitrary rectangle let's say it looks like this right how do you figure out the blue box well now you can just look at geometry and then work your way back to proof with yourself which is that you know the blue box is just a red box minus this purple box and the second purple box right because there are the areas that you don't want to count so you just subtract them out but then now you see that we double subtract out this area that is now let's say yellow uh so we want to add that back in so that's basically the idea behind the formula that you will see that this is the visualization hopefully that's good enough i'm not going to get into it that detail i mean or like you know this is a good enough intuition um and then now we're going to go back to the math or the um the thing so then now yeah now you and you know you kind of took a look at what we did we basically have four queries to uh look up matrix and you know and like a couple of additions and one subtraction so that's gonna be old one time which is why i'm confident and the pre-processing is easy as well and the pre-processing is easy as well and the pre-processing is easy as well it's kind of dynamic programming but you can you know you can implement in other ways i suppose but i'm going to do it in the way that makes sense and i'll show it to you in this right now so basically now we have self. um prefix sum maybe let's also just do yeah rows is equal to length of matrix uh columns is equal to the length of matrix sub zero uh but only if i'll just double check whether it is we have to check for zero but it looks like i'm good here so i just keep this at here um and then now we can just times columns plus one for range of rows plus one and we want to make this basically a rows plus one times columns plus one matrix um for me i always like to do it with the zero um zeros so yeah so then now we just go through the index right so for x in range of uh one two rows plus one because we want to do an inclusive y and i always i think other people usually do it in a other way but i usually do it this way um basically i just add i do it each row at a time that's the way i remember it but i think you can probably do a little bit um you know basically i do this and then i do it to the on the columns um and that should be basically good you know i think you can mix it up into one set of for loops but i find this easier to uh just remember and yeah for testing purposes we can just print this out just return zero just for you know i did more test cases nope but yeah now we can print it out and this is clearly wrong because i forgot to set you know uh i forgot to set it to the matrix so yeah so it's up so we have to set it to the matrix of x minus one y minus one um and yeah but yeah so now you have three zero i mean and you could kind of verify this uh by you know visualizing it i'm not gonna do that because i'm relatively confident uh this time around even though i made mistakes in the past and just before um but yeah but now um yeah and keeping in mind that the first row and column is gonna be zero because if we represent having zero elements um that's the way i do it by convention anyway so you could get you could do without but you just have to be careful with your if statements and checking bounds and stuff like that uh but yeah but now we go to the rows and columns which i'm gonna have to double check to make sure that there's zero index of one index or whatever um so it's gonna be zero indexed okay just making sure because there's no consistency in a lot of places so you know be careful but yeah so now we just return uh self.prefix of as we said self.prefix of as we said self.prefix of as we said um this is zero index so we want uh this plus one so yeah so we wait also i want to make sure that they define the cut okay because sometimes they put it in different order and join the different giving you different corners instead of upper left and lower right so i just wanted to read the constraints to make sure um i mean it's not hard to fix you just have to kind of keep track of a few more things or you have to do some if statements or something like that but yeah now we have this is the corner that's lower right so then now we subtract and i might get this wrong to be honest because it's easy to get off by once um this minus also the same thing but for the column is this is that right row two yeah um and then as i mentioned this could be off by once i have to think about it a second because i'm really bad at all by one so at least like i have to um i have to make sure you know and okay so what happens is that this is inclusive this so this should be a minus one because we wanted to count this row inclusively okay i think so anyway it could be well who knows how math works um and then now as we said we have to add in back in the thing that we um didn't get or we subtracted twice so yeah i think this is also minus one but i could be wrong i mean this part i'm a little bit the off by one's is the only thing i worry about the math i think we're okay as we said whoopsie daisies um do we add this back in am i adding the right thing no i think we have to include this maybe even though we're under counting so maybe i think i'm wrong here um okay hmm yuck okay i mean i know this is still wrong because that's what we had before but oops and now there's even more wrong um what was the first request is two one the red rank tango okay so why do i get 23 okay let's print this out again maybe i make messed up after all but anyway the idea is right maybe you could fast forward this part a little bit as you know i'm usually doing this live but yeah so we start at 4-3 which is the last row 4-3 which is the last row 4-3 which is the last row uh second to the last cell is that right now it's the last row second to last so that means that it is 38 right so we have 38 that probably makes sense we want to subtract the first row so that should be the first row the index is oh i see so the corner is to the right of it so i think i over adjusted a little bit so i think i was thinking about the cells for some reason even though the corners don't include it so i think this may be more right now that i think about it because it is that point that's to the rest of that uh maybe too much all right i mean it's conceptually right it's fine uh you have the idea but i'm being really bad right now let's see so we have 38 minus row one column two row one com2 so the prefix is the now this should be i think that's where i messed up this should be plus one even wait is that true because then you would just get a smaller number so row one okay i'm really bad at all by one oh no row two okay so it is row two so that means that you want the first two rows which is index two that seems right maybe adding back is a little bit weird because that is the is it okay so let's see so row one column two one what's right what's what one common but i keep saying that for three so it's gonna be two um two rows down oh wait this is one index so is three rows down and one uh column so it's basically the first row so three five one four one so that's 14 right so we should have 14 here that we're removing but okay what am i printing sorry friends sometimes off by ones are hard but i would also say that you know i mean uh you may be better about it for me this is me knowing so once you know it becomes a little bit easier to kind of compensate for it oh is that why because i need to plus one here because i think i yeah okay i think i was focused on the other index that i think i might have just forgotten about that one um so off by one again but uh okay no that's too long unfortunately but is it yeah no this should be more right but then now maybe this is uh because if this is zero okay what happens if this is zero then we include no element so action this should be right what is going on what's going on so it yeah dirty a part is finally right uh this one row one how did i which one did i do first row one column two so column two is going to be three row one is four so actually i did the other one so 14 is should be the other one unless i just did the math one which is possible now 14 is the other one and then eight is this weird corner this rear corner is right did i just do the muffler now this is 14 still oh i see because i think i need this here and then i need this here to be on the same row is this oh and also i should probably change this one to get the right answer okay like i said off by one's a hard that's why you need to be really precise but i was just i think i'm watching a little bit um yeah it looks good now as i you know but i would also say that one if you have the principle right principal's right you don't have to memorize these things and i don't i have to prove it every time and sometimes i get to bounce wrong but you know my debugging is based off knowing the principle and not just like you know like try random things and guess it is correct though it may seem that way but i mean i knew i was got the guiding principles but i think i just anyway let's give it a submit and hopefully this is right yep looks good um as we said as and you can probably figure out um you know this is a little bit tricky i don't know what difficulty that they may give it to be honest because it couldn't go right away because it's either you know it or you don't a little bit um but here this is of n squared or r times c to be more precise and this is all one as this is just four lookups and some addition and subtraction so yeah um that's all i have for this problem it went a little bit long because of the debugging but hope you enjoy it i hope you learned something and yeah let me know about your questions comments whatever it is and i will see you later you know stay good stay healthy stay well take care of yourself and others if you can and to good mental health bye
Range Sum Query 2D - Immutable
range-sum-query-2d-immutable
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`. * `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. You must design an algorithm where `sumRegion` works on `O(1)` time complexity. **Example 1:** **Input** \[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\] \[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\] **Output** \[null, 8, 11, 12\] **Explanation** NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `-104 <= matrix[i][j] <= 104` * `0 <= row1 <= row2 < m` * `0 <= col1 <= col2 < n` * At most `104` calls will be made to `sumRegion`.
null
Array,Design,Matrix,Prefix Sum
Medium
303,308
1,876
what's up guys so let's solve this 1876 substring with size very distinct characters a string is good if there is a no repeat characters given string has reason number of good strings consumption lens ring s note that if there is a multiple occurrence of the sense of string every our current should be counted okay so for example this guy is a new right it's a answer and the yzz is not because there are two multiple gta it's not the ads now right so this is just sliding with no approach you can maintain a dictionary uh you can maintain a dictionary and they just count you can start from these and uh for every new character just count it and delete the first one right so and the idea is that there's only uh 26 english characters right so you can uh initialize the dictionary you can use the list right and then now delete and the count just one okay and uh the boundary case is that if lens is lesser you go to two and it must return zero okay so initialize your d to be 26 and it goes through the first three uh this is the standard technology in the skill in a python that you can change the alphabets into the number so a will map to zero okay so the order s i minus like seven plus one so you start from you build a dictionary at least and if maximum d there's a two that means every one is unique right so you can initialize it to be zero otherwise that initially in your size the answer to be one otherwise become zero and it goes to three to length s for a new character you add for the old character you delete and uh for every time you just check that the maximum d lesson two otherwise zero and then return your ends so this is a linear right because this list is linear only 26 characters and you slide sliding window approach okay that's it see you guys next videos
Substrings of Size Three with Distinct Characters
map-of-highest-peak
A string is **good** if there are no repeated characters. Given a string `s`​​​​​, return _the number of **good substrings** of length **three** in_ `s`​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "xyzzaz " **Output:** 1 **Explanation:** There are 4 substrings of size 3: "xyz ", "yzz ", "zza ", and "zaz ". The only good substring of length 3 is "xyz ". **Example 2:** **Input:** s = "aababcabc " **Output:** 4 **Explanation:** There are 7 substrings of size 3: "aab ", "aba ", "bab ", "abc ", "bca ", "cab ", and "abc ". The good substrings are "abc ", "bca ", "cab ", and "abc ". **Constraints:** * `1 <= s.length <= 100` * `s`​​​​​​ consists of lowercase English letters.
Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources.
Array,Breadth-First Search,Matrix
Medium
null
212
welcome to June's LICO challenge today's problem is word search to given a 2d board and a list of words from a dictionary find all words in the board here's our word search puzzle and we're given a bunch of words and we want to return an output of all the words that exist inside the word search each word must be constructed by letters sequentially adjacent cells which means left right top or bottom and the same letter cannot be used more than once immediately when I saw this problem I thought all right that first search is probably the way to go and it reminded me of the island search problem and you could use check for each word the entire board and check to see in a depth-first board and check to see in a depth-first board and check to see in a depth-first search whether the word can be constructed or not and that would work but it's a big weight not only is it a waste of space whenever you need to compare whether the prefix is existing for this word it's going to be inefficient because you'll have to compare each letter so is there a data structure that can help us out here and they give us a hint that implementing a tree or a prefix tree would greatly help so let's begin with that and I'm not going to go too much into what this is because I've solved before but just know that it's basically a bunch of nested dictionaries for each letter of the word that way when we try to compare to see if we want to continue our algorithm we could just search our tree instead so let's begin by implementing a tree class and we have first the initializer which is just going to be let's call it child a dictionary now we want to insert a word so first we'll set a current pointer and say this is equal to the self child and for each letter in the word we'll check hey does exist and if it doesn't we'll create a key for this letter and then a dictionary for the value and continue on this algorithm until it ends so for L in word if L not in her then we want to say create a key with a dictionary like this and continue on Saker was now than equal the cur of the dictionary and finally once we're finished we want to mark the end of the word and we'll do that by putting a hash tag here and just make that equal true now we want to check to see if the word actually exists inside this tree okay and that is pretty similar we still set the current pointer to self dot child and for L in word we're just going to say hey if L not incur then we immediately turn up false otherwise if it is we'll just continue on like this and at the very end we're going to return whether the this hash tag is in the current dictionary return hash tag incur so that should work now starts with is very similar except we don't check this hash tag all we're going to check is to see if we were able to finish our path and if we were then we can just return it true so let's just test that out real quick what we'll do is just create a tree and we'll say keep on insert ABC and let's check to see if these work here T dot search ABC that should be a true and we'll check see if a B works that should be a false and we'll check with a bee that should be true so let me just try running that and that should be true false true okay so I got a runtime error see starts with B name word is not defined ah it's not word its prefix okay so let's try that again all right so true false true so that looks good now we have our tree structure okay so now that we have that let's first make some space here to make it readable and what I'm going to do is take these words and put it into the tree so let's first initialize a tree here and say for all the words in words we're going to insert that into our tree now we want to write our depth first search algorithm right begin that let's first initialize a couple variables I'm going to start with n for the number of rows and that's just going to be the length of board M for the number of columns that'll be the length of board 0 and also our output will make that equal to a list now this is going to be a depth-first search and is going to be a depth-first search and is going to be a depth-first search and I'm gonna pass the row the column as well as a built path so I'm gonna just got I'll call that path you can call whatever you want but this is going to be a list which I'm going to build up and checked and convert it into a string what I check to see if this word exists but what does what is this algorithm need to contain all right and for that I'm gonna go to the white board alright so here I've represented the Award search and here's our tree this is just going to be like a representation of it and let's just begin at this algorithm I'm gonna start the first cell a and the very first thing I need to check is are we in bounds since we're passing in the row and column we'll make sure that the cell actually exists because otherwise are all the more break so first are we in bounds and if not just return and stop the recursive stack but there is one more thing we need to check and that's to make sure that if we are let's say a B we never want to go back to a because we can't repeat letters right so in order to make sure for that we'll have to mark somehow just like the islands problem or we're gonna mark it like zero or something like that to say that we've been here before so we'll have to mark a visited somehow in this cell but one difference with this is once we've finished this recursive step we want to revert it back and that way when like we go to D a is not gonna be visited anymore so we'll have to make sure to have some sort of backtracking here so I'll just write that so once we're at a now we want to check to see if we should even continue this right because is a inside of our tree and we have that function starts with to know whether or not the rest of the algorithm is necessary say we were at D if we check to see if D starts with and you merely see there's nothing that starts with just D then we should just end the algorithm right there right so if in bounds if so if it's not in balance and it or its visited then we want to return but also if it doesn't start with not starts with then we also want to return because there's no point in going any further finally we want to check to see does it exist like we want to a search so say that we're at a and then we just go down a B we its inbounds its visited yes and we built a building up our string and we check to see is it inside our tree and yeah it is so a B so once if it's in search then we want to add it to our outlet right and I apologize for the messiness but you might think okay then we can just end there because stack there we can just return but we can't do that because there's actually other letters too that we need to check for a b c and a be e so we have to continue in our depth-first we have to continue in our depth-first we have to continue in our depth-first search it'll end once it's either out of bounds everything's visited or letters no longer start with like these letters and that's just going to allow us to be like a b c a be e it'll stop once we see that doesn't start with and all the while we'll be adding into our output the letters that do exist for the word and set our tree and here just our depth first search would just be typical you know row plus 1 row minus 1 column plus 1 calm minus 1 column plus 1 yeah so hopefully i'll code this out and it'll start to make a little more sense now that we have our intuition of how we're going to code this out let's start coding it very first thing we want to check is it out of bounds or have we visited because if it is then we just end this call here so if the row is less than 0 or row is greater or equal to and or column is less than 0 or column is greater or equal to m or this cell has been visited before so that will just try board row column and i'm gonna mark it with making these equal to 0 and if any of this is the case then we just returned stop the algorithm right now great now we want to check for if it starts because if it doesn't then we should just end our algorithm right so if not key that starts and I mentioned that I'm gonna use lists for this building up this path so let's first how do we do this we want to do a join for the path plus this board roll column and that's going to create a list with all of the characters and we'll just call this string and that's this is just to save on the expensiveness of appending strings and stuff so let's see if not T that starts with string if this the tree doesn't contain the starts with string then you know what just end this right now because why continue this algorithm there's no reason otherwise we are able to pass this then I guess we can do an else if key dot search and I should say starts with search string then what then we want to add it to our output right so let's append it to our open string and we can just continue on our algorithm one thing to note is it is possible for them there to be multiple ways to find this word and we don't want to return duplicates so I'll just say okay search and the string not in output and there's probably better ways to do that but they'll do for now all right finally what do we want to do here well look we guide to our deaf for search now right so what we're going to do is say grow - one column and we want do is say grow - one column and we want do is say grow - one column and we want to pass in the path as well as the our built-up path right here and the our built-up path right here and the our built-up path right here and what I'm going to do actually is save it as a temp just to make that a little bit more understandable and passing the temp and we'll do our depth-first search we'll do our depth-first search we'll do our depth-first search roll this one call - one column plus one roll this one call - one column plus one roll this one call - one column plus one thing to note though I need to mark this point that about I've already visited this point right so in order to do that we will say let's first have a placeholder for this current character like this now I'm going to make this equal to zero and once we're finished with our stack we're going to make that equal back to the place holder so that's no longer visited okay so that should be our whole different search algorithm and we want to do this for each one of our cells right so for n in range of n number of rows or m in range of M just call our deafer search we'll do n m and we'll just pass in an empty list for our pack list it's a little bit up and finally just return our outfit so I may be missing something here let's see if that works OOP got a runtime error name word is not defined word okay and where is that is in line 34 words okay check to see if this works okay so it looks like our test case works let's see if we can submit this and they're accepted Hugh so this is not the best solution I already know that but it is I believe a time complexity of n times M there's probably some inefficiencies that I've missed somewhere here there I was able to avoid having to create like extra DP arrays for tracking the visited cells but this works hopefully you guys can play with it and find out fine figure out if there's anything better but that's it
Word Search II
word-search-ii
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_. Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. **Example 1:** **Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\] **Output:** \[ "eat ", "oath "\] **Example 2:** **Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\] **Output:** \[\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 12` * `board[i][j]` is a lowercase English letter. * `1 <= words.length <= 3 * 104` * `1 <= words[i].length <= 10` * `words[i]` consists of lowercase English letters. * All the strings of `words` are unique.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Array,String,Backtracking,Trie,Matrix
Hard
79,1022,1433
148
hello and welcome to another Elite code video today we're going to be doing problem number 148 sort list and it's an interesting problem because we are going to be doing a store but now we don't have an array we actually have a link list so we'd have to figure out like how that would work and there are common problems that you either have to do this on parts of like a list or yeah basically you're using this as a sub problem to do something else so doing this or doing like reverses on linked list is going to be something that you're going to want to know for sure okay so let's take a look at this problem so given the head of a linked list return list after sorting in ascending order so we have list four one three and now we want to sort it well there are like different algorithms to sort but what I'm going to be introducing is a merge sort you can do a I think it's probably the easiest one to do and I think it makes the most sense with list nodes because you could do other swords you could do like a bubble sort or something um but realistically honestly um the only sorting algorithm well at least one out of the few that I know how to do off the top of my head is a merge sort and maybe like a heapsort but the nice thing is it's also like one of the most efficient sorting algorithms so it is an M log n sorting algorithms I think there's also quick sort and heapsort but we don't want to use extra space here so we're just going to use the uh yeah we I think we could technically use a heat sort and that wouldn't be extra space if we just delete all of these um all these connections and we put our nodes in a heap technically that would be concerning extra space but we're going to do emergency right here because I do think it's a little bit trickier to execute than a heapsort and also it's with a linked list so it's going to add some complexity here but anyway we're going to want to sort this and the way that merge sort works is let me actually show you basically what we need to do is we need to it's like a dividing conquer problem we need to be dividing our list up until we have one node so let me show you what that's going to look like right so in the beginning if we have an even list we're going to divide it up like this get rid of this then we have these two sub problems now for the left sub problem we have two nodes we have to divide that up again this divide this one up okay and now we are going to actually be merging or cursively so we're going to merge these two then we're going to merge these two and then we're going to merge that whole thing so let's take a look what that looks like right so for a four and two we're going to merge a four and a two well it's pretty straightforward for Just Two nodes right it's just going to be 2 4 here so we're gonna have two four so that's going to go over here 2 4. and then for this one three it's going to be the same thing it's only two nodes so we're going to merge them so that's gonna be one three and now we are going to merge these two lists together right so one so we have a one three I'm not going to draw the arrow but imagine there is an arrow two four actually I could doesn't matter so let's try this so we have to merge these two lists and now this problem is also like a liquid easy or liquid medium right where it's merge two lists that are sorted and so once we know that then it's pretty straightforward we just go through the lists and we need to just check like what element is smaller and that's all we have to do there and so we're going to go through these lists and like I said this is like once you get to this point we have two sorted lists it's pretty straightforward we just have some index where we're uh we just compare the values and then we take the smaller one so we would take like the way it would work I mean just need some more space here so the way it would work is if we have two four so we're gonna have a pointer to each of these and then we're going to say like we're gonna have a dummy node that's going to start and then we're gonna say like okay I'll take the smaller value so the one would be the smaller value here I'm gonna move this over here now the pointer is here now we have a two and a three so the two is smaller and then we're going to move that over here and now we take the three and then now this is pointing to none so whenever we have a none we just always take the other one so this is four and then our you know we stop when they're both pointing to none and then we just return the next pointer of the dummy note so that's how you do the merge so we have remember we have two steps we have a split step where we keep splitting our array our list into sub elements and then we have a merge step and so let's actually talk about the split step real quick and I'm going to show two different examples so let's say we have these nodes there's a couple ways you could do it like The Brute Force kind of or you could do a clever trick so the brute force is you start here you just go down the list and we can just get like a count right so we start here we go now unless we figure out how many nodes are in here and then you figure out like okay well let's say the count is four that means I have to start here that means I have to move up whatever nodes like one or two so you would just do that in a loop you'd move up like one or two nodes and then you'd have this pointer here then you just say like okay let's take the next node of this node and that's going to be my second um like linked list that we're going to be splitting and so we're going to have that be this node so this will be like you know the first list this will be the second list and then we just take this connection and delete that but there is a tricky way to do that and so I'm going to show that and the way to do that and this I think this works for any list so for a list with four nodes we're going to want to split down the middle right we're going to want to have two and so the way we're going to do this we're actually gonna have a slow pointer here and a fast pointer here and what we're going to do is our condition is actually going to be this 30. so it's going to be a while fast and fast.next and let me show you fast and fast.next and let me show you fast and fast.next and let me show you why so that's going to be our condition to execute the loop so clearly here that condition is true right so the Fast Point the fast node has to exist and the next node that has to exist so let's actually work that out so this is true for the first case now what we're going to be doing is we're going to move the slope pointer up one node we're going to move the fast pointer up two nodes so let's take a look what that's going to look like so iteration one this is true so our slow is going to go over here actually let's just draw it here this is gone and now the fast pointer is going to go up two nodes which will be over here and now when we go into this loop again so fast.mex does go into this loop again so fast.mex does go into this loop again so fast.mex does not exist so we're going to end here and so you can see that the slow pointer is going to be the node right before the node we care about so then we can just say like uh you know like second node or whatever it is or second list equals s dot or slow dot Max you know and so that would give us this node and then that now that we have this node this will be the second link list and then all we have to do is break this connection and then we can mer we can like now we just do the sub problem for the rest of it so that's how you would split a list with four elements so the two cases are odd or even elements right and by the way we can also test this with one out so our base case is one Element so with one element we wouldn't even do this with two elements it would work as well because the fast would be here the slow would be here and then we wouldn't even go into the while loop and so we would split right here so that would work let's look at three elements so with three elements what would happen is the while loop would be true so the slow would go over here the fast would move two up so it would actually come over here and now our fast is out of bound so it wouldn't happen and so we'd break here which is fine right so for a uh linked list with an odd number of elements you can either split it with like the more number on the left or the more number on the right so this is like five we can either split it into this or this it doesn't really matter right well like when we merge them it doesn't run you can modify this a little to split in whatever way you want and for other problems like some problems are going to want you to split in this way some problems are going to want you just put in this way so you could just slightly modify this fast algorithm I think it's like you just modify where the fast pointer starts by a little bit and then that will change your outcome for that but in this case it doesn't matter but anyway let's go let's walk through a Five Element list as well so let's say we have one two four and yeah now we don't really need to keep track of like a current or account we just have these slow and fast pointers so we would have a slow and a fast and let's see what that would look like so we can move them uh right away so let's move it here now the fast is going to go over here now there is a fast and a fast dot next is still true so we can move again so slow is going to come over here fast is going to be out of bounds and so we are going to chop right here which is fine right we're going to have this list and this list so totally fine and so that's going to be how our split is going to work and then what we're going to do is we're going to merge the nodes that we split so we need to write a splitter function that splits and then we need to merge and so what that's going to look like let me draw that so like for a list like this we're going to say merge and then we're going to actually split this thing right so we are going to split the left and then split the right so it's going to be split you know the left part the right part so what actually what that would look like is the left part is going to be so let's just say it's m s and so this is going to be 1 2 here and then split the right part it's going to be three four like we call this after we already made our initial split and so if you think about it recursively then okay you'd have this one two so what would that look like well so once we have this recursive case then it's pretty straightforward because this is going to break down into this and so remember uh V split of one would return one and the split of two would return two so we would have a merge of Node 1 and node two which would give us this so that would give us this over here would give us one two sorted so now we have like the value that actually gets returned into this would be one two and now for three four uh it would be the same thing right so when we try to do this sub problem with the split three four what's going to happen is we're going to chop it up like this and then when we call split on three split on four and we merge those then that's going to return to us three four and so 3 4 is going to be returned into here right so now our sub so now once we actually rehearse back our stuff is going to look like merge these two lists which is what we want so that's kind of how it works we chop up the list and then we call and this is going to be the function that we need to call so we need we do need to write a merge function and then we need to call split function and then we just need to call uh split on because split is going to call merge in it so we need to call split on the head of the list and now it will give us the new linked list and so let's do that so first we are going to write the merge function let's do that and this is like I said this is just another Elite code problem where you're given two sorted lists so we can just call that list one list two okay and we can definitely handle um like we can definitely handle uh I don't think we can ever have a list of no elements I'm pretty sure we can debug that later I think at the at like these lists have to be non-empty because these lists have to be non-empty because these lists have to be non-empty because when we split and we have a list of one element it would just return it wouldn't try to split it again okay so assume we can assume that list one is not empty unless two is not empty here so we do the same thing we always do so we make a dummy node the list node here we don't have to give it a value so we just do this then we say while list one or list two so I'm gonna I think in some of my old problems I have like three while Loops I'm going to show you how you can write this in one while loop just to make it cleaner a little bit so we can say so this is always going to be true if one of the nodes exists so you could say if not list two so if there's not list two we're always going to be taking from list one or and then this is going to be uh left I should be list one right so if list one dot val is less than list two dot pal okay then we're going to want to use list two dot valves so oh we also need to make a current node so occur dummy as usual okay so now this is going to be Cur dot next so this is means we're going to be taking from um list one guaranteed right if there's not list two then we have to be taking from list one and if list one dot val is less than this two dot well we're also taking from this one so that's going to be a list one uh yeah and we just want to take that note yeah perfect now what we want to do is we want to update list one so this one equals list1.next this one equals list1.next this one equals list1.next okay so now we need to actually move up this node so this is going to be uh I actually know what we need to do is we need to break the connection between um yeah so like for example like let's say we do have this dummy node and we're processing a list let's just say one two three whatever like one two three so the arc and then our current node is somewhere over here let's just so actually the current node is this node so what we did was we said this is this and this like this let's just say this is L1 we actually moved it over here so that L1 does not exist but now what we need to do is we need to break this connection right here let's do that next and that's going to be um occur equals per dot next and then we can just break it here yeah her dot next equals none so we broke it there now else we need to be taking from list two so that's just all the same stuff two Dot two equals list two dot next curve equals heard about next equals none okay so that should uh deal with that now we just need to return the which is the head node of our which is the head node of our which is the head node of our new list okay so this is the sub problem for that and if you want to look into that I do I think in my easy Speed Run I do have like uh I actually did this exact problem pretty sure and then some other ones okay so now we need the other function and that's going to be the split function right and so the split function is going to actually do the same thing it's going to take list uh no it's actually gonna take one list so the split function is going to take one list and split it into two yeah like when we're when like when we have this one two three four it's going to take this one list and split it into two and then it's gonna merge yeah so it's a split it's gonna split and merge but we need to call this merge okay so for our base case if the length of list one is one then we already like done sorting it and splitting it that's pretty straightforward so list one dot next does not exist not and we can return straight away okay now we need to do this slow and fasting so it's slow fast equals list one dot next and then like I said uh they still have it saved no I don't but it's going to be well fast and Fast cut back next let's go dot next fast remember we move the fast up twice okay so now the slow um in our picture the slow pointer is going to point to this node and so now what we need to do is we need to save the node after it and then we need to make a break here so let's do that so let's just call this list two equals uh slow dot next equals none and now we need to return remember we are merging the split of like the next part so that's going to look like this it's going to merge and it's going to be split we need to do a sub split again like this is the recursive case so we need to split list it's not going to be list one this is going to be uh no it is going to be list one yeah just one list two because now our list one so for example like let's actually show what that looks like we did have a list one this so let's say this is list one okay and so what we did was we industry is a little bad but let's actually fix it so it's more legible uh okay perfect okay so what we actually did was our slow was gonna end up here and so we chop here and this is going to be list two this is going to be list one but because we chopped here now these two lists are actually split so list one is one two and then list two is three four so now we need to call split on each one of these lists because we need to do like a recursive sub split and then we need to merge all that together so we're going to call split on one two which is going to split keep splitting and then it's going to merge that into some sub list and then we need to do the same thing here merge that into sub list and then we need to um yeah so split and then when we split it's going to have another merge and so on okay so I think that should be right now finally we just need to check for these variables can you have like an empty list or something yeah so it looks like there is a case where we are given an empty head and but we never actually handled that but that's totally fine we can just check for it here so we can say if not head turn none I should take care of that issue now our list is guaranteed to be at least one item and then display it will just return that one item so now we need to do one last thing we need to return we need to call split on the head I think that should be it hopefully we didn't screw it up all right so this needs to be split list one and then we need to split list two we need to keep trying to split them until we get to the recursive case I don't know how many parentheses I have here okay too many uh if not list two or hmm let's think about this so if not list two then it will do list one yeah team is fine or if not list two that means list one has to exist but what if there's no list one right or yes and we might have to just check for list one here because like what if there's a list two and not list one that would be the case yeah Okay so just one and that should be fine hopefully okay so let's think about the time and space here yeah you can technically break this while loop down into multiple but we did at the cleaner way this time I think there's actually a way to even do it clear than this but at least this makes it all better okay so now let's think about the time and space here so what are we actually doing well I guess we know for the time and space right this should be n log n because this is a merge sort so n log n is guaranteed to be um a merch or it's getting a tdbn login because we're going to split the list n times and then each for each like sub list we need to merge that and so that's going to be on log n okay um for the space so it's gonna be all one because we didn't actually make like any new lists we're just splitting the notes we're current we're using the nodes we have we're not creating any new nodes we are creating this dummy node but we're deleting it every time we're not actually like adding it to the list or anything so that should be oh that should be constant extra space so that's the key with these linked lists to make these functions uh efficient you need to make sure you kind of sort the list you sort the nodes in place and it's a lot easier for Linked lists because we just break up the pointers and move the nodes around right so it's a lot more straightforward than like with an array to sort it in place and things like that okay and yeah I think that's all for this problem so hopefully you liked it and if you did please like the video and subscribe to the channel and I'll see you next one thanks for watching bye
Sort List
sort-list
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 5 * 104]`. * `-105 <= Node.val <= 105` **Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
null
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
Medium
21,75,147,1992
1,678
Hello friends good evening everyone today we will see the L code question 1678 the question name is goal pass inter interpretation so the question say states that you own a goal parel that can interpret a string command means we have given a string command the command consist of alphabet G the parenthesis and in parenthesis Al in some order mean there are only three types of alphabets in any order in string common the gold parcel will interpret G as the string g means the parcel will consider G as the string G the anti parenthesis will consider as o and the AL with the parenthesis is considered as Al the interpreted strings are then conc concatenated in the original order given the string command return the goal pass interpretation of the command so what we have to do is we have given a string which consist of G then empty parenthesis and empty and parenthesis which uh consist a Alon so in this string we have to consider the G as G the empty parenthesis as o and the parentheses with Al as only L and we have to con concate all the string by converting into the original string given the string command return the goal par interpretation of command so here we have given a command uh string and we have to uh interpret all the strings and convert it into the their given meanings and we have to WR understand so here the test case one is here is a string command G empty parenthesis and in empty parenthesis a so the goal passer interprets the command as follow see the G is converted into the G the empty parenthesis is converted into the O and the AL is converted with the parenthesis into a and the final concatenated result is full so we have to return a string example number two command so here is the given string and the expected output and the constant are one is the command is greater than 100 and command consist of only GRE characters in uh single order so the approach is simple what we will do is we have given a string command CM D equals to so the is this and the output is g o a l which this convert is this and after converting this is this and after is this so this is our finally expected output so the approach is simple what we have to do is we have to check the first two characters of each given string means by recognizing the two characters we can interpret the front characters what will be the expectation so here we will check for so sorry so what we will do is we will take the string g a l so we will use the for loop from Z to n minus1 and in this for we will Traverse each character and we will state three conditions the first condition will be if I value is G then we will concate the G to the main answer string this is our answer string and this will conate to here suppose if I and I + 1 is conate to here suppose if I and I + 1 is conate to here suppose if I and I + 1 is the bracket parenthesis so we will form candidate o and suppose if I and I + 1 is a then we will Contin a so and I + 1 is a then we will Contin a so and I + 1 is a then we will Contin a so the approach is simple we will solve this question using this so first what do Comm this is C+ we will Trav from 0 to first we will check if command of I = = first we will check if command of I = = first we will check if command of I = = car G you will declare the string empty Str if the given character G then we will plus = to will plus = to will plus = to G if I character the next character are equals to the open parenthesis and equals to parentheses then what we will do we will add four and after you Comm I character isal to open parentheses and I + 1 then we and simply we will return the string to the function so we will ch okay so now we is and we will sub is accepted thank you
Goal Parser Interpretation
number-of-ways-to-split-a-string
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order. Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`. **Example 1:** **Input:** command = "G()(al) " **Output:** "Goal " **Explanation:** The Goal Parser interprets the command as follows: G -> G () -> o (al) -> al The final concatenated result is "Goal ". **Example 2:** **Input:** command = "G()()()()(al) " **Output:** "Gooooal " **Example 3:** **Input:** command = "(al)G(al)()()G " **Output:** "alGalooG " **Constraints:** * `1 <= command.length <= 100` * `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Math,String
Medium
548
309
let's cover the fifth video of the best time to buy and sell stock Series in which you can have as many transactions as you want as long as you don't have more than one stock at the time you don't buy the stock the very next day you sell it the given concerns are the length of the prices is within 5,000 and length of the prices is within 5,000 and length of the prices is within 5,000 and all the prices are within 1,000 to me the most intuitive solution 1,000 to me the most intuitive solution 1,000 to me the most intuitive solution to this question is the use of D programming for this question I also triy to come up with a greedy solution with preprocess results like the solutions I derived for Leo 122 123 and 188 eventually I could not think of any greedy property that I can utilize so the focuses in this video will be three variants of Dain programming Solutions the first solution I want to cover is the so-call tap down Dain program which is similar to the one that we use to solve theod 188 if you haven't watched that video I will strongly recommend you to check that one out first as usual we to think about the Transitions and statuses let's start with the statuses this time there'll be three statuses the first one is we're are holding stock or we are not holding stock but in a down we just sell a stock right now so we cannot buy it the very next day will be not in cool down so there are three different statuses on top of that we also need to know which day we are in right so there is also the DAT Dimension and this is o n this is 03 and that's the statuses about the transitions we need to think about the transitions from each state to the other state before our Holding stock right now there will be two possible outcomes I can either Keep Holding stock or I can actually sell it and now I'll get into the cool down state How about if I'm now at cool down there's only one possible transition which is to not equal them How about if I'm not includ out right now what will happen next I can either do nothing I will SK at this state that in cool down or I can actually buy a stock so I'll be holding stock are three different types of transition so this is O three before move on let's review the top down D programming structure if I'm having a function called DP the first step will be checking the congregations like if I'm already at the end of the array I should just return some default result it will be followed by the memorization part if we have visited this status before then we should return the result immediately and it follows by a transition block which we just cover it on the right hand side and lastly you do be the update of memorization and also the return of the results right this is our second time covering this top down damic program structure so this should be familiarity all right now let's move on to the next variant of dynamic program one of the obvious strength of using tap down di programming is most straightfor solution derivations however most of the time the alternative button up dynamic programming will be faster or have lower constants in the time complexity on top of that in some cases the button up version can even have better time complexity or space complexity in the Big O notation that's the reason why we should learn how to derive both of the solutions now let's do bottom of the program one trick to keep in mind is that the traversal order between top down and bottom up di programming is usually the opposite because we are now trying to push the current answer to the Future sub questions instead of spinning out to the future questions then using the future answers to update the current answer let me elaborate on this these are the previous transitions between status for T down algorithm for example if I don't know the max profit I can get by holding a stock at the beginning of the day I will delegate that question to two scenarios in the future holding a stock at the beginning of tomorrow versus selling a stock by the end of today and getting to cool down by tomorrow basically I dedicate a question to the Future and I will figure out the maximum value by doing these two actions and then update this H do status however in the bottom up version the holding to status this status to figure out how it is updated now the host do status for the future that say i+ one do status for the future that say i+ one do status for the future that say i+ one will be actually a maximum of poock I and not in cool down right you can see the direction is the opposite now we are trying to update this post stock from here and from here let's take a look at other example cool down in i+ one will'll be from Whole down in i+ one will'll be from Whole down in i+ one will'll be from Whole stock only h stock I now let's look at the last example star cool down I + one will be from the maximum of P I + one will be from the maximum of P I + one will be from the maximum of P down I and not in qu that's how we update the three different statuses in the bottom up di program so you can see the order is totally the opposite now let's think about how this done in the full loop have a full loop from I = to 0 to nus1 have a full loop from I = to 0 to nus1 have a full loop from I = to 0 to nus1 and keep doing this and in this approach we you have three arrays post not in cool down and cool down arrays each with n+ one space complexity however if with n+ one space complexity however if with n+ one space complexity however if you take a closer look we are always using the I value to update the i+1 using the I value to update the i+1 using the I value to update the i+1 value uh optimization we can have is to reduce this space complexity from n to just o1 we just need to have three arrays of two values this trick is called the use of roading array and this is example of how you can get better space complexity from using bottom up di programming rather than the top down di program right now let's move on to the coding part and we'll Implement all three variants of the solutions now let's start with the implementation of the tap down PP algorithm we will first start with having these variables as instance variables so that we can use later I need to know the lens of the array and also need to deal with theorization part which will be none or un three because there are only three states we care about which are holding the stock or pull down not in and to have this sta for each dat and here I will need to make a code to the program function starting with Day Zero or the first day and the status I will start with the status with n qu so I can buy the stock at the very first dat now let's fill in the content for the DP function it's again a instance function there will be a position it's integer and also the status which is also integer ranging from 0 to two we return integer as the mixed profit I'll start with the check on the cloner cases position if it's at the end of the array I will return zero directly because there's no more profit I can get after that I will need to check if self record position status has been visited if this is n none I should just return this value directly because we have visited this status before and know the answer at this moment other than that I will need to actually do the transitions there will be three cases when St is equals to zero something if it's one we can do something else and at the end the state is two after the transation updates I will need to keep this value in a record self. record position status will be updated with the prop this next proper right now if we are at the status of hold your stock what will happen next the next profit will be from two cases the first case is that I may be at the same Holding stock stus so s. DP position plus one that be staying at zero or I can actually sell a stock so move on to the next stage but once I sell a stock I'll be in a CO status I can get the price of selling that Stu now when I'm in the status of in coold down there's one option for me which is. DP plus one and move on to no cold down status so I can buy a stock afterwards lastly if I'm now in a no cold down status get two options for I can either do. DP position plus one and stay at the same status or actually by the stock will be + one in actually by the stock will be + one in actually by the stock will be + one in the Holding stock status minus price I pay to buy the stock now I see if it works again we need to add self notation in these places all right now we pass the test cases and let's do submission you can see the speed is pretty decent at around 45 Ms and if it's around 70% of the users but it's around 70% of the users but it's around 70% of the users but now we're going to move on to the bottom up solution the speed will be even faster than this now that's start the implementation of the bottom up PP AR how we use these signatures here now this is called bottom up PP algorithm again I will first calculate the length of the array as the variables N I also want to keep the status in the variable code braet this time I would like to initialize the values with negative infinite number the infinite number needs to be large enough such that will never reach this value I will say like 10 million should be large enough now I would do minus infinite number for underscore in range three if is for n+ one array here now three if is for n+ one array here now three if is for n+ one array here now remember that before we start the record Z and two is actually a sped starting point that's the status where at the first day we haven't bought anything so we're not in cool down I need to change this value to zero for all other cases there are all negative infinite because there are not valid cases will later update those stas now we would like to start with index from 0 to n minus one and let's think about the transitions first of all the very first transition is data zero which means we are now Holding stock now we think about how would you get to the holding status at index plus one there are actually two possibilties first of all you might be already Holding stock at index our case is you are actually not in cool down status and now you actually pay the price and buy a stock now you will getting to Holding stock status today how about the C out status you will be in COD out status today if you were selling s yesterday so who will know the record is from record index zero plus the prices you will get today let's see it's a status of that including you get here by doing two things you were either already at no status yesterday or you were at qu status and after day you are not in qu anymore now at the end once we update the record end times now everything should get into record and position there are three status here but actually we don't care about the first status zero because at that status we're still holding a stock so that will not give us the max profit we can skip that one and just doing the maximum value between n one which means you just sell a stock or you'll be Reger than two which means you seller stock slightly earlier and now you are in no SC status and now let's do a run to see if it works okay it pass two cases and that's not to submission okay you can see um it's slightly faster because we now save quite some time from not doing recursive function the last impementation we cover is to do bottom up but with rolling array again I will copy paste this function and come in this part out and let's do the r array first the change needs to be done here is actually pretty small instead of actually having plus one array here actually need only two because we shrink the array from n plus1 to two I need to maintain which AR to update so I introduce a variable code black here it will be changing from Z to one back and forth this one is not index plus one anymore this one will be one minus flag so that it will be always one or zero but the flip side this one will be flag this one will be oneus flag that be flag two this it's also flag and the array we need to F all right now let's see if it works let's do run here okay you pass all the test cases and do submission you can now see HP is around 95% of users the reason it is faster is 95% of users the reason it is faster is 95% of users the reason it is faster is because previously we actually need to do the initialization for the huge record array but now you don't need to do so you only need to do it for the first 01 element and then later on the update will happen automatically these are three different variants of the implementations to solve this question and I hope that you like it thank you for watching
Best Time to Buy and Sell Stock with Cooldown
best-time-to-buy-and-sell-stock-with-cooldown
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[1,2,3,0,2\] **Output:** 3 **Explanation:** transactions = \[buy, sell, cooldown, buy, sell\] **Example 2:** **Input:** prices = \[1\] **Output:** 0 **Constraints:** * `1 <= prices.length <= 5000` * `0 <= prices[i] <= 1000`
null
Array,Dynamic Programming
Medium
121,122
1,802
Hello friends welcome to code Sutra in this video we will be solving Lead Core product number 1802 maximum value at a given index in a bounded array in this problem we are given a value of n that will be equal to the size of the array for example here we are given n is equal to 6 so the size of the array will be 6 then we are given a maximum sum that is the sum of this array cannot exceed 10. so if we take this example what is the sum of this array it is equal to 10 so it is not exceeding the given value and we are also given an index in this case the index is equal to 1 at this index you have to form the maximum value for example this is the maximum value that we can put here and there is a given constraint what is that the elements difference cannot be greater than 1 that is the adjacent element cannot difference cannot be greater than one for example here it is 3 can we put 5 here no this is this won't be a valid sequence similarly this is a three and this is will be a one is this a valid array no this is not valid so the difference between any two consecutive elements can only be one and we have to make this element as the maximum element so let's take another example can we form this array 3 4 3 2 1 and 1. no why because this sum will be exceeding more than 10 so this array is invalid so let's take one more example here it will be two one and one yes this is a valid array why the sum is lesser than 10 but the point is this value has to be maximized that is in this case we can take this value up to 3 so 3 will be our answer so we have to return what is the maximum value 3 in this case so let's look at the very first approach that will be Brute Force approach we'll take the same value the first thing that is given here is all the elements have to be greater than 0 that is all the elements let's make uses one there are six elements all the elements will be equal to one now what is the idea is we have to increase the value at One how can we increase it we will just increase it one two one what will be the sum in this case the sum will be equal to seven it is still lesser than 10. so now let us try to increase it to three can we increase it to three no right so what is the idea we have to first increase the adjacent elements one by one so in this case the sum will increase to 8 similarly in the next case the sum will increase to 9 and in the next case again the sum will increase to 10 and in this scenario we can just stop it but definitely this will take a very huge time complexity but the basic idea what we are trying to do is we are trying to form a peak element here one of the quick observation that we have to form in this is these elements form the peak element and any element on the left side and on the right side will both keep on decreasing this is one of the quick observations that we have to draw let me give you a different example and let us Approach at the binary search for example we will do the same thing 1 so here we have to put the maximum element right so let's assume the maximum element value will be 5 for example one five one so this is not definitely a valid right so let's make it valid how can we make valid Phi 4 3 2. then four and three but is this valid no right this is not a valid thing so the idea is we will keep a given range for this what will be the range will start from 1. and the range will be equal to maximum sum so 1 to 10 what we can do is say for example the mid equals Phi so if it is not possible with Phi itself can we make this value as 6 or can we make this value as 7 no right so if 5 is only not possible we can eliminate all the other values that is 7 8 9 and 10. so first thing that we did is we kept a range that is between 1 and 10 so once we identify that it is not possible with 5 what we did was we eliminate all the other choices similarly say it is possible with three it is possible with 3 right so then it is meaningless to check two and one why because it is possible with 3 why do we want to check for two and one so that is the core idea of binary search what we are doing is we are finding an element sorry we are finding the peak value then we try to form an array such that the sum is minimum and if this sum is lesser than this maximum yes the array will be valid and this peak element is also valid let me explain the possible function once again that is if this is valid or not let us take this example and we wanted to make this element one and one so let's make this element as 4. this will be 4 and this will be 1 and 1. so what is the idea here one two three four then three and two if you look here this is the minimum sum can we reduce the sum any further no this is the minimum possible sum that you can form with this peak element so if you look here very carefully this forms an arithmetic progression on both the sides what is an arithmetic progression this is increasing from this side and this is decreasing from this side and this forms the peak element there is one more scenario also say there are eight elements one then it will increase to three four three two so this is also one possible scenario that is there will be ones previously but the arithmetic progression will start at some point and will end at the peak then again it will form an arithmetic progression with the difference as minus one so that is the core idea and we will add both this sum and if the sum of these both is lesser than the maximum sum given yes this particular value that is 4 will be valid that is the maximum number will be valid so without further do let's dive into the code what are we doing here first we are writing the is possible function we are taking the left value for example here right so why are we picking this left value why because the one can start from anywhere so what are we doing here the left value will be equal to Peak minus index and r0 why because it can go lesser than zero in this first scenario we saw right that is it can start from here also 2 3 so the thing is it need not start from one it can start from any other so we are trying to find what is the left value and here we are also finding the sum or the sum of all the numbers on the left so what is the formula that we are using here it is just equal to n by 2 into a 1 plus a n what is A1 is equal to the first element of the arithmetic progression and a n will be equal to the last number of the arithmetic progression and what is n is equal to number of elements so we are first finding the left sum then we are going to find the right sum whatever will be on the right side of the array so then if this sum is lesser than the maximum yeah we written that this particular element will be true so why are we subtracting because this element will be added twice right so we are subtracting the Peak from that then what is the main function actually the main function is we have defined the range here the range is from 0 to the maximum and for every value just like we did 1 to 10 we are finding the mid value say 5 in this case we'll check if it is possible for Fiverr Rod if it is not possible straight away eliminate 5 to 10 all these values are eliminated that is the right will change from mid to 1. similarly if 3 is possible we will eliminate one and two what are we doing here we are just changing left equals to Mid finally we will return the final value that is equal to left plus one thank you for watching the video please do like share and subscribe
Maximum Value at a Given Index in a Bounded Array
number-of-students-unable-to-eat-lunch
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of all the elements of `nums` does not exceed `maxSum`. * `nums[index]` is **maximized**. Return `nums[index]` _of the constructed array_. Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise. **Example 1:** **Input:** n = 4, index = 2, maxSum = 6 **Output:** 2 **Explanation:** nums = \[1,2,**2**,1\] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums\[2\] == 3, so 2 is the maximum nums\[2\]. **Example 2:** **Input:** n = 6, index = 1, maxSum = 10 **Output:** 3 **Constraints:** * `1 <= n <= maxSum <= 109` * `0 <= index < n`
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Array,Stack,Queue,Simulation
Easy
2195
287
hello everyone welcome to day 29th of march liquid challenge and i hope all of you having a great time today's solution would be 634th video of the lead code daily challenges that we have been solving from past one and a half years and the question that we have in today's find the duplicate number here in this question we are given an array of size n plus 1 also it is told that all the elements will be in the range of 1 up till n inclusive that simply signifies that one number will be repeated twice in this input array what we need to do we need to identify the duplicate number that is present in this array also the question states that you should solve the problem without modifying the nums array and you should only use constant space to come up with the algorithm so these examples are pretty easy to understand here the duplicate element is two and this is what we need to return i'll be solving this question using four different approaches we'll go from the naive approach to the most optimized approach and let's get started with the presentation that i have created for this also in case towards the end of the video do you have any feedback or queries feel free to ping me on telegram group or discord server of coding decoded looking forward to seeing your messages now let's get back to the pvt find the duplicate number lead code 287 it's a medium level question on lead good and i totally feel the same so let's get started let's assume you're in an interview and the question is given to you the example is in front of you the knife or the basic approach that comes to everybody's mind is to sort this array up so when we'll sort this array what do we get one two three four and now we can use a single pointer and check whether the current element happens to be equal to the next immediate element if it is then we identify the duplicate element otherwise if it does not we keep on iterating through the entire array the time complexity of this approach is order of n log n y n log n because we have sorted this input array up the space complexity is constant time can we improvise this the answer is obviously yes let's walk through the second approach now the interviewer wants you to reduce the time complexity how can we do that what we can do we can simply create a frequency map and using that frequency pump what we will do will i will store the frequency of each element that is present in our input array for example we have one we have two we have three and four will iterate through the entire iron we'll store it's the frequency of each and every element the frequency of one is one the frequency of two is two the frequency of three is one the flat of four is also one and now we'll once again i trade through the array and check where the frequency is greater than 1 you'll be able to find that at 2 and that becomes your answer so this is your another approach time complexity of this approach is order of n because you are iterating through the array linearly and the space complexity is again of order of n because you are using extra space now this frequency based approach can be replaced by sets so you can create set and you will keep on adding elements onto it as soon as you see that an element is already present in that set which you are trying to add you simply say it's a duplicate element for example you see one so you add one to it you see three you add c to it you see four you add four to it now you see two is not part of the set you add two to it and when you are iterating through the last two you see that two is already part of that set that means it's duplicated again the time complexity of this approach is order of n the space complexity is again order of n can we improvise it further the answer is yes now let's talk about the third approach where the time complexity would be the order of n and space complexity would be constant time also we are taking an exception here to what was specified in the question we will be modifying the input array to understand it better let's get through the example so we have the input areas 1 3 4 2 and here in this approach we will be exploiting indexes as frequencies so let's get started in the first go what will i do i will simply reduce each and every element by 1 so that the elements lie within the range of 0 till n minus 1 the indexes and the values come in parity with each other now let's start the iteration here the index that you see is zero so what do you check the corresponding value the value is again zero so you jump on to that value which is zero and you simply negate it up so you now we have minus zero over here let's proceed ahead and this simply signifies that zero has been visited or seen in your range let's proceed ahead next we see is one so what element do you see at one you see two so you go to two you jump on to two and you simply negate it up that simply signifies that two has been visited in the past let's proceed ahead next we see is 2 itself so what value do you see minus 3 over here so since it's already negative you take the absolute value and let's go to 3 and we simply negate it up since uh we are negating the value at three to the third index that means uh three has also been visited in the past now let's proceed ahead next we see is three itself and at three the value happens to be minus one we take the absolute one and we jump on to the first index happens to be this one and we simply negate it up that simply signifies that one has been seen so far now comes the most interesting case so you see four at four what value is it you see one so you jump on to one this time we're going back to one and what do you see here now you again tried negating it up however the value is itself negative in nature that simply signifies that one was also visited in the past as a result of which it's a duplication scenario this is the way when we can say that one as an index was duplicated so since we subtracted 1 initially from our input array we'll again add 1 to our current index 1 plus 1 gives you 2 and this becomes your answer however the trick here is we have exploited indexes for keeping track of frequencies and we have modified the input array is there any other solution where multiplication is not at all needed the answer is yes which is that approach fast pointer slow pointer is the way to go we will be exploiting the property of cycle detection in a linked list to solve this question how can we apply this algorithm onto this problem let's walk through it so here let's take the same example that was specified in the question we have elements as one three four double two and let's start the iteration at the zeroth index what element do we see one here and from one where is the next connection going let's go to one and check there's a connection from one to three value so let's create a node starting from one and it is connect getting connected to the third value and from three where is the next connection going from three we have the connection to two so let's create from three a new node till two from two where is the connection going from two the connection is going to four so we have 4 over here and let's go to 4 and from 4 where is the connection going it is going till 2 so from 2 we from 4 we have a connection going till 2 and what is the most interesting part if you carefully observe the starting point of your cycle in your linked list is a point of duplication there could have been more elements involved at the intermediary steps however what we are interested in finding out the first position where the cycle is getting started which is 2 and that becomes your answer this is a very famous interview problem based on the concept of linked list we've already solved it plenty of times in the past i'm attaching its link in the description below do check that video out if you want to know more about cycle detection in a linked list problems now let's get back to the coding section and conclude this approach so here for the very first time we are seeing the practical use case of cycle detection in a linked list concept in general and it's slightly difficult to think on these lines in an interview unless you're you haven't done or read similar questions in the past but so don't get disheartened if this approach did not click you in the first go we all are in the learning phase to conclude it further let's quickly walk through the coding section and let's quickly find out how easy and simple it is to write the code here i've taken created two pointers slow and fast both of them pointing to the same location which is nums of zeroth index so in general uh in cycle directional linked list problem remember slow pointer moves by a single position fast pointer moves by two positions so i've added a do while loop here because i want this operation to run at least once and i'll keep on moving ahead till the time my slope pointer is not equal to the fast one with each iteration my slow pointer takes one step and fast pointer takes two steps so slow equals to numbs of slow and fast is equal to numbers of fast is a first step and again you are indexing it using the dumps array that means it is taking two steps once we are done with this we are able to identify whether there is a cycle in the system or not so it's again the same concept once this loop breaks what do we reset the slow pointer from the starting position and again we keep on iterating till the time my slow pointer is not equal to the fast one and as soon as they become equal that point becomes your point of sight starting of the cycle in your linked list so it's again the same concept exactly same formula that we used to solve the linked list problems uh and this brings me to the end of today's session i hope you enjoyed it the time complexity over here is order of n and the space complexity over here is order of one i hope you enjoyed today's session if you did please don't forget to like share and subscribe to the channel thanks for being here have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question signing off your friend your mentor your catalyst in this journey of yours sanchez take care sayonara
Find the Duplicate Number
find-the-duplicate-number
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. There is only **one repeated number** in `nums`, return _this repeated number_. You must solve the problem **without** modifying the array `nums` and uses only constant extra space. **Example 1:** **Input:** nums = \[1,3,4,2,2\] **Output:** 2 **Example 2:** **Input:** nums = \[3,1,3,4,2\] **Output:** 3 **Constraints:** * `1 <= n <= 105` * `nums.length == n + 1` * `1 <= nums[i] <= n` * All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times. **Follow up:** * How can we prove that at least one duplicate number must exist in `nums`? * Can you solve the problem in linear runtime complexity?
null
Array,Two Pointers,Binary Search,Bit Manipulation
Medium
41,136,142,268,645
1,020
today i'm gonna show you how to solve legal question 1020 number of enclaves basically you're giving our m multiplex n binary matrix grid look like the example here and zero represents c and one represents land cell a move consists of walking from one land cell to another adjacent so it's four direction it's not like all direction it's only basically using this one cell as an example you can only move to the left the right upper and down that's basically four direction land cell or walking off the boundary of the grid return the number of land cells in grid for while we cannot walk off the boundary of the grid in any number of moves looking at the example here and the this is the input and the output is 3 here and the explanation is there are three ones that are enclosed by zero and a one that is not enclosed because it's on the boundary so this one is does not count because it's on the boundary and let's take a look at another example this is the second example and the output is zero the reason is because all ones are either on the boundary like in this case or can reach the boundary so these ones that does not count at all because they are connected with the boundary it can reach the boundary so they cannot count and then these ones that they cannot reach the boundary at all and then they cannot walk off that's why they count so basically what this question is asking is that you need to write a function to count the ones that are inside that's not connected to all the boundary so let's think about what we can do here and the first thing came to my mind is that this is a graph problem right and you want to use um uh depth or search in this case to basically find all the ones and you want to define or that for search function to count all the ones first and to make sure you don't visit the cell that you have already visited you should use a visit set so that it won't visit again and then after that the trick of this problem is that you don't want to count any ones on the boundary and also you also don't want to count the ones are connected with the boundary so in that case after we have that function what we can do is we want to iterate through the graph on the uh this row and the last row here and then these cell just we want to iterate through everything on the boundary and the boundaries neighbor to make sure that we don't count these once we visit these and we add them to the visit set and then we can run the defer search function in the middle section to make sure we count the ones um because the boundary and the boundary's neighbor already added to the visit set so when we count the ones in the middle section we won't count them again so basically that's the thought process and i'm going to show you how to do this in code here typically uh you want to define a graph and the rows and calls equals this is basically just how you uh define a graph in the in python and then this is lens 0 and like i mentioned that i don't want to visit the cell that i have already visited already so i want to use a stat for visit is it can't type today um and then we want to rule out some edge cases like if not grid simply grid does not exist or not a grid zero then we want to return zero right in that case that's zero cell the output will be zero so the most important thing is we want to define the uh that first search so for the different search i'm gonna pass two parameter one is the row and the other one is the colon so if the uh row is in uh is in the boundary like this is within the boundary and zero is um the colon is also within the boundary and the grid if the grid row column equals 1 right and if the row and the column not in visit i have not visited this yet if all these uh requirements emit basically uh within the range and the ones are uh the value of the cell is one and also i have not visited i want to add this row and column pair to my visit set so that i won't visit it again once i add it to my visit set i want to visit its neighbors basically that first search um all four directions it said that this one is adjacent for direction list so i'm gonna do upside and down four times and it's pretty straightforward and the neighbor will be r plus one minus one and then the colon plus one and the colon minus one so that's it of the uh that for search function then the next step i'm gonna do is what i wanted to do is i want to iterate through all the cells in the boundary and find out their neighbor to run that for search on these so make sure that the boundary cell and the island that are connected to the land that are connected to the boundary are added to the visit set so when i actually count the middle numbers i won't visit the boundary cell again so to iterate through these boundary lists i will have to do the rows and the columns so basically for row and range um rows every single row right i don't i want to run that first search on the row and the column i want to do um zero so every single row and i want to do column zero and i want to run the different search on the row and then the colon minus one it's basically what i visited is this that's the default search r and zero and then the next one i wanna do that for search on is the r and the columns minus one so it's basically zero here right so i visit these so the next for loop i want to iterate through the columns so the columns we only need to do these two and then these two right so for c in range um it will start from one instead of zero because we have already added so column minus one i want to run that for search on row zero and then the colon so one row zero right and then the and then i also want to run that first search on rows minus one basically it's the last row and then the column will be the column that i have specified basically this guy and this guy right so after these two for loops and i have already iterated through the boundary cell and then the boundary cells neighbors because the deficiency the data search function itself actually already went through their neighbors so then the final step what i would do is i will start counting the result right let's give it a result to uh s0 for our in range rows so every single row for c in range of calls so every single column that if grid r c if the grid value equals one so in the middle section if it's one that i will count it and another big requirement is that the row and column not in visit because in these two steps i have already visited the um the boundary cells so i don't want to visit these again and then once every time i found one cell that meet this requirement i want to add a one to the result and then after the entire for loop i want to return my result yeah that so basically that's it for the code and by doing this you should be able to calculate the output let's see if we can get through okay the output is expected okay great so i hope this is helpful and let me know if you have any questions and i'll have more questions coming for you and i'll see you soon bye
Number of Enclaves
longest-turbulent-subarray
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
Array,Dynamic Programming,Sliding Window
Medium
53
1,354
That a hello everyone welcome appearing to lead us in this question has constructed with multiple sources 200 Dhanshyam Security Question Ijhaar Development Course and let's look at presentation to have created for the solution all subscribe to is band kiska table 116 magic trick apna adhir ve subscribe The Amazing To Do Subscribe That With Any Element In Year For Example Gray Water Total Form Of The Informative And Subscription Me Unwanted This Updater Total Time Hits 59 Midsummer Night's Dream Place The subscribe and subscribe the Video then subscribe to subscribe button Take from this is Not Important Fuel Total The Tarzan Subscribed To Select One To Understand And Solution And Instead Of Going From All Want To Get There Will Be Removed From To All World Withdrawal Awal Thursday That Singh And This Not Important Will Avoid A Mins Of Priority Young Brigade Improve Death Toll Tax Return Below A Quarter Total Sound Or Input Target Are Down 0 That In Its Affidavit Right To Food Elements Of Priority Q Midning Maths Evil Elements Of Obscuritism Subscribe To 56001 To Target 9315 Total Committee 0 Are Absolutely Powder Maximum Element From Private you which indicates 9 and will write thing would that particular inductive one to three for lips united states of knowledge and was difficult subscribe to that x plus 800 options interviewer replace the total song with reduced to 100 years in the native the police tried to go For More Element Is Quite Maximum Interactive Elements 5.5 125 VS OnePlus 3T Elements 5.5 125 VS OnePlus 3T Elements 5.5 125 VS OnePlus 3T A Plus And Will Absorb Zoom Element Are Withdraw From Do Subscribe My Channel Subscribe Se Zara Subscribe To A Limited Time And Uses Same Input And Do Not Push Hard Since 1995 What Is The Meaning Of Elements In The World Channel Subscribe Now To Receive New Updates Subscribe - - - - 2 Subscribe - - - - 2 Subscribe - - - - 2 Hello Friends Reduce Wali Anil 8128 &amp; Hello Friends Reduce Wali Anil 8128 &amp; Hello Friends Reduce Wali Anil 8128 &amp; Displaced 0 - No Comments Subscribe Like Subscribe &amp; Share &amp; Subscribe &amp; Share &amp; Subscribe &amp; Share &amp; Subscribe Elements That Will Give A Total Element Which Will Update - Subscribe To Will Update - Subscribe To Will Update - Subscribe To That Saurabh Updates Total K Updated By 9 Maths Plus 110 More Total Five's Hunter Flight Maximum Element Amendment Pims Side End Skimming Subscribe My Channel Not Subscribed One Right Is This Logic Helps Reduce Also Calculating The Evening Elements Every Time And Result Of Which Will Make Him A That Naturally Chronic Professional Examples Pet Do Subscribe Button Adhuri Arzoo subscribe and subscribe the Channel subscribe to subscribe and subscribe the hai to yeh ulta delete indian art work pimple hai saunf 125 will do subscribe The Channel Please subscribe and subscribe our end of leucorrhoea related 191 Then Display Multiple Times Subscribe What Do You Mean Equal To That When Difficult-2 Next9 Defense That When Difficult-2 Next9 Defense That When Difficult-2 Next9 Defense Institute - Marine Decision No That Institute - Marine Decision No That Institute - Marine Decision No That Instituted Of - Time Multiple Times Instituted Of - Time Multiple Times Instituted Of - Time Multiple Times Software Update Please Subscribe Modification Very Good So Subscribe My Name Is The Meaning Of Element Subscribe 496 Subscribe - To The Element Subscribe 496 Subscribe - To The Element Subscribe 496 Subscribe - To The Meaning Of Roop Un To Interpret That Adalat And Milk Ashwin Process And Blast Box Mein Remedies To Samudra Meaning Elements 122 And Will Be Replaced Sure Updated Lutb Scan More Subscribe To New Delhi Main Terminal Total Is - Max Element Which All Functions And Is - Max Element Which All Functions And Is - Max Element Which All Functions And Africa Tube School Maths Elements Of Equal To Medium Total Subscribe Button And That Electrolyte Negative How To Recite One I Meaning Total 20 And Marks Rajput Is Loot Subscribe Your Voice Mail Express And Calculate Updates Owner Interrupted Not Equal To Are Next Serial Motors And Then Meaning Total Beach Explained The International Ismail updated this 0.1 International Ismail updated this 0.1 International Ismail updated this 0.1 President Twitter The Amazing Maths All Will Update The Total Plus In The Evening Total Is A Positive And Will Simply Return Roar When School K Subscribe To A Logic Section Onto Trimming Mute Total - Serial Line Number Twenty One - Serial Line Number Twenty One - Serial Line Number Twenty One A Place For Total Line Number Team Is Tweet Total Strong A I Want Her Close Moment So Let's Type Of Tattoo Intention Knowledge Tiger Shroff Absolutely Near A Good Leader Submitted That Accepted Problem First Time Complexity Based Approach Time Complexity Border Login Log in and suites complexity is ignorance mode of and giving priority question for solving problem thank you for watching my video by not difficult problems do you do subscribe in interview for this problem with us a flying Jatt day session please don't forget to like share and subscribe Our Channel for Grade S
Construct Target Array With Multiple Sums
find-players-with-zero-or-one-losses
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat this procedure as many times as needed. Return `true` _if it is possible to construct the_ `target` _array from_ `arr`_, otherwise, return_ `false`. **Example 1:** **Input:** target = \[9,3,5\] **Output:** true **Explanation:** Start with arr = \[1, 1, 1\] \[1, 1, 1\], sum = 3 choose index 1 \[1, 3, 1\], sum = 5 choose index 2 \[1, 3, 5\], sum = 9 choose index 0 \[9, 3, 5\] Done **Example 2:** **Input:** target = \[1,1,1,2\] **Output:** false **Explanation:** Impossible to create target array from \[1,1,1,1\]. **Example 3:** **Input:** target = \[8,5\] **Output:** true **Constraints:** * `n == target.length` * `1 <= n <= 5 * 104` * `1 <= target[i] <= 109`
Count the number of times a player loses while iterating through the matches.
Array,Hash Table,Sorting,Counting
Medium
236
49
Hi gas welcome back to my channel so today our problem is group anagrams so what have you given us in this problem statement here we have given an add of stings what do we have to do with this TRS name type of anagrams You have to return by grouping, this can be in any of your orders. Now we have to understand what is this anagram, so we will understand all this through the example. Okay, so see what we have been given. Hey, we have given the string like you. Take this word, it has been made, now how many words can you make by combining these three words, how many words can you make by doing the latest of these three, what will be the sum or grams, what will we call it, we have to group them, okay And what do they have to do, finally we have to return it can be in any of our orders, so what will be the answer to this, see, it is not necessary for you to come in the order in which it has been placed, okay, what is your body after that, what is in it? The latest thing has been done to him, the material from this has also been done to him, so what will have to be done, we will have to keep these two together, right, after that, the matter is that he has no one in his group, so what will be this simple, he will remain alone and we What to do, then this will be returned, this is done, these two of you are in one group, these three are in one group, so now how will we solve this problem, see what will we do to solve this problem, see, if you have This has been given, this has been given, so you know how it has been done, then if you sort these three, then after shortening them, only one word will be formed. If you sort it, then what will be formed, 'et' will be formed. Okay, after sorting this, what will be formed, 'et' will be formed. Okay, after sorting this, what will be formed, 'et' will be formed. Okay, after sorting this, people, now it will become at, you will sort this also, at will become right, so what will we do here, what will we do with this, what will we do with each word, we will sort it, okay, we will sort it and after sorting, So if there is only one, then we will keep it as 'A' in front, So if there is only one, then we will keep it as 'A' in front, So if there is only one, then we will keep it as 'A' in front, okay and we will take the map, we will store it in the map, whatever comes on it, you keep storing it on it, which word will it be, okay which word. This is being formed after shorting, so go into it and keep storing it. How will you do it? Like you have an AAT, if you solve it then what will become of your AAT, this will become your key which will be sorted, we will make a sort cookie and the original one will be called that. What will we do next, un vector sec, which will be your value, it will be a vector, okay, we will insert e80 in it, then we will come to this, if you solve this also, then this will become at, no, then this will be its tomorrow that we will insert in this. So what will we do with this, we will insert it in this because our value is of vector type and this is your string, so after sorting, this will be the result, after that what will we do, we will insert this in this, then on 10, you If you sort then what will happen is A &amp;T will come here and what will we &amp;T will come here and what will we &amp;T will come here and what will we do in it, we will insert 10 which is the original word in it, okay in the vector, after that we will come and solve Aate, then what will become At will become which is this, so what is this What will we do with the original that comes, what will we do by inserting it in it, after this neither T will come nor if you sort T, then what will become A&amp;T i.e. if it is of then what will become A&amp;T i.e. if it is of then what will become A&amp;T i.e. if it is of then insert it in it and after doing 80 it is ok. This will come, if you do Bed then ABT will become ABT, now what will you do, you will insert the original word into BAT, okay, now what will we do, what is the second value of the map, what is the second value of this? We will set a vector min. This is a vector, so this will be the 2D factor. Okay, the answer will be today's vector. We will pick this vector and keep it here. It is done, then what will we do with it, we will take 10. Okay, then let's talk. We will take this and return it, okay, and what is yours, what is the mapped string, and what is the second value, what will be the value, what will be your vector of string, okay, when what we are going to do in this is the original word, we will sort it and which The original will be inserted in the vector, what will happen from this, you will know that after sorting, all the anagrams will be from the same key. Okay, so whatever will be in the vector, we will set it as the original. We have to get it into a group. So what will we do here, we will insert the original string here, we have inserted the star here, what will happen after sorting from Ki to Ki, it will be from Ki to Ki in a group, A, I, now I am your A. Now what will you do, you will insert the second value of the map in the answer vector, it is okay because we have taken this 2D factor and its type is the type of map, the second type is also a factor, so here this Simply you will insert this then what will you do with the answer and you will return it ok because your solution is done. If you liked the video then please like, share and subscribe.
Group Anagrams
group-anagrams
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** strs = \["eat","tea","tan","ate","nat","bat"\] **Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\] **Example 2:** **Input:** strs = \[""\] **Output:** \[\[""\]\] **Example 3:** **Input:** strs = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strs.length <= 104` * `0 <= strs[i].length <= 100` * `strs[i]` consists of lowercase English letters.
null
Hash Table,String,Sorting
Medium
242,249
256
today we're gonna be going over a leak good question called paint house paint houses a question that's commonly asked by LinkedIn so the problem description says there are our Arobin houses each house can be painted one of the three colors red blue or green the cost of painting each house with a certain color is different yet to paint all the houses such that no two adjacent houses have the same color cost of painting each house with the certain colors represented by an N by 3 matrix for example cost 0 of 0 or the top left corner is a cost of painting the house Sierra with color red cost one of two is a cost of painting house one with color green and so on find the minimum cost to paint all houses and just as a quick note we're told that the cost is all positive numbers or all of them are positive numbers so if the input is this we want to output 10 because 10 is the minimum cost of painting all the houses the explanation says paint how zero and blue paint house one green a paint house to blue so therefore 2 plus 5 plus 3 is 10 so this isn't too tricky of a question I know it sounds kind of confusing but when we think about it all we really have to do is pick a color paint the house that color and then in the next iteration or on the next row of houses we just have to pick the minimum between the two remaining options right so if we just painted house red we can no longer paint the next row red so following that logic we can just kind of calculate oh if we choose green here what's the next best thing to choose if we follow that so let's take an example here so if we had these as our houses which just go down here to visualize it so let's say these were our houses and let's say we just picked 2 right so the first row is 2 I don't really remember what color that corresponds to let's say it's red on the next row of houses we know we can't pick red right because we just did so we just have to choose the minimum between green and blue in this case so we would take 5 and then since we took 5 we know that we can't take you know 19 because that would be green again so we have to choose between 14 and 3 so we try and follow that logic I think we could basically populate all the totals up till the rough last row and then simply in the last row of houses we're in our cost array the last row right at the end all we had to do is return the minimum of these three values so let's try and start formulating a solution so the first thing I always like to do is have error checking right so if cost is know or cost that length of 0 we really have no houses to paint right there's no cost to rice so we can't really do anything we're just gonna return 0 because that's the minimum cost of painting no houses now we're not in this case we just need to iterate through the houses but we want to look backwards right so I want to say something like from these houses let's assume that I picked one of these colors and let's say right here let's say maybe I picked 2 which corresponds to red I can't pick 16 here so I have to choose between 16 and 5 and obviously we said we want the minimum so we're gonna pick the minimum between those two values so looking backwards will set I equal to 1 let's start we'll say I less than costly I plus and so now we just have to do that logic that we just talked about so we want to add 2 costs of I 1 let's do 0 first we're gonna say plus equals the minimum right so we'll say math dot min costs of I minus 1 and we can't choose the 0th index right so we want to choose the other two so we'll say 1 and cost I minus 1 - now for the similarly for the minus 1 - now for the similarly for the minus 1 - now for the similarly for the next color right I of 1 we're gonna do the same thing but the indices will be slightly different so we can't pick one so we have to choose 0 or we have to pick 2 so cost I minus 1 and 2 and then similarly same thing here I and now our l2 plus equals math min cost I minus 1 and now we want to choose between 0 and 1 and now finally at the end of this all we have to do is return math dot min and now we just want to look at the three values at the end right so in this case it would be here and we would have you know previous values into these rows and we would just choose the minimum between the values in our last room net so we can just do a quick math op min so if a mass out min of cost length minus 1 0 cost the cost of cough stop length minus 1 and we'll throw this in a math up men so that we can just have one statement here so these two will be minimized inside this math Amin and then we'll just check the third value so we can say again cost and cost outline minus one and here we want to check two okay so I think that should do it let's check it out see if this works awesome it does let's check out the details and the details tell us that we cut past 101 out of a hundred little test cases and we're hungry clothes inside awesome so that's how to solve elite code question paint house again this is a common interview question for LinkedIn and definitely there are definitely similar problems for Google and Facebook and other companies are big tech companies so this is a great question to know you guys have any questions be sure to leave it down in the comments if this helped you be sure to subscribe to try and release a video every single day so that basically every day you guys cannot practice and any question yeah if this helped you guys give it a thumbs up and good luck on your interview so I'll see you guys next time
Paint House
paint-house
There is a row of `n` houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by an `n x 3` cost matrix `costs`. * For example, `costs[0][0]` is the cost of painting house `0` with the color red; `costs[1][2]` is the cost of painting house 1 with color green, and so on... Return _the minimum cost to paint all houses_. **Example 1:** **Input:** costs = \[\[17,2,17\],\[16,16,5\],\[14,3,19\]\] **Output:** 10 **Explanation:** Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10. **Example 2:** **Input:** costs = \[\[7,6,2\]\] **Output:** 2 **Constraints:** * `costs.length == n` * `costs[i].length == 3` * `1 <= n <= 100` * `1 <= costs[i][j] <= 20`
null
Array,Dynamic Programming
Medium
198,213,265,276
1,601
Hello friends welcome to code Sutra let's all lead code problem number 1601 on this beautiful Sunday morning the problem is maximum number of achievable transfer requests in this problem we are given an integer n which actually indicates the number of offices say we have three offices and the second thing is we have also given transfer request array this means that one wants to go from 1 to 2 and 2 wants to come from two to one for example this one Toto indicates that one is trying to go from building one to two and somebody from building 2 wants to come from two to one and somebody is also trying to go from zero to two the thing is all these offices are completely occupied and you can take a transfer request only if somebody is going out and somebody is coming in that is the number of seats won't get increased how many people are trying to go out that many people have to come in say for example two people are going out of building one then two people have to come back to building one only then you can take these two requests so what is the question is what are the maximum number of requests that you can accompany in order to achieve this that is zero influent outflow for a particular building for example in this example the first and the second request can be taken why because somebody is going from building one to two and somebody is coming from building two to one but this operation can it be taken no right nobody is trying to coming to building zero so this place one of the places here will be awakened and one of the places here will be increased so this cannot be taken the number of requests that can be accompanied is equal to two so we can at Max take two requests and make the transfer so this will be a run so how do we come up this the first thing that comes to our mind is fine we have one two and we have two one why not cancel them out right we have one two we will try to find in the entire array let's find two comma one and we will cancel this but is that going to work let's take another example for example let's take this example one two three and three one right what does this indicate this completely indicates that all of the three operations are possible though there is no two and one right so in this case our answer will be three so the initial idea of this approach won't be successful what is the next approach if you say in the problem constraint we are given that the maximum number of buildings is 20 and the second thing most important thing is the maximum length of request the maximum transfer request is equal to 16. so this indicates that this is somewhere leading us to backtracking or generate all the options that we have got for example let's take this example and try to generate all the possible options that we have got the first thing is this request what are the two options that are available to this request one is you will include this request or you will not include or exclude this request right one is you will include this or you will not include this so in this case each of this has two options so what is the total number of options we have to generate it is nothing but 2 to the power of K where K is equal to the number of requests fine right so but how do we go about generating all these options the first idea is let's take this array itself that is the request array itself and we have three buildings now the influent outflow to all the buildings is zero let's take the first request that is one comma two somebody is going to go from one comma two so what happens if somebody is going from one to two so we accept this request and what will happen building 0 there will be no change but from building one somebody is trying to go out where is he trying to go out he is going to building two so this is our first option what is the second case that we are taking up that is we will not include this if we are not including this everything Remains the Same that is 0 comma zero then again after we are done with this let's next go to the second request that is 2 comma zero here we are done with this and we have generated two options but now let's go to this request once we go to this request again we have two options here and two options here if you look here at every stage just like a binary tree or options will increase so the first thing is we will include this what happens when we include this that is 2 is going from here to here the thing is 0 minus 1 will be minus 1 but 1 will become 0 and this will become 1 minus 1 0 why because two to zero and what if we don't include it will remain as the same then again we have an option from 2 to 0 1 0 minus 1 and if we don't include any of this 0 comma zero but don't forget that here we are what are the number of requests that we are passing we are approving one request here we are approving zero request here we are approving two requests and here we are just approving one request so don't forget we also have to pass to this how many number of requests that we are approving this data also has to flow from the top to bottom we have to keep track of how many number of requests we are accepting and how many number of requests we are rejecting so once we have got generated all the options again in the next case we will be having two more options everywhere will be having two more options but let's directly go into the answer option as we know these are the true transfers where will that be coming from that will be coming from we will include the first one but we will exclude the second one and we are trying to include the next one what is the next operation that we have got the next operation is 2 comma 1 so what will happen in 2 comma 1 somebody is trying to go out from 2 that is this will become 0 and 1. this will also become 0 and the total number of requests will be increasing by 2. so this is the answer or this is our base case where all of the transfer is equal to 0 and this is the maximum that we can accompany so in simple words I will be explaining this once again what are we trying to do is the first thing is we will keep track of the transfer for all the number of buildings this is our initial thing and we have the request array right so we will consider the first request and we will be generating two options right and for these two options again we will be generating two more options and two more options until we are exhausted with all the requests and once you are exhausted with all the requests finally if the transfer array is like this then we will our answer will be the number of requests and the maximum of all these answers will be our final answer or result so what will be the sudoku for pseudo code for this the first thing what all has to be passed to this backtrack the first thing is we have to pass the index right because in which request are we trying to do at this point of time that is the first request or we are trying to do the second request so it will be told by the in int index then we'll pass on count what does this count indicate this indicates how many requests have we already processed so this indicates that and transfer indicates how many people have been transferred for example 0 1 minus 1. so this is what is indicated by transfer so what is the first option that we have got the first option is we will not care about this particular request we will just don't consider it a talk so what happens we will just increase the index by 1 our count and our transfer will be remaining the same because we are not considering this transverse or count our transfer won't change but if you want to include this these are the operations that we have to do what are we doing here is in the transfer that is in this particular array of zero we are changing increasing and also decreasing so that is what we are doing we are decreasing one and we are increasing the other so once I have done with this that is the first request we will be calling the second request what we are doing here is we are increasing the index by one why we have to call the next request and we are also increasing the count here unlike here we are increasing the count here why because we are considering this request we are approving this request so the count becomes one and our transfer array has changed but don't forget we have to also change the transfer array once we are done with this why because it has to come to the initial position after we have done this so what we are doing is whatever we did here we are just reversing that right so now what is the base case is we are exhausted with all the requests say there are fire requests and we are done with all the fire requests once we are done with all the fire requests we will check if all of them are equal to zero if even one of them is not equal to zero we'll just return it out if all of them are equal to 0 in this stage our count will be our answer and we will take the maximum of this or whatever is the already existing for example our existing answer was 3 but in this Loop we found out that four requests can be approved so our answer will be changed to 4 so that is what is happening here see uh I can understand that backtracking though it is not very tricky but this is a complex algorithm if you understand this it is very easy to solve all the problems because it's not tricky it is just a complex method to understand once I have understood this trust me you can solve all these problems straight away without even consideration you can just code the solution for all this problem so this are the problems with the increasing order of difficulty that you can consider solving to get better at backtrack we have a telegram group where we'll be discussing about this problem and the solution to this problem or if you have any doubts regarding any of these problems you can just ask me so I have mentioned the link of this telegram group in the description please do consider joining the telegram group dive into this solution so as we mentioned in the pseudo code the first thing is we'll be calculating the base case that is if we have exhausted all the index then in that case we'll be checking if there is no zeros then only we'll be Computing the answer and this indicates that what we are doing is we are approving this request if we are approving this request what happens is the guy from the 0th index is going to the building on the index one so that is what is happening here and will continue with the backtracking that is we continue generating options on this options that is what we are doing here and finally we will reverse whatever we have done here and we will consider the next option that is we will not at all include this building what happens in that case the index increases by one but the count and transfer will remain the same then finally in the main function what we are calling is we are calling this backtrack function with the initial configuration that is we are at the zeroth index and we have not approved any request so that is the initial case and all the building transforms will be zero and finally we will be returning the answer one main thing here is if you remove this backtrack and if you place it at the beginning there is a change in the time taken to run the problem please do comment in the comment section why this is happening and thank you for watching the video please do like share and subscribe
Maximum Number of Achievable Transfer Requests
maximum-number-of-achievable-transfer-requests
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
null
Hard
null