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 |
---|---|---|---|---|---|---|---|---|
946 |
hello hi everyone welcome to my channel its all the problem valid sequence is given to sequences post end for which distic feel returns through this end only used is cold have been the result of sequence after cost and mod on lamp stand for example 1ghz sequences 12345 end Points Pe Vo 500 What Will Happen Will Push Vansh Subscribe Clearly Indicating Problem Subscribe Video Also Posted By Pause 56001 On 4 Nov Epic Of Our Stags Pace Of This Element Sunil Ponytail Clerk Element Easy To Sunidhi Pop Sequence Understanding Navy Form Increment Pointer Most Loud Pointer In this will implement this is one which axis difficult to find no one will continue for the population morning take this element pitch balls to today stand now five physical safe element of this is pet out and increment our point to the nation in three is matching method Stuff Ballpoint Pen Moo Pou Interfere In The Proper In The Point Of Willpower And Still Standing Committee 1st Step Empty And Process Oil The Element In Food And Properly Which Means B312 Performs Operation Twist And Distance Tiles Near To Return Ruk Liquid Example First Will Add One To The 10.23 Example First Will Add One To The 10.23 Example First Will Add One To The 10.23 Length 4084 Zannat Pop Song Pop Out For Similarly This Matching This Point Note 52252 5.5 That Elements Such Processes For All 5.5 That Elements Such Processes For All 5.5 That Elements Such Processes For All Saint Population Will Give Key Notification Turn On This Is The Meaning Of This Is Very So Let's Quantum This 640 This Is A Pointer Representing For the population invitation and gifts avoid all elements in most a software for this in taxes imposed in veer one to three stags to portion tourist next9 then olive oil subscribe btech student from this depot that element exam point a effect is the smell of this net Point out from last 16 I am Anil that I tower doctor J 108 and after that will keep doing in India and have written effects MP4 notification wearable buy I am Saudi cheese work England test also maximum test cases on photo copy paste thinking swabs operation research Institute Were Looking In This To Scheduled For A 200th Test What Were Getting A Perspective And Samridhi Ko Or Ki Side Not Accepted So What Is The Time Complexity And Space Complexity Of Dissolution And You Can See The Length Of Pollution For This Seems To Be Getting All The element important quarter inch and basis of witch nothing but water and space in which case all deposited elements go into existence on which also find the space and time select from itself but if you want you tube this news is modified if modified in tracks and this Is it from input tray post operation warning to three low floor and 500 to 1000 poster and points disawar population are software veer 1532 219 that if you are in interview follow up operation of interview massage and question like can do it without using space which state but e Still Alive Hello How To Use A Modified And What We Can Do You Celebrate Win Modified Crops Are Just Numbers In The Same Truth Will Be Next Chief Of Intense Pain In The Basically Representing The Element Process Element In Our Life In Post That And Will Addison To the post of i plus and prevented dash land will check is the point at which children in moderation switch off even today pores which is svr increment in gift what we can do will compare effigy element in pop dare element in moderate like zip code to element In Food Are Effective Set I - 151 DPR Acid - - Oil Will Increase The Process Of Acid - - Oil Will Increase The Process Of Acid - - Oil Will Increase The Process Of Operation In Just 10 We Are You All Like This Full Or 250 To 900 Question Evidence For Will Complete This Element With This Point Will Fight Over In This Elements Will Give We Have Seen That Seems To Be Will Remove This And Tiger In Two Years Back To I Will Go Down And They Will Go Right Side 6 And In The Return Of Its Elements Just Need To Change We Need To Remove The Mid Point For Tracking Chief Joe Hair Institute of India-International Update This Joe Hair Institute of India-International Update This Joe Hair Institute of India-International Update This Condition Hair Fall Star Plus is equal to obscene Maintenance and Share Institute of Taking Stock of Bal Check Hair Oil Sugar 10 and Wash the Post of I - One Feels 2.5 100 Years Post of I - One Feels 2.5 100 Years Post of I - One Feels 2.5 100 Years of Independence from Various Degrees of India and 100 others like this and hear yaar cutting expected to know which can submit this the fact that accepts no you conceive not using words into conflict over subha space complexity after dissolution of wave time complexity shampoo open dry ginger cardamom solution hit the like button Acidity My Channel thanks for watching
|
Validate Stack Sequences
|
smallest-range-ii
|
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._
**Example 1:**
**Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\]
**Output:** true
**Explanation:** We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
**Example 2:**
**Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\]
**Output:** false
**Explanation:** 1 cannot be popped before 2.
**Constraints:**
* `1 <= pushed.length <= 1000`
* `0 <= pushed[i] <= 1000`
* All the elements of `pushed` are **unique**.
* `popped.length == pushed.length`
* `popped` is a permutation of `pushed`.
| null |
Array,Math,Greedy,Sorting
|
Medium
| null |
201 |
yo what is up youtube today i'm going to be going over bitwise and of numbers range it's a medium problem on leak code i just started a slack channel where i post daily legal problems that i solve and eventually post videos of i'm not going to be posting easy problems anymore or posting videos to them they're just too easy i'm just going to stick to medium and hard lastly subscribe to my channel if you haven't already and i'll see you soon all right so bitwise and of numbers range given a range m10 where uh the range is zero to this large number return to bitwise and of all numbers in this range inclusive so if we're given five and seven uh it's four um it's kind of hard to realize what's going on unless we draw it out on the whiteboard so um i have the problem right here the five and the seven so i believe yeah m is the lower range so this is m and this is n um so they just want oh sorry yeah so they just want us to end it so and means that all the numbers in that range have to contain one so what that means is we're gonna check to see does this column here contain all ones well no there's a zero so we're going to put zero and does this column here contain all ones one so yes there's a one what about this column uh we have a zero here so zero and this column there's a zero here so zero has to be all ones for the and function um so this number two bits i hope you guys know bits at this point is equal to four because this is the one two four eight so it's just four right there um and i could go over bits that's like a whole other topic um saving this problem later to explain in the function but basically how we're going to solve this is we don't want to do brute force that'll take a while but if we take this number and this number well first i want to say that the and the number that we're going to be returning is always going to be less than m it's not possible for that if you just look at that um in this problem up here we're gonna see well there's a zero in this one so we have zero there's a zero in this column zero there are zeros in every column so in this one it's actually just going to be equal to zero um so the way we're going to do this the easiest way is we just bit shift one at a time and when that number finally equals when the two numbers equal each other so we're going to bit shift n and m at the same time and when they equal each other um that's what that's when that's the number we're going to return so if we bit shift this one the first time we have zero one so this is seven and then we're going to have five so we'll just do an n and m um and when we bit shift five for the first time it's zero one zero these are still not the same so we have to bit shift one more time so we have seven sorry i'm running out of space and then we have so zero so we're just moving the ones to the right one and zero one well now they're the same so we're going to um shift the number to the left the number of times we shifted the ones so how many times did we shift them we shifted them one two times so we only did this is the first one this is the second so we're just gonna shift them to the left two times so i'm gonna do it up here zero and five um so now we're gonna shift this one two places one two so we actually don't even need to do both of them we just need to shift it over two times so we're gonna get one zero which gives us four this is equal to four so that's how we're gonna solve this if we did it in this problem you'd see that they would never equal each other so yeah let's code it so we're going to have to keep track of the shift we're going to increment shift so and then we're going to loop through while um m is less than n or no that's wrong walt does not equal so to do the bit shift to the right it's this symbol so we're gonna just shift it once um and it updates m so that's how we do the shift so we're shifting all the ones one place over basically and now let's increment our shift counter and that's basically it and then we just return um either or no we have to um so now we have to shift it either one to the shift amount so that's what we did in on the whiteboard and then we just return n so hopefully that makes sense um i actually got asked a bit shift question before in an interview i did not know how to do it i just hadn't studied bit shifting at all i never ran into it in school or anything so yeah so um not the greatest i don't know why it's i think memory usage is weird um so it's owen of one and o of one um we didn't have to create anything so that's why i'm confused why the space is so um low but yeah we didn't even have to loop through um we just did we just shifted them over cons i believe they explain it here although there's a loop the number of iterations is bound by the number of bits that an integer has which is fixed so the time complexity of the algorithm is constant so that's why we have ovo on space complexity and pretty simple solution it's really fast the hardest part is just being able to come up with the logic on the spot so that's all i have for you guys thanks for watching if you like this video please hit that like button i'll see you in the next video
|
Bitwise AND of Numbers Range
|
bitwise-and-of-numbers-range
|
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1`
| null |
Bit Manipulation
|
Medium
| null |
188 |
hey what's up guys this is john here again so uh actually today i also want to briefly talk about today's daily challenge problem uh which is number 100 188 best time to buy and sell stock number four you know i think this is a great problem you know this is like basically the last one this is the last one probably not basically this is the one of the uh the buy and sell stock uh problems you know and this one is marked as hard so the reason being is that if you guys have uh solved those kind of best uh time to buy and sell stock one two three you know you i think you guys will most likely be pretty much very familiar with this kind of question okay so here's the problem you know basically you're given like a list of price of a stock okay and the price is like this it could be it could go up and it could go down okay and the constraint is that you are only allowed to uh to buy and sell uh per i mean on a separate day so which means you are not allowed to buy and sell at the same day so it means that if you're buy if you buy the stock on the ice day okay you will buy if you buy on i stay okay you can only sell starting from i plus one okay so right and then if you sell the stock on the iplast one day and then you cannot buy it on this day you have the earliest day you can buy it's a i plus two days and you cannot buy before you sell this stock okay you must sell the stock before you buy it again okay and cool so for this problem you know that you know the because this is like a generalized version of the i think the buying style stock number three or number two i don't quite remember so which you're given like a k number here so it means that you are allowed to complete at most k transactions okay so this is like a general case of that right so i think a simpler version is that you may only complete uh at most one transaction okay or at two transactions or in general cases this is like at k transactions okay and i think the other one is like your i think the other brand sell problem is they're like also even like a buy itself with a cooldown so something like after selling a stock you have to wait for one day and then you can buy it again something like that but it's not relevant for the up to this problem okay so basically you're not you're only allowed to do like k transactions okay and here's a range here so the price range is 10 to the power of 4 but keep in mind no keep in mind this one k is isn't the 10 to the power of 9. so this is super big right so which means that we cannot even loop through this k here we have to be uh careful about this one here okay i think uh if you guys have watched my previously uh buy and sell stock problem you know i typically use like uh like this approach basically i'm going to define like a by dp array so we have a by i and then we have a cell so i okay so this one means the uh you know uh at i stay right the last transaction is by sp is by okay so cell means that at the ice day the last transaction is sell so for all the remember guys so for all the buy and sell stock problem you can always use this approach basically you define like a two dp array so the first one is the at the ice day and the last transaction what i mean was buy was by a stock and here the sell tr the cell eye means that at i stay the last transaction will sell okay so that's basically the uh the basic version of this uh dp definition right but in this case you know since we have like uh a k here a case transaction so what does this one mean it means that we're introducing another dimension of the dp array here okay basically uh other than the i here we'll also have another k here okay so this k means that you know i stay at ice day you know the last transaction is buy but we have done k transactions right we have done case transactions i mean of course i mean let's say this case is like uppercase case so this is a lowercase so k is in the range of the uh zero to the upper case k okay same thing for the cell so i uh ik right similar like the uh at the i stay right the last transaction is excel uh and we have done the case transaction okay so we can just use this uh dp definitions to help us solve this problem you know so let me try to uh code these things here so we have and we'll uh we'll take care of this like this huge k number later on so let me try to finish the uh the main logic here right so usually the template is it's like this right so we have a buy and cell right and okay i'm going to change this one to uh to up to uppercase k okay so we have a k by here right i mean the uh so at the beginning we have zero right the zero and since we're creating a two dimensional two dimension like array here so the inner the second dimension is the k plus one right for in range n right so the reason i'm doing like this k plus one is that later on when we calculate the uh the result we'll be using like a k minus one okay so we do a k plus one so that uh the k minus one will not go out of the boundaries the bound okay so cell same thing for this okay i'll just copy and paste this so now we have that and then so the main loop is like this so we have i in the range of the one to n right so and then like for each eye here right we're gonna loop through the uh everything all the range to k plus one from one to k it means that uh we have like uh one transactions right and then we have like the uh starting from one transaction and end at the case transaction basically we're considering all the possible transactions possible numbers of transactions that we can possibly do at this i stay right and then in the end we simply return this we simply return the max of cell minus one right so why is that i mean it means that at the end in order to get the maximum profit right the last transaction has to be sell right and we're getting that to the uh to the until the last day right until the last day but since we have a at the each day we have a k different options transactions that's why we're considering all the transactions at the last day because we could get the i mean we could get the maximum profit uh with one transaction with two transactions with any number of transactions which we don't know that's why we need to get the maximum out of all the possible transactions for the last day right so that's why here okay so the state transition functions is pretty similar like the all the other buy and sell stock problem the only difference is that we are having a k here right so basically you know in order to buy okay so for each of the buy here right we have two options right so we either buy it or we don't buy it okay basically we either buy the current stock or we don't buy the current stock so the first one is always we don't buy the current stock right so how so if we don't buy the current stock i mean we can get our car get the current trend transaction from i minus one right because that's the i minus one day right and the last transaction is still buy right because we're not buying it here right so be so which means at i stay the last transaction is still the uh the by i minus one because this one so the buy that definition of the bias uh dp array here it means that it uh stands for like at the i state right uh the last transaction it is buy so that's why we can use the i minus one since we didn't buy it so the transaction didn't change right so that's the first we don't buy it so the second one is of course we so basically we buy the current stock okay so if we buy the current stock so what does it mean means that i mean uh it means that uh the previously i minus one day okay has to be sell right because in order to buy the uh the current stock right it means that we have to uh we have to buy this sorry we have to sell the stock first okay right otherwise i mean if we already have a stock okay we cannot buy it here right so in order to buy it here so that will which basically will fall into the first case here so in order to buy it we have to sell it first okay so if we sell it that means that you know the i minus one day the last transaction is cell okay and the uh the transaction will be k minus one right so remember buy and sell buy and then sell okay this is one transaction okay right so this is the trend the transaction k here and when you do another buy then sell this is transaction k plus one so that's why you know if you buy it here right so when you do the cell here it means that the cell belongs to the previously transaction which is k minus one so that's the uh the state transition function for the bi for a by dp array similar for the cell okay silent 7k here and of course the first thing is that the first option is we don't sell okay so if we don't sell it means that we already have a uh so if we uh if we don't sell at the uh at the current state okay and it means that okay sorry here i forgot one thing here so i mean if we buy the current stock we have to decrease the current price from the uh from the total right because we're spending that money okay so the first thing similarize the buy here so the first option is that we don't do anything uh today so which means we but since we're like we're calculating the cell right so it means that the last transaction of at i stay should be cell which means that you know this thing comes from the cell i minus one k okay right so that's the first state basically you know either previously day right we don't we have a like uh the last transaction will sell then only then it's possible that i mean we cannot sell at the current day which uh still ending uh has the other last transaction uh as a cell right so that's the first and how about the second one so second one means that we're selling right so we sell at the at i stay so which means that we have to buy it at the previously day right uh we i mean we don't have to buy it but the last the previous days last transaction has to be buy right otherwise we cannot sell okay but remember here is like a little uh thing you need to be careful here remember that you know the buy and sell they belong to the same transaction so which means if you're selling the case transaction it means that we buy when we do the buy here we are buying for the k transaction so the k they belong to the same transaction okay and uh since we're selling it so which means we can get that price the current price right cool so as you guys can see so that's basically the generalized version of this i mean like i said i know if you're like given like if you only can allow to sell doing two transactions right so you can simply replace this cable with two here right and if you're only allowed to do a one transaction you can replace this k with i mean with one right but and this is like a general generalized version of this uh like how many transactions here okay so next that's the main part right so since we're starting from one here it means that we have to initialize the uh the zero case okay so and since we have like uh like a like two dimensions so it means that you know for each of the k here right so for k in range okay sorry so this would be a uppercase k here so for the k in range the uh in range k plus 1 right so for these things we want to initialize what we want to initialize by right so by zero of k here so if we buy it at the first day the profit is of course the uh the zero right basically we're spending that amount of money you know so this part you know even though at the first day we cannot even make like a k number of transactions but since later on we'll be uh using like as you guys can see we'll be using like this uh by zero right see the byte zero and with the case years and we'll be looping through all the possible case at index by zero that's why i mean we also ins besides this by zero we also need to like initialize all the out values for zero and k for by zero and k okay and in terms of sell we don't need to do the sell because we cannot sell stock at zero at the first date because we haven't buy it yet right we haven't bought it yet so which means we can just leave it at zero okay um cool i mean if you just run this uh the code like this i think you can pass the test case but if you do a submit here you'll get an okay oh sorry so okay another like a base case is like this basically you know here if n is zero right if n is zero we simply return zero okay right so if we do a submit here so as you guys can see here so we have a memory arrow here because the uh see this is the huge k here and if we're trying to allocate this amount of a dp alpha array here it will definitely uh exceeds the maximum memory a lot here because case is too big right like this and also not only the memory but you will need to move to the loop here right it will definitely tle because this is like the end time n times k right the case itself is a 10 to the power of nine so this part will definitely tle so to handle this part so what can we do so the way we are we're handling this uh this special k special case is that you know like i said you know uh you know since we are only to do either buy and sell at one uh at each day so assuming like we have end here right so the most transaction we can average we can ever do is like what is n divided by two right that's the total number that's the maximum number of transactions the transactions we i mean we can do right so if the k basically you know if k is equal or greater than the n divided by two okay so what does this one mean it means that no matter how no matter when we sell or buy the stock basically where there's no limit right we can basically we can sell and buy stock at any time and because we have to be since the k is so big and we don't have to worry about the constraints of case transaction right so basically that's going to be a special case so and if that's the case we can simply do another like a simple check uh handling here which is the uh you know what as long as the current uh stock is higher than the previous day stock then yesterday stock will basically we can simply do us buy and sell right so let's say we have a uh yeah let's say for example this one okay if the k is so b let's say if the k is 100 right so for this one how so now the problem becomes easy so we can simply do what we do uh we just check right we just check if the current value is the current if the current value is greater than the previous value so we in this which means that okay so we start from 2 here 2 is smaller than 3 of course we cannot buy 3 and sell at 2 because that will give us an active value so we have a 6 and 2 6 is greater than two which means we can buy and buy at day number two and then sell at the uh the third day which will give us a four here right so we have profit four and the next day uh five is smaller than six which means we don't buy it right and same thing for zero right but for 3 and 0 we have 3 here so 4 plus 3 is 7. okay how about this how about if we have like a 2 3 5 six seven okay so if the uh if the stock price is always increasing okay we can still use that logic right basically you know we compare three and two then we have a profit one right and if we compare five and three we have profit of two basically you know this thing that it doesn't mean that we are i'm buying at uh the first day and i sell at the second day and then i buy it at the second day again then i sell at the fifth uh at the third day i'm just using this logic to calculate the maximum profit it doesn't mean that i have to buy and sell at the same day here so it means that i buy it at the uh at the first day right and i sell it do i sell it here probably not because i see that okay yeah i can still make profit right and then so here i'm not selling until i'm reaching the end of this array here right so the total profit is going to be a 2 to 5 which would be 7 which will 2 to 7 which would be 5 right yeah one two one yeah which would be five okay so which means that i mean if the price is i sorry i'm starting for i in range one to uh to unplug to n right if the price is i is greater than the other prices of i minus one okay then we do a we have our answer here answer is equal to zero okay then the answer plus the uh price is okay i minus is i minus one okay and then we can simply return the answer here right so that's how we handle this like the case where k is greater than the half of the number two here right so and we just simply return this like we just use this one okay so now if we run submit now as you guys can see it's pretty fast right it's only 124 milliseconds because now the time complexity is it's like so for this part it's just o of n right and for the second part you know since the k is bounded with n so this part is also an n square right cool i think that's yeah i think that's everything for this problem you know it's a basically it's a it's the most uh general case for the buy and sell stock problem where we have like uh case transactions you know so the key point for the problem is that you know we have to uh introduce a second dimension you know whenever we have like a transaction constrained for this buy and sell stock problem it means that we need to consider at each of the day at each day here we have to consider all k transactions which means we're adding like an additional dimension on top of our dp definition here okay and other than that it's just the uh to set this set the base case and then this part right i mean this is like generic uh like for all this buying cell stock problem i think the state transition for buying the cell there are they're all pretty similar okay where the uh you don't buy right you don't buy at the current state so which means you this one has to come from the buy i minus one because you're saying that okay even though i don't buy it means that the last transaction is still buy right and then if you decide to buy it then it has to so the previously the previous day has to be a cell okay then you and then you can buy it of course don't forget to uh to either increase or decrease the price the current price okay cool i think that's okay thank you so much i'll stop here yeah and thank you so much for watching this video guys stay tuned see you guys soon bye
|
Best Time to Buy and Sell Stock IV
|
best-time-to-buy-and-sell-stock-iv
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `k`.
Find the maximum profit you can achieve. You may complete at most `k` transactions: i.e. you may buy at most `k` times and sell at most `k` times.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** k = 2, prices = \[2,4,1\]
**Output:** 2
**Explanation:** Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
**Example 2:**
**Input:** k = 2, prices = \[3,2,6,5,0,3\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
**Constraints:**
* `1 <= k <= 100`
* `1 <= prices.length <= 1000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Hard
|
121,122,123
|
53 |
welcome to leak codes blind curate 75 where I'll be solving the top 75 legal questions this question is called maximum sub-array and it's a classic one you sub-array and it's a classic one you sub-array and it's a classic one you definitely need to know here's the question given an energy rating nums find the contiguous sub array containing at least one number which has the largest sum and return it some say we're given a list like this we want to find the maximum sum of any cell array inside here and it's got to be contiguous here it's going to be 4 negative 1 to 1 which has a maximum sum of 6 and we actually only need to return the maximum sum some possible not the sub array itself ok so this is known as codons algorithm and it's one you definitely need to know leak code considered is it easy I don't think it's that easy but if you memorize it and just have it in your back pocket definitely will come in handy so here's the basic idea we'll just go through the array and start with initializing two numbers one for the maximum sum that we've calculated so far and one for the current sum that we've calculated at this point so here at negative 2 we'll say negative 2 is our current maximum sum and store that as our max some for now because that's you know the maximum sum that's possible so as we move on to the next one now we add the current number to our current sum and that's going to be minus 1 right and minus 1 is greater than minus 2 so we'll store that as our maximum sum now we move on to minus 3 and now our current maximum is going to be minus 4 obviously minus 1 is greater than minus 4 so we'll keep minus 1 as our maximum sum but here at for now our maximum sum is going to be 0 right I'll current sum is going to 0 so that's obviously greater than our maximum sum of calculate so far as minus 1 so now 0 should be our max from sum but here's the thing with cotton codons algorithm one of the things you want to check is would it be better to just get rid of everything before because if we just thought rid of all this and said hey start this sub-array here for said hey start this sub-array here for said hey start this sub-array here for is obviously greater than zero so it would be better to just start here and say this is gonna be our current sum and I'll be considered the maximum sum at this point and whatever we calculate moving forward if this point is greater than the maximum sum we've calculated so far then whatever we calculate as our maximum current sum moving forward it's going to be greater than keeping all this back here and that's the idea like we have this kind of pointer that essentially moves up whenever we find that getting rid of it is going to be greater than keeping it and we don't actually need to keep the pointers we just need to calculate the maximum sums so the first thing you'll need to do is first initialize two variables one for the max sum and one for the current sum and the maxim is going to be the lowest possible integer that we could have in Python and you can do that by this representation that's like a float and the negative in physically the lowest possible number in Python and current some will initialize that to zero because we haven't actually calculated anything yet right so for every number in nums what we want to do is calculate our current sum so current sum will be basically plus whatever num is here but we also have to keep in mind it might be just better to get keep the number that we're on so what we'll do is say max between either occur sum plus the end that we've calculated so this is everything we've calculated so far Plus this current number or just this current number because if that's the case then if this is greater then we can just get rid of whatever it came before and just start over now our max sum is going to be equal to the max of well and you mix them with calculated so far and the current sum finally we can just return the maxim so it looks like that works for a test case let's submit that and they're accepted so yeah I mean it looks very simple but it's one that I think you'll need to look into a little more there's variations of it of saying how could you return the sub-array return the sub-array return the sub-array I've if that's the case you want to keep track of the index numbers and lots of variations to this but this is my preferred method there's other ways to kind of go about it but yeah codons algorithm is definitely like you know a tool that you'll definitely need for these programming algorithms alright so thanks for watching my channel and remember do not trust me I know nothing
|
Maximum Subarray
|
maximum-subarray
|
Given an integer array `nums`, find the subarray with the largest sum, and return _its sum_.
**Example 1:**
**Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\]
**Output:** 6
**Explanation:** The subarray \[4,-1,2,1\] has the largest sum 6.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** The subarray \[1\] has the largest sum 1.
**Example 3:**
**Input:** nums = \[5,4,-1,7,8\]
**Output:** 23
**Explanation:** The subarray \[5,4,-1,7,8\] has the largest sum 23.
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.
| null |
Array,Divide and Conquer,Dynamic Programming
|
Easy
|
121,152,697,1020,1849,1893
|
1,962 |
Hello hi friends welcome back today we are going to solid co problem 1962 reduced to minimize the total so let's go through the description yagya 101 text interior files fear files for a representative number and stone singer of oil and interior you should apply the calling operation In Delhi Times Juice Benefits Of It And Remove Lower Of Piles Of Is Divided By Two Stones Prominent Rate Sorry For Example Of Piles Of Aaye Ki Value Isse 027 Divided By Two Wickets 3.5 Se Zor 027 Divided By Two Wickets 3.5 Se Zor 027 Divided By Two Wickets 3.5 Se Zor Is 123 Basically Chat Start Floor Miss Noticed That You Can Applying two operations on the same file more than once Returns the minimum possible total number of stones remaining after applying the K operations. Crown X Front 100 All is well after Fluid Develop Broad Hag So let's check the second example over a year and we can discuss how we can solve this problem Solve power hitting fast and gold is to minimize the total print and they also want to do the floor Operations on which can choose any file from this a great and you can be divided by to write and selected value so common so let's take this example of first so you can see also share a pot with you is you will first use this Likely it's right Down list person * Solve this problem using priority queue * Solve this problem using priority queue * Solve this problem using priority queue and maxid so let's Radhe Shyam 436 702 Research values and its disavar priority accurate Research values and its disavar priority accurate Research values and its disavar priority accurate se zor priority q a ah good quality khurai priority why to this is max kidman tension a r priority q so what will You Give Worst Error Sharing and They Will Keep All Dwellers in 250 Tubelight Will Foster Heroine Offers This Will Have to be the Giver of All Boons To Adding to the Cube Solve Priority Cue Your Intuition Max Clement Actions and Always Maximum When You'll Be on the Topic World will be inside front sun cancer seven days 6 3 4 and a threat in foreign death is 3 Will Come Out For It One Hour Late I'm Just Writing Here Dry Is Equal To One Quick 120 In The Beginning Job Equal To One Will The For Twelve Treat Should Sit On Top Priority Queue And Will Apply To Operation Right Holidays Like This Operation Were Going To Apply For Your Profile White Divided By Tonight Show Seven Divided By Two Is Equal To 3.50 War Divided By Two Is Equal To 3.50 War Divided By Two Is Equal To 3.50 War Floor Is Equal To Three Light Of Debt So Will Have To Reduce The Value Of Discipline Wife 138 Elections This Value Will Be Gone From The P Rahe Thank You And Will Have To You Quote 7 - 350 How To Add New Value * Will Have To You Quote 7 - 350 How To Add New Value * Will Have To You Quote 7 - 350 How To Add New Value * Umpire Radiculos Forward Convenience And This Value For Clear Late Than Right Because It's A Priority Cue Suno Will Have 64 382 Hours Again will take second term and will do the operation against him will welcome to you will again complete war Next largest Kallu is six and will develop by two right subscribe to is equal to one should reduce that file path rules Sikh - file path rules Sikh - file path rules Sikh - 6 - 3 is Equal to 321 Gone Now and Women 6 - 3 is Equal to 321 Gone Now and Women 6 - 3 is Equal to 321 Gone Now and Women in the Lost War Edit Back to the Q Right Election Three Will Be Added Soon Because What is the Lowest Worldwide Should Not Give Equal to Right Now Will Do Against the Nation 's Weakness Loot Highest Value from the 's Weakness Loot Highest Value from the 's Weakness Loot Highest Value from the Means of And Will Come True For Divided By Too Quiet Too Right Is Equal To Show Will Have Liked This Point Will Be Difficult For - Point Will Be Difficult For - Point Will Be Difficult For - 2012 Have Soot To You Will Have To Head Into R Priority Q Again Raised Some None As You Can See You Are Finished With Ours Apart from corporations which were three light show what will oo approve finished operations will take out all the element from the priority queue and will sum the upright su time now all these elements in how much will be four plus three plus two life and plus Women Plus 303 Plus Two This Flight Software Is Our Answer Basically Tight 34 How You're Going To Minimize Total So Normal Foreign Cigarettes But Man Is Going To Take The File Which Is The Highest Stones Value Side 34 How Day You Will Be Beneficial For That Because It will give the maximum all likelihood that will help to make it a total tight development can reduce that maximum point to fight conducting so let's move will reach the highest value and today is world best data structures in Java is priority because maximum implementation is possible Provider Computer And Expression When You Will Create Private Unit Certificate Always The Maximum Element Will Be On The Top Of The Priority Cue Light Show This Is The Way We Are Going To Solve This Problem Is Most Example Justin's Size And Tile Tata Wanted 2 Explain So In This case you know you can see the twenty-20 the maximum value lights of the twenty-20 the maximum value lights of the twenty-20 the maximum value lights of cost value will be reduced by step like it is equal to right in this case was 12213 difficulty in front and in the next time like to have two terms ultrasonics I will Not Like You Will Take It In Which You Will Read This Good Night So If You Calculate All This Number Other Values Like This Thirty Plus 1040 Plus0 Answer For This 159 To Be Our Loop Minimize Total Value Right After Operations Show Will Take This Also Enable Testis For testing so let's look at the implementation deviate so common first created in tears from very well that ends in hudson 2010 days came cricketer priority this of interior right because they want to cold in tears and I have created and expression hair vikas want to maximum different Saunf Bal Se Bhi - A show maximum value in the Bal Se Bhi - A show maximum value in the Bal Se Bhi - A show maximum value in the top in that case after that you will read through all the files and will offer like add put two points value in to the prime qualified and after that is created dirty variable is equal to 07 2012 Method Number of Side Effects of Two Whole Document Value of How Many Times Were to Have Done at Operation of Creativity Variable Day to You Will Lose Invite Look So Will Always Be Positive Value from the Priority Q Mains Wear Rested Removing Highest Element Always right straight rule use that operation this operation is the population register me thrust of side divided by two solve this operation courier implemented share using dip c divided by two right dip c divided by two right dip c divided by two right and you will get all consonants subtracted from share it and you will again put The remaining value * till each act put The remaining value * till each act put The remaining value * till each act for example a year when we common don't like share and divided by two floor person will reduce the 12.7 - 3 and pushed back 12.7 - 3 and pushed back 12.7 - 3 and pushed back into the queue rights hotspot they are doing basically a download lower house android kind of example In This World Top Three Times In This World Software Without Operation With Priority Wilson Elements Of The Elements Remaining Elements In The British Rule And They Have Implemented This Problem Solve This Is The Largest This Disgusting Incoming In 2000 Was So Will Get The Correct Answer is phase good answer hair soft will take place of mother taste sales is clear is a solid take this test case after all equal to three hindi status the software suvidha answer clear software getting 12th thing correct answer is clear which arm the soul will just record 12520 Too 200 World Twenty Years on the Software Testing Correct Answer Remained So I Can Place and Submit Our Solution Here is 200 G Solution God Accepted Sweet Past or Dowry Cases and Its Effects of Almost 70% Poster Dena Rate Submissions and 70% Poster Dena Rate Submissions and 70% Poster Dena Rate Submissions and Almost 800 Persons Better in Memory After which pretty good 200 grams this how they can solve this problem of removing stones minimize total using back ready approach and user priority queue volume maximum implementation right to holder maximum values always in the top of form holder maximum values always in the top of form holder maximum values always in the top of form so you are here so if you have A Positive Looked Into My Play List of List Codes and Solutions for My Channel Please Cricket Nov 18th July Month and Solve Problems Which Were Previously Cured by Companies Like Amazon Apple Microsoft Google Facebook and Not Many Other Companies Should They Eat Coding Questions Were Previously A Kinnar Interview Santosh And Explain With Examples And Details And Java Code To Prostitute Also Rate Hand Free Problem Sugar Different Varieties Of Problems Batting Fruits Dynamic Programming Liquid Related Problems Spring Related Interview Questions And Hatred For Search Difficult Life Is Aa Be In Your Life Partner Research Trees And Craft Related Problems To Prostitute Definitely Help You In Your Job Interview Preparation All Subjects In Another Place Called A Job Interview If You Are Prince And Java Telephonic Interview And Your Initial Screening Lot Of Problems That Were Previously Art And Frequently Asked Questions So You Please Go Through the day if you like this video and if you find this video helpful please subscribe to my channel and like this video thanks for watching video
|
Remove Stones to Minimize the Total
|
single-threaded-cpu
|
You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the operation on the **same** pile more than once.
Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_.
`floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down).
**Example 1:**
**Input:** piles = \[5,4,9\], k = 2
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[5,4,5\].
- Apply the operation on pile 0. The resulting piles are \[3,4,5\].
The total number of stones in \[3,4,5\] is 12.
**Example 2:**
**Input:** piles = \[4,3,6,7\], k = 3
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[4,3,3,7\].
- Apply the operation on pile 3. The resulting piles are \[4,3,3,4\].
- Apply the operation on pile 0. The resulting piles are \[2,3,3,4\].
The total number of stones in \[2,3,3,4\] is 12.
**Constraints:**
* `1 <= piles.length <= 105`
* `1 <= piles[i] <= 104`
* `1 <= k <= 105`
|
To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks
|
Array,Sorting,Heap (Priority Queue)
|
Medium
|
2176
|
1,756 |
Hello friends welcome back to my Channel today we're going to do a Leal problem together I've been doing some Leal problems recently just uh for the fin it um lead code 1756 design most recently used Q This is taged as the medium problem so the idea is that we want to design a queue like data structure that moves the most recently used element to the end of the queue notice that we do not remove it or anything we just move it over to the end of the Q but the Q size Remains the Same so the examples here is that given a init argument we initialize the Q to be a range a list of this range so if we give an eight then the Q is initialized with internal Q of 1 2 3 4 all the way to eight and if we call a Fetch with three this should move the third element which in this case since it's set it's one index uh in here so it'll be one and two and three so it'll move element three to the end of the que and this Que Now becomes like this so everything else Remains the Same but the three gets moved to the end and similarly now if we want to fetch five we want to move this six all the way to the end fetch two is moving this two all the way to the end and fetch eight is moving the eighth item in this case it's just the two itself so it's already at the end so we just return it directly so the most referal way is that we just you know internally keep like a list initialize this Q with a range of one to n we want to fetch the Kei item so not it is one indexed here already so we want to decrement it by one zero indexed and the items that we want to fetch uh will be we can just pop it out of the Cube now we have this item that's at the Keith um that is the Keith element in this Cube and uh we want to add it back physically to this q and return in like this in one two okay and if we submit notice that this is a medium problem and this is I think a little bit too easy for a medium problem actually let's go over the complexity first so the time complexity for this will be all of N and space Also all of n hint one is basically what we have implemented here um however a better way to use is the square root decomposition technique so to move it over here so this Square decomposition technique so idea is that you can build chunks of size square root of n for each fetch operation you can search for the chunk which has the I element and update it so this will be all of square root of an per operation isn't that nice and move this element to an empty chunk at the end so it sounds a little bit complicated but the idea is simple basically the idea is that currently let's say we have an array like this currently for every single movement let's say batch three then basically we have to move the entire list over with a copy of it and move every single item one step forward and move the number three the third index item all the way to the end so the operation is all of and basically we are moving every single element in that list so this has a big overhead and then one way to optimize is that instead of moving the entire list every single time we can try something like this like we separate things into smaller chunks and the idea is that for every single operation instead of moving the entire list we only move a small chunk of that list and the rest of this can potentially remain the same so the overhead is a lot less it's going to be the square root of n basically the size of this chunk um where we set to be chunk size Square Ro of inin so each chunk has size square root of n same fetch three first of all first we have to find where the third element is which is uh it has to be because we have to make it and now it becomes two so the idea is that we want to this give us which chunk it is and this give us which element within that Chunk we want to look at so in this case uh fetch three zero pop with key element which will become like this and then we need to insert it to the end so the only two trunks that we need to move we need to change is the first one and then also the last one in this case the complex c will be kind of constant times square root of n which is also just square root of N and notice that the middle chunk doesn't need to change at all it stays the same the only chunks that get to changed would be the chunk which uh contains the element that needs to be moved and also the last chunk uh if it has more room if it doesn't we'll have to create a new chunk so those are the only two operations needed so in the Above This square root decomposition technique the time complex like we mentioned here would be square root of n but space since we are still keeping all of the elements here so space will still be all of them so this second solution will be more optimal in terms of uh time complexity so basically it's less overhead for the queue operation and slightly faster time complexity but I doubt we will need to have to you know code it out during an actual interview because the code itself can be quite lengthy and it's just very long to code it up you have to think about the corner cases like check the end if there's an empty chunk if there's room on in the existing chunk if not we have to create a new chunk to add the new element and this and that it'll be a great exercise um but I would say if there's enough time in the interview I would go ahead and try the second approach but I would first definitely um code up this first uh solution just to solve the problem and then and bring up the second um square root decomposition technique to indicate um how we can optimize for the overhead here so that's it for this episode I'll see you next time
|
Design Most Recently Used Queue
|
minimum-deletions-to-make-string-balanced
|
Design a queue-like data structure that moves the most recently used element to the end of the queue.
Implement the `MRUQueue` class:
* `MRUQueue(int n)` constructs the `MRUQueue` with `n` elements: `[1,2,3,...,n]`.
* `int fetch(int k)` moves the `kth` element **(1-indexed)** to the end of the queue and returns it.
**Example 1:**
**Input:**
\[ "MRUQueue ", "fetch ", "fetch ", "fetch ", "fetch "\]
\[\[8\], \[3\], \[5\], \[2\], \[8\]\]
**Output:**
\[null, 3, 6, 2, 2\]
**Explanation:**
MRUQueue mRUQueue = new MRUQueue(8); // Initializes the queue to \[1,2,3,4,5,6,7,8\].
mRUQueue.fetch(3); // Moves the 3rd element (3) to the end of the queue to become \[1,2,4,5,6,7,8,3\] and returns it.
mRUQueue.fetch(5); // Moves the 5th element (6) to the end of the queue to become \[1,2,4,5,7,8,3,6\] and returns it.
mRUQueue.fetch(2); // Moves the 2nd element (2) to the end of the queue to become \[1,4,5,7,8,3,6,2\] and returns it.
mRUQueue.fetch(8); // The 8th element (2) is already at the end of the queue so just return it.
**Constraints:**
* `1 <= n <= 2000`
* `1 <= k <= n`
* At most `2000` calls will be made to `fetch`.
**Follow up:** Finding an `O(n)` algorithm per `fetch` is a bit easy. Can you find an algorithm with a better complexity for each `fetch` call?
|
You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing
|
String,Dynamic Programming,Stack
|
Medium
|
2243
|
503 |
my channel so in this video there to go the first goal of course is to solve this problem and do some live coding here and the second goal is to see how you should behave in a recording interview so before we start the real content for today i would really appreciate that if you can help subscribe this channel because it can help me to grow so thanks a lot so let's get started um first of all in the real code interview you need to understand the question remember don't jump into the coding part too quickly try to have a nice discussion understanding the question and um if there's anything unclear please clarify the question with the interior and also at the same time think about some ash cases let's restart this problem it's called next greater element two so given a circular array the next element of the last element is the first element of the array so print next greater number for every element the next greater number of a number x is a first greater number to is traversal other next in the array which means you could search circular to find this next greater number if it doesn't exist output minus one for this number so this is very similar to another question which is called nescritor element one so in that question we use a stack to solve this problem and here it is also okay to use a stack to solve this problem so the next part we are going to find how to solve this problem uh so in a very cool interview you need to discuss with the interviewer how you are going to solve this problem please get an agreement on the solution before start coding so for this one uh we are going to use that to solve this problem um we are actually going through the input array twice like from the beginning to the end then from the beginning to the end because this one is uh asking us to find the next greater number which could be circular so if we if you like have a copy of the array and append to the end something like that then for sure we are going to be able to find the next greater number for the last number so um having said that the runtime is going to be oliven and is the length of the array let me introduce how we are going to use stack to solve this problem so we are going to have a stack so every time uh let's see this example let's say one two one so if the stack is empty or if the stack uh if the top element of the stack is uh a is larger than the card number then we are going to push the number into the stack so first for the first one you're going to push one into the stack and then um when we encounter another number which is greater than the top element within this array then we are going to uh we are going to dump that we are going to pop that out and then add this into the final uh into the final or into the final uh so into the final result so in the stack actually instead of pushing the number real number into the stack we need to push the index into the stack so that we can update the final result array so let's say we have the result array at the very beginning we push one into it and one actually this is zero because it is index and we see that the next number has index one which is two so two is larger than one so we are going to update that this one has two and then we are going to push one into it and then we see a one here so one is uh a smaller thing so we are going to have the stacking uh to be pushed into here and then we have another uh we have the we then we go through this again from the beginning to the end so we see that one is still uh still it is equal so it's not like we can we don't need to do that uh we cannot really push we cannot really update the result array so instead what we are going to do is we are going to push this into the array and then we see that okay the next number which is 2 is larger than the one though so we are going to pop that out and update the result array this one is 2 and then we see that this two is larger than uh the sec the third number which is in the stack so we are going to have this update um as two as well so um and uh after that it is we are going to push another one into here and then another two into here and finally we see that only the this one is not updated so if this if the place is not updated then you're going to have this x minus one so let's see if this is uh something so it says that uh the greater number if it doesn't exit off output as minus one for hit for this so i don't see the range of the input array so i think at the same time we need to keep a record of the places we have updated using a set so the set is uh so the set is contains all the integers so the integer each integer is the index of the array so this one uh it keeps record of the index that has been updated in results so um i would say that's pretty much it and at the end if because this position it is not in the set so we are going to set it as -1 so the reason we keep this set is -1 so the reason we keep this set is -1 so the reason we keep this set is because we don't know whether the input array is all uh is our positive number if it's a positive number then of course we can initialize everything as minus one uh but actually what we could do we could make it simpler so we don't need to use a stack here instead we could do we can initialize everything within the result array into s minus one and then we just update it uh regularly so if it if the position is not updated then it is minus one so we don't need to keep the set okay so that one could make things simpler so the runtime is the olefn and space wise it could be all of them as well so having said that let's do some coding work so for coding uh please care about the correctness of the code readability of the code and also don't be too slow so first of all of course uh so it doesn't have any constraints so the apps case watch case i could think of is as a is a empty thing so if it is empty well should we return so if it is empty let's say we just return a num pointer then let's say you just return a non-pointer otherwise uh it is our general algorithm so we are going to have nums and we initialize everything as -1 and then we have a stack here so remember in the stack it is the index of the number within the array instead of the value so you're going to go through the array twice so as zero i smaller than nums uh dollars times two minus one so this is actually if it is times two okay so it is numbers times two okay plus i so this means we are going to go through the array twice so uh into idx is equal to i modular num dot less um if the stack dot empty is empty if the stack is empty or the stack dot if the top element of the stack is larger than uh the current number so this is nums idx then you're going to push then we are going to do the push into the stacks dot push uh it is actually numbs because it's index so it is we should have this nums uh here so you're going to push the index here and then we're just going to continue otherwise we're going to say well stack dots well the stack is not empty and the nums stack dot peak is smaller than um index then we are going to keep popping things so into is equal to stack dot p pop so this is actually the index of it so you're going to update um you're going to have update next uh return as equal to nums idx okay and finally we are going to have stack.push stack.push stack.push idx finally we're going to return the results so this is pretty much the implementation so remember after you're done with coding uh please do some testing as well so let's rely on this uh platform to help us to do the debugging work and also let's do a submission okay it's the wrong answer okay so when it is zero then you're going to return none okay uh so it's not none but instead we return empty array so here i think this one should help us fix the case here all right so let's do another submission oh all right so everything works well now so this is pretty simple question uh and that's it for the coding work if you have any questions regarding the solution or regarding the coding whatever feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
|
Next Greater Element II
|
next-greater-element-ii
|
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number.
**Example 1:**
**Input:** nums = \[1,2,1\]
**Output:** \[2,-1,2\]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number.
The second 1's next greater number needs to search circularly, which is also 2.
**Example 2:**
**Input:** nums = \[1,2,3,4,3\]
**Output:** \[2,3,4,-1,4\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
| null |
Array,Stack,Monotonic Stack
|
Medium
|
496,556
|
345 |
ladies and gentlemen welcome to today's lead code daily number 345 reverse wealth of a string we know that when we are reversing a list we find the left Mouse one and the right motor one and we switch their values secondly we'll find the one next to the leftmost and the second rightmost and we switch their values and the third right most and the third left most and we switch their values until we funded the middle ones we stop our reversing we can see clearly when we are reversing actually we are using two pointers the two pointers are moving towards each other and they are switching values when they are moving towards each other in this problem we are only supposed to reverse both so we can use similar method the only difference is that we will just ignore the non-war characters will just ignore the non-war characters will just ignore the non-war characters now let's demonstrate at the very beginning the left pointer is already at a wall but our left pointer is not so we'll move our left pointer until its miserable now both of them are at our wall will switch their values because both of them are easy so nothing happens now let's continue moving the move forward until the meter wall now we can see the meter 2 volts will switch the O under the e like that now we'll continue move left and the right pointer onto the pointer and meet each other this is a python code you can take a look
|
Reverse Vowels of a String
|
reverse-vowels-of-a-string
|
Given a string `s`, reverse only all the vowels in the string and return it.
The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once.
**Example 1:**
**Input:** s = "hello"
**Output:** "holle"
**Example 2:**
**Input:** s = "leetcode"
**Output:** "leotcede"
**Constraints:**
* `1 <= s.length <= 3 * 105`
* `s` consist of **printable ASCII** characters.
| null |
Two Pointers,String
|
Easy
|
344,1089
|
376 |
so hello everyone today i am going to discuss the daily lead code practice challenge which is the wiggle subsequence it is the 376th problem in the lead code so a wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative and the first difference if one exists may be either a positive or a negative so a sequence with one element and a sequence with two non equal elements are trivially vegal sequences so for example the given array that is one seven four nine two five is a wiggle sequence because the difference is 6 minus 3 5 minus 7 and 3 alternate between positive and negative so in contrast the next array which is given in the example that is one four seven two five and one seven four five are not bigger sequences because the first one is not because its first two differences are positive that is difference between 4 and 1 is plus of 3 and 7 and 4 is plus of 3 whereas the second one is not because the last two differences that is difference between five and four comes out to be plus of one and difference between five and five is zero so according to the question we are actually given an integers error num and we are required to return the length of the longest wiggle subsequence of norms so let's just so let's discuss this with the help of an example so here is our example so we are given an array that is 1 7 5 10 13 15 10 5 6 and 8 16 and 8 so typically according to what we are given in the question we are ought to find a pattern in the difference is some something like this and a sharp increase and a sharp decrease pattern something like a mountain that something like a scenery which we used to draw when we were in a kgs when we were in a kg so now let's just discuss about the sequence which we are given over here so talking about the difference between the first two elements it comes out to be positive of 16 as the first number is less than the second one so the second difference comes out to be minus of 12 because 5 minus 17 comes out to be minus of 12 so at first the c the difference pattern basically increased and at the second instance it increased it decreased sharply so talking about the difference between five and ten and five it comes out to be plus of five so that if so according to the push according to the pattern that we are actually desire according to the desirable pattern which we are required to find so the difference pattern increase sharply whereas for the next one that is between 13 and 10 it comes out to be plus of 3 so it is at this point the difference is increasing which is actually not required according to our question so at first this so this element is also part of a vegan sequence this element is also part of a wiggle sequence this one is again the part and this one is also the part but this 13 is not part of a wiggle sequence because it has violated the rule of wiggle sequence that is at this point the difference didn't decrease that is the difference didn't decrease as in trend with our previous as in trend with the previous difference so talking about the next elements that is 15 and 13 so again the difference is an increasing difference so which is not in trend with the previous one that is at this point the difference must be must decrease so this point will also not contribute to the length of our bigger sequence so talking about the next difference that is between 10 and 15 it comes out to be minus of 5 so the difference here decrease so at this point we can say so if we want we can basically ignore both of these points and directly jump to this point 10 which will actually contribute to the wiggle sequence wiggle subsequence that is the trend which is given in the question so talking about the next difference that is between 5 and 10 which comes out to be oh i'm sorry which comes out to be minus of 5 so again this spill this is again a strictly decreasing sequence over here so this point so this thing so this element will also not contribute to a wiggle sequence so hence we can basically discard this element so talking about the next difference that is between 16 and 5 which comes out to be plus of 11 so it will contribute to the wiggle sequence as the different as the difference over here is strictly increasing as in trend without with the question so by this we can actually discard this point from our from a calculation because we can discard both of these as well because it is not in trend with the question that we are actually required to solve so till now we have found five elements which are following the wiggle sequence trend so talking about the last one i'm sorry it's not five it's the these are six this is also contributing to the wiggle sequence sorry it's actually five only like the five differences we have found over here which are contributing to this trend so talking about the last difference that is between 16 and 8 which comes out to be negative of 8 so here the difference will difference trend will startly decrease as of our as of the trend which is given in the question so from here we can find out that so this uh so this ti so this difference will also contribute to the wiggle sequence so till now our so basically our six differences are contributing to the trend which is given in the question so typically we can solve this question with the help of two variable method like for example first one talking about this one let me just move this text box over here let's just discuss over here so basically we can take two variables that is up when the difference will go when the difference will actually be increasing will be in will contribute when the difference between elements comes out to be a positive and next one we can take as down this down variable we will in we will increment when our difference comes out to be negative between the elements so talking about the first element as if we are given in the question a sequence with one element will uh will be trivially a vehicle sequence so as we can say the first element in our question can basically contribute either to a positive difference or to a negative difference so we will initialize both of our variables to okay since when our difference will increase suppose the difference up so the difference at this point which you have contributed will in is an increasing c is any is a increasing difference so by default at this point we will assume according to the given trend in the question that the difference before that is somewhat decreasing so the l so the further so in the iterative approach our upper are up variable will actually increase by the formula up is equal to down plus 1 and vice versa is true for down that whenever our difference is decreasing at any point so we are assuming that are different that the pattern of differences before it is already increased so our down saw down variable will increase by upwards and also there is a possibility for elements of the array to be equal so in that case our up and down both will not increase at all that is at that point up will the value of up and down will remain as it is so now taking our so not dry running this approach again so the difference between both of these elements that is 1 and 17 comes out to be plus of 16 so our up will increase by down plus one that is it will come out to be two and our down will remain the same that is one and for the second difference that is between five and seventeen are difference comes out to be minus of 12 so it is a decreasing sequence so our down will increase by up plus 1 that is 2 plus 1 which is equal to 3 and our up will remain as it is so talking about the difference between 5 and 10 which is plus of 5 so it will so it is again an increasing sequence after decreasing sequence decreasing path decreasing trend so our up will increase by down plus one that is it will come out to be four and this will remain three so difference between 10 and 13 as it is comes out to be plus of 3 so in this case our sequence is strictly increasing so our up will remain as it is that is down plus 1 that is 3 plus 1 4 and our down will remain as it is and so that if so talking about 13 and 15 the difference between both of these elements comes out to be plus of 2. so the sequence of diff so the trend of difference between both of these elements comes out to be strictly increasing so our up will remain as it is that is four down plus one four and a down will you know are up will come out to be down plus one that is four and a down will remain as it is so talking about the difference between 15 and 10 so here the difference comes out to be minus of phi so in this difference we will observe a decreasing trend so when we observe a decreasing trend so our down will increase by up plus one so the current value of up is four and up that is four plus one our town comes out to be five and our up remains as it is that is 4. so talking about the difference between 10 and 5 it again comes out it comes out to be minus of 5 so here also we will observe a downward a decreasing trend so our down will remain as down will come out to be a plus one that is four plus one five and since no upward trend is observed in the array so our up will remain as it is so talking about the difference between 5 and 16 so it will come out to be plus of 12 so at this point we have observed and observed increasing trend in our array so when we observe an increasing trend as if as of we know so our up variable will increase by down plus 1 that is 5 plus 1 which is equal to 6 and the down will remain as it is that is five so talking about the la difference between the last two successive elements that is 16 and eight it comes out to be minus of eight so and in this difference we can observe a downward trend which is according to the trend which we want in the question so our down variable will increase by a plus one that is seven because the current value of up is 6 and up will remain as it is so the final answer will be the maximum of both of these elements so finally our answer is 7 and hence this is the right answer so now let's code it quickly after having this discussion so first of all we will store the size of the nums array in some variable n and as of the as of given in the second statement that sequence with one element and the sequence with two non equal elements are truly legal sequences so if the value of n is less than two basically it will return the same as it is so now we are taking two variables that is up and down both of them initialize to one and so on for integers of we will start with the next element because we know that the first element can be part of any of the sequences that is either an increasing or a decreasing so it so that element will actually contribute to each and every sequence so that is the current element is greater than the previous one so we will increase the up value plus one else it tells if numbers of i that is the current element is less than the previous one so our ground variable will increase by a plus one why we have used an else if over here because there is quite a possibility that we will face that both of both the previous and the current elements are equal so in that case we are not required to increment either up or down so that's why i've used an elsif over here and finally our answer will be maximum of comma so let's just run this code see a gorgeous ring you know you try to select the code so hence it ran really faster it's faster than 100 of the online submissions for the bigger subsequence and consumes very less memory so i hope all of you like this video and if you are new to my channel please subscribe the channel and for any of the feedbacks regarding the video please do com please do write them in the comment section i will be happy to i'll be happy for the improvement thank you so much
|
Wiggle Subsequence
|
wiggle-subsequence
|
A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
* For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative.
* In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`.
**Example 1:**
**Input:** nums = \[1,7,4,9,2,5\]
**Output:** 6
**Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
**Example 2:**
**Input:** nums = \[1,17,5,10,13,15,10,5,16,8\]
**Output:** 7
**Explanation:** There are several subsequences that achieve this length.
One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8).
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6,7,8,9\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
**Follow up:** Could you solve this in `O(n)` time?
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
2271
|
729 |
Loot ke guys welcome and welcome back to my channel and this video we are going to solve mycalendar one such problems 2021 kya hai here we have given you a mic calendar class which has a function book function what do we have to do implement the nice book function Now what is this book function doing? Now this is doing the work of one booking. One booking is doing the raisin on this. So what is given to you here. Bro, a start and in is given in the function. Understand in a way. An interval has been given by you that after keeping the laptop, now we have to check whether this slot is already booked or not. If it is already booked, we cannot conduct the dominant one to the west, then what will we do, we will do the return forms. In the condition and if we can enjoy this event then we will go through it. Okay, so now how will we check whether we can do it or not. Look, we have given you an interval, so you will check whether that interval is already used somewhere. No, is it our skin problem that is going to be booked, are we going to do it between any interval, okay, so maybe you are going to control it between any duration which is already there, where there is already a little event. If you are in that condition, you have to get double booking, then what will happen in this condition, will it be return false? Okay, so let us understand it well through the example, what is our problem, then we will see our implementation, how can we improve it, okay? So see what we have to say here, first example is taken, now what do we do through this hmm and understand the problem, okay then see what we have given you here, a MyCalendar memorandum is a collector, is there anyone from the sector tomorrow? There is no time, so there is a tap here, then next we will send, we are going to call the book function which will do the booking, okay, so look at the first in traveler, what is given is start and in, okay, Dr., so this is start, that is yours. It is okay, Dr., so this is start, that is yours. It is okay, Dr., so this is start, that is yours. It is included, it will be yours in the interval, but what is not yours in the interval will be 26q. Okay, so we are going to do this momentum here, let's withdraw here and here, we will cut from here. Now this one's Here, here we have taken, next is us, so let's go somewhere here and outside, but it is being used here, so you can do it because this-this is this-this is this-this is what we will do, not here. If we can, we ca n't do this alarm hunger, so what will we do here in this world, okay now this 2030 of ours is a school of the app, so we can take it by including ego, we can stop that tight, so what will happen to us, this slot hunger If possible then we will cool down here, we will start ok now how can we solve the problem of forehead so what have you given here it is 110 now this is 20 ok people accept it that you already have Salman let's accept it as even Let's take it, okay, now the star is ours, given it, next we have been booked for this, we will start the run, okay, now we will see next, okay, now the next solution will be from here, it is quoted from here, we do it from here is yours, then 5 I stop and what is yours 215 that if you say this then look for 15 minutes, now see that it has started, Hello friends, yours has started, it is ok, now what will we do here, first of all we will check that the start has been kept in a condition. Here, what is your start now, what is yours, what is everyone's first, including your ribbon, what is it smaller than that, what is it that you are gathering, where you are going to do, is it smaller than youth, what is it? That this is not enough, this is enough to give the previous approval that whoever is doing our work should not do any overlapping, the first cement which is ours has to be used, this is what Shankar is using, this is not enough because he can Not that this is the start, I too, these results should be here somewhere, if there is a plate here, then is this enough to improve the scale? This is not enough for you, because even in this condition, what is there on you? Starting is smaller than puberty. Okay, now the Indian which you are going to book, now let's check it, is it adv1, is it smaller than this, then somewhere it will not come in its interval, due to this, there will be a smaller one which will be booked. We are going to make this one smaller, so somewhere you will come here now, okay, but this is if your after this will be here, somewhere after this, it will be somewhere here, there is also a star here after MS Word. Also, if it happens anywhere after China, then what can we do in that condition that it will overlap somewhere, so let us put one more condition here that and ours which is MS Word which we already have to prevent. Are we going to make a comeback, is it not smaller than that or is it not smaller than that? If both of these conditions are there, if we are feeling full then what will we do in that condition, what will we do here in this condition, we will not hunger for this, okay This front will fall. Now let's come to how we are going to solve our problem. What we will do here is that we will use the tractor and the tree. Okay, we will keep going inside that. Okay, we will take off a tractor. Here, what will we do in this? What will we do first on Test and Twenty20? So simple as this, it will be cancer. We will do it in the form of B.Ed. Okay, I have done 10, We will do it in the form of B.Ed. Okay, I have done 10, We will do it in the form of B.Ed. Okay, I have done 10, now I have passed for this, the answer will be I am Ujjain 2, it will be okay. Done through, what will we do after that when we click on 1525, we will check here whether there is any such event anywhere in this vector of the year, whatever is our wish i.e. Joe Murphy will be this i.e. Joe Murphy will be this i.e. Joe Murphy will be this and what is ours will be this pea. 25th, is this condition anywhere that song1 which will be in this vector, which element is filling this condition that if we fold the current of this condition after filling it, then see what is this one even from 1561, your intense 120 here. But right now one element here is smaller than twenty and this one is smaller than 1025, okay so this condition, what will we do, we will fold it here, we have done OK, now where will we put this inside also, two less. We will joint because here this has not happened yet, we will not do this, sorry here again we will see for 2030 ok then we will keep it for 2030 now 2030 is clear again now check one condition so there is an element in the factor of air right now because The next one was not hungry, okay, so we will compare with this one, yours is like this and this is this, okay, now we will see this one, which one is ours, so one, is it smaller than puberty, is it smaller or not, its collar is only a condition. No, it has already been applied on them, so what will we do here, we will do through and it is fulfilling the condition, so what will we do, we used to fold, so what will happen here, it will go to root, okay, let's see the code like this. Quite easy, okay, then we and this will be our solution, it will be OLX white, it has happened that this will be square, now we will also see the optimization, let's look at the first one, so look ahead, what have we given you here, star in this function, what do we need? What we have to do is to do the element, here we did this, first took a vector of pair, declared it, OK, now what we did here is to use equal in which what we are going to do is, we will check all the elements which are in the sector, okay, we will check then. Check this kya jo start hai aapka jo this start that this list is in the form of a second initial i.e. a cigarette i.e. these initial i.e. a cigarette i.e. these initial i.e. a cigarette i.e. these points which is there and next for you stunning debut in has given you this and will be expressed in East zone tractor His starting is fine, so if this condition is feeling fulfilled, what will his enemy do? Okay, about this, if the condition is fulfilled anywhere in this person's wife, then this slot will not be your appetite. So, what will we do in the condition, we will fold the return, we will joint the other wise, we will do withdrawal pushback, start in different from, we will do it, we will make it through, okay, so this is a solution, now we are going to see the second solution, here what will we do, use Bollywood. Now here how we are going to do it, so here we are going to use this concept here, so here how we are going to do it, but I remove it that I will give Morkel, then he will do his golden moments, he is your end login But it's going to happen because here what we will do is use a point and solve the stalls okay so here we are going to throw to what will we do here I will read a pin set up carrier okay so set Let me tell you what we will do in this, we will set our feet here, then in this tree, whoever is going to do the minutes, will do the Indian point first and will do the starting point later, then we will do it like this, so here you will have this or that, then twenty. First you will do the inside, okay and you will insult the tan here, now see, whatever is next, we will check for 1520 for this, can we talk for this, is it okay, can we book or not, starting is your pending. Okay so look here these days point even first mostly here and this is Sonalika here okay which on you can use both set up area map and foot here which we have here so this is your foot form So what will we do now after this year, when we see the point of the tree, will you point it or try to point it? Now we only look at the nearby element. The duty element is of the tape recorder. Is this a function of yours? It is a function in which you Log in, prayer time complexity is there, what does it do, this just greater element, it will give you the limit of just great animal, okay, so 1508, what will be that settlement, someone will see this figure, if you do not see the element, then just get Here in Africa, 20ml is not the one that came to you, it is yours which you will refine the element here, it means that the Indian juice will always be better, now just sign them, the batter is ok, so the below is 2810, not 810, that is always lagna even. This condition will happen, you have already got this condition, according to the account you have here, the element point has gone in this illegal and then again not, when has the map of air staff air job been created, set your element at your place. So you will check there, you will find it, if you fine it will give you a friend of 2018 final for the phone, well, now by pointing this, see, this condition has already opened, Acidity 131 Mr. This will be Lassi because this But notice if we fold then it is better, this condition has been fulfilled, now the second condition is that we have to check. Okay, first of all we have to check whether you got this here, did you get its per bond, if not, then that condition. Also, what can we do if no one is found, on the contrary, because of which it is not in the voice, not only in the suggested one, then it is a data element in itself, so you will get hungry somewhere here, it is okay, get lost in the next one too. So and when we check, we got this for this, then this is the condition, so you have the file. Now check this condition for, that is, whatever you fine, its second element, which is the second element of the tree, what should be your second element. What should it be? The rhythm of now should be. Here is the lace. Here is this symptom. S1 This lesson plan to-do list will This lesson plan to-do list will check this with the unheard. What will we do? Will not be interested in this. Okay, if we could then what would we do? We will cut it, now look at 2030, now if you are not able to do it, then you will not be able to get interested in it, then if you look for 10:30 pm, you will look for 10:30 pm, you will look for 10:30 pm, you will look for 80, now if you do 28.5, then you will get 120. look for 80, now if you do 28.5, then you will get 120. look for 80, now if you do 28.5, then you will get 120. First, this award will not get it, okay, then you will get points. Will not get the statement from none, it is greater than this, so what we will do here, we will simply book, we will book that our what will start for him, let's see about this also. Okay, see what setup we have taken here. These two are now it's okay by drinking and what we here that here and toe it are taken now also appointed bond start and in this side setting the form of year in but your which on the first value only what return you If it gives then it must have been given to you. Okay, it is returned. What will we do here? We will check whether it has not reached the point in the last week or not, if it has got the point then we will check that condition again. It's second which is calculus in, what if garlic India is in that condition, what to do with golden voice, what will we do, which is our side, we will set these first, then start later, we will do it through the fans here, simple. The code is I hope you guys understand thank you
|
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
|
729 |
hello everyone welcome to learn about in this video we'll discuss about today's little problem that is my calendar one this is a medium level problem and we understand what this question is asking us to do and how we easily we can think of finding a solution to questions like this okay so first of all the question says uh you are implementing a program to use as your calendar okay so your task is to implement a program so this will be our program over here so this we can use as our calendar okay so that's the task now we can add new events okay in calendar as you know we add new events if adding the event will not cost double booking okay so if it does uh if it don't cause a double booking then you can add so what a double booking is the double booking happens when two events have some non empty intersection so if we find the two empty are getting the intersection of the non empty section there is some moment in common in both the events then that means that's the double booking okay now uh if we just check then it's like the event is represented as a pair of integers that because they start an end that's a pair of integers given to us as a event and then uh it says that uh booking on half open intervals that start and till time that is less than n so it's like equal to start at less than it okay so we need to keep up yeah remember this thing uh so this is the whole idea now well this is like we need to implement the my calendar this my calendar is the class we are going to implement and uh this my calendar constructor is there which initializes the calendar object okay and a further what it does it simply uh there's a function called book you can see there's a function code that takes two uh elements like start and end if this returns two if we can book a calendar and it returns false if we cannot if there is a double book then we return false okay uh so that's the whole thing is being said just let's uh look at the example examples is uh the call of the function okay first this when you see my calendar so that means that's a call to the constructor is done then you see there's a book and book three times it's done so that means it tries to call this function book three times so that's the how the input is uh given to us and that's how we need to interpret it now when my calendar is called you see there's nothing given as a parameter so it is blank for us okay when the first book is called is uh called with 10 and 20. so what is 10 and 20 you should be like from starting from 10 till 20 you are booking this slot okay so that's the book you've done and since previously there isn't any other book so you are returning true out of this so that's look there's the first uh output is true for us okay then we're we got another book with 15 and 25 when 15 and 25 is there so that simply means we uh should start our booking from 50 and here but see 15 is something that lies between 100 if our slot is booked from 10 till 20 so that means 15 is already booked right so we can book this slot no so that's how that's why we actually return a false in this case okay next it starts from 20 till 30 remember the end is less than n so whenever 20 is saying book so that means less than 20 is booked so in this case whenever we're trying to book for 20 to 30 we know the 20 is free for us right so can we book the slot yes we can book the slot so we return true so we announced book the slot as well and for the initial case when the constructor is called is determined so that you don't need to uh whatever it actually does run so that's the whole understanding of the concept is now how can we actually go ahead and do this the first thing will be taken a list of say a two-day list a list of uh say a two-day list a list of uh say a two-day list a list of uh arrays okay array which stores the start and end and for each of the array element you just check if it's less than that or not and ultimately you can find what i mean exactly is uh first you note down that you start is you first start is like you make an array in the sense like a list of like 2d rather okay you just make a note that is the start okay 10 is the start 20 is the end first notation step next you find 15 and 25 to check like all the values you have in your 2d array uh in that if your start value is less than n or like anyways if it's start value is less than n or its uh end value is less than and uh okay like if any one is lies between them then you return false else you add the value okay so in 15 and 20 you find that 15 lies between them so you return false next you find 20 and 30 so you add 20 and 30 in our uh 2d list okay uh why i rather to the array but look in a 2d array if a 2d array has a fixed uh number of rows okay you need to pre specify the number of rows you know the number of columns will be two columns will be there starter in column but in number of rows we take so how we can power up that thing we can cover up that thing using an uh error list are a list of uh a list of integer arrays so it will be like a 2d array fine uh an array another array will be there fine so that's how we would define the stuff so that would be the pretty much brute force up so let's just try to uh go ahead with this approach further we will look for improving this code uh how we can actually improve this code is like you are using an uh 2d uh you are using the analyst and then a list of integer arrays right so whenever you are doing a list of digital array the thing is see you are actually drawing a line like this is the 10 uh tell 20 is a book for us so it tells in 20's book for us so next thing will be from 20 uh like if it's a price at the beginning 10 till 20 is work for us okay uh next 20 to 30 will be booked now 15 comes somewhere in between right uh when 15 comes somewhere can we book that no we cannot do that so what we can do we can uh improve this by keeping an reset like make it in the form of a tree that 20 is on the top fine uh from 20 10 to 20 is booked for us then uh rather than this other timings are free so if it is like 20 to 30 we need to book and we need to go ahead we can book and move 30 to the top so we can have a tree set rather like a sorted set it will be uh so we can do that and then we can uh keep finding the floor and the still will help us to find the starting and the uh ending of that so that can be an improvement to that to our idea okay so that is the minute but first let's uh just try out our brute force one uh let's see how our brute force one works and then uh if we are not satisfied with the brute force approach we'll try to improve it fine so let's go ahead with that so there you see our first approach actually works pretty good so how what did actually we did is like took a list of integer fine and further what we tried to do is like we uh initialized our uh calendar variable the kind of the list of integer calendar as a allo is fine further we are going through each of the uh like each of the array in our calendar like each of the bookings we have till now so here what we are trying to do is like if b of 0 is 10 fine is less than n so if it's less than end that means if uh b of 0 is less than n is 25 so that's true 10 is less than 25 and we're checking for if the start being 15 fine start is 15 over here and it's less than b of 1 is less than b of 1 that is 20 uh 20 so we're checking if n if the b of 0 is less than our end okay and uh b of 1 is like b of 1 is greater than our start that means the start is less than a b of one that means that lies in between like there's lies and overlap so if that happens we're simply returning false okay in the other case if that is not happening we will simply add a booking add or start into our booking and return it true that is our booking is done so that's the idea now how we exactly can improve this is like we can uh go ahead and say we can use a tree saved for this fine i'm just uh changing this code and writing it for you okay so that uh it becomes understandable to uh like it becomes understandable so that's how we improve it what we did exactly we were doing the same thing using on a less than an integer but here we are using an reset fine now idea being the same see like in preset we should mention that it should be like each of the uh like the array we are adding it should be like uh based on the starting index okay it should be ordered interestingly starting with this level the start time of each of the different now what are we doing we just uh took a book uh like the current booking that we're going to are giving us the it's returning us florence ringer so what is doing we're getting the floor value of the calendar like the calendar and the uh ceiling value of the calendar okay so like the top side of the like the already booked range we are finding out and from that if you're saying that if start is close then four of one that is the uh end value of the floor if the start is less than that then it's caused okay if it's less than that means we cannot do that father if the ceiling is a start value of the ceiling is less than our end that means that two means that we cannot wired without working and further we are simply if the both cases are not working then we simply return like adding our value like adding our stuff to our calendar fine we're simply adding this to a calendar and making a book are returning true so see we have dramatically improved our uh run time our initially memory was 54 mb and memory remains more or less the same but we see we have dramatically improved our calendar why is this so we are not checking for each of the bookings and checking for each of the booking and finding whether we have a slot or not rather we are finding out the floor and seal based on the range how we're doing see we're in the floor of the whole calendar rather the flow of the booking like this booking variable we have i was just finding out what's the lower value of this book less than this and what's not ceiling value the value of this book so yeah we know the particular range you need to look for and now we are searching for the value okay so that's the idea that's a trick we use to just improve our code and this functionality is not supported uh by our uh list so we have to go ahead with our preset helps us so that's the whole idea behind this now you can further improve this you know how you can further improve this where is tree set rather than using a tree set start using a tree map pre-map tree set start using a tree map pre-map tree set start using a tree map pre-map up to integers like start integer and then uh like the start integer and the end individual so if you are mapping it directly then you are not using that array so you are just improving the particular time complexity a bit more okay and we are working more or less with two exact values not that the whole uh arrays every time see here if you notice you we are using arrays right so you can like exactly if you see we are using errors we are using arrays over here fine uh so how can you go ahead with using a free map for this so that will improve the solution much further so that's more or less about this video guys i hope i can make you understand how this question works and how you should go ahead and start thinking on this kind of question uh also make sure to like this video if you think that this is helpful i can make you understand something and also subscribe to this channel for regular foreign in my next video as well thank you
|
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
|
60 |
Hua Hai Hello Everyone Welcome Back To Back Or Man To Day Problems Permission Sequence So In This Problem Will Try To Understand Problem Description And Will Provide You Hello Everyone Welcome Back To The Government Today This Problem Is Permit Action Sequence In This Problem Will Tried To Explain Problem And Will Draw A Different Problems Solutions For This And Will Also End Standard Time Complexity For This Problem 15th Process YouTube Channel Please subscribe this Light of Cooperative Problems and Right Knowledge with Problems Ur Problems is the Best One Two three little and contains a total of and factorial ionic permission and life by linga and traveling observations in order to get the following sequence for any one to three lakhs of you have any school Prithvi-3 three lakhs of you have any school Prithvi-3 three lakhs of you have any school Prithvi-3 number one to three for the least they can generate All 1053 withdrawal weight factorial permission skin generate fennel and 383 factorial is equal to go into six and the from given in the written update parmesan sequence and write short end of this given bhind to generate permutation and return field per meditation from the result ok fear in The example of physical three and physical two three for unique third permitted to this going to be how to mantri singh ko foreigners 124 and where is equal to three places and result it was not understood with the example sum possible solution of birth gender all the permitted To return personality which a menu love generating stations for pattern for example 123 will give the first element and first taste and fast elements in love between ten people subscribe that the first one of this bill is equal to study and will play with r * Bhavan pattern and forest * Bhavan pattern and forest * Bhavan pattern and forest combination will be based on number all right inside also vansh or combination online day will fix that court will move to the first position and behave with no these two elements of word next element login will keep it Is The Information And Verified And Will Be Next Point Doing This And Next Point Doing This And Next Point Doing This And Teachings Which Form Will Start From Zero Will Put Will Give Chance To That Number Online Software Ka Descendents Stadium Din Hero Also It's Going To Study Only So You Will Put This 250 Unreal Engine You Will Work Without Singh And It's Rather To Study Yaar Thank You Will Put One In The Newly Married To Ultimate Love-Vyaar Traveling This Numbers Between Their Ultimate Love-Vyaar Traveling This Numbers Between Their Ultimate Love-Vyaar Traveling This Numbers Between Their Indices For The First Time Will Feature A Steady And Day Hi Custody And Dhani Clear Swift In General To Overcome all victims to retain list will take blacklist and Cathal Parmesan from despair and vitamin E that all right only half drop back of this permission not approach SSBR doing permitted to be guilty callers of and factorial of year time complexity of that Need to explore all possibilities all sorts of things will not be interested in all the combinations like you only want one combination and this is also the statement flash lights all two will not need to generate all the combinations and start then that combination is ultimately we will also find in Factorial Space OK Khabar Did Not Record There Only Want One Combination And Age Between * Retired Snowflakes Understand There * Retired Snowflakes Understand There * Retired Snowflakes Understand There Different Approach And Will Laugh With Difficult Pattern In The Given Nak Combination Her Viewers Pay Aa For This Half Inch Right In This They Will Achieve Fixing The First Number one I am online than Ajay Devgan to number can we can write in this way foundation of ki tu menu 3 the walking singh gosal dhondu you can write permission of two plus we are the number and were playing with the number one shri m ki singh us For every year because Saurabh Singh years whichever way you have any to the four left hands is free and number starting from 12314 senior in this scenario will write in this only they will be 10th and permissions can be one plus permutations of two to three taken before the second per medicines Can be permitted in this way of keeping to well fix permission scan bhi vansh hui and former dhaneshwari three a plus permutations of so why and vansh to and 4 and where keeping force fix daily permissions going to be warned to and three servi tup Tup 80's Hui 9 Years When You Have A Say Hello Friends Welcome To Three Do It Means Starting With Zero You Can Always Create Above Meditations Because Symbols For This Also With Total Six Patterns Soich Number Will Give You Will Get To Patterns Symbols For Hero Also If You Have Any School Proof And Date Means Starting With The One's Good Effects In This Number Have Enough And Magical Tourist Having A Physical To Three Does It Means And 123 Ok Login With Starting With Wave New Remedies To For You Will Have A Total Six Patterns Opportunity 6 More Patterns As You Can Create Finance Starting With One Is The Means You Have In Your NH-12 406 Pattern Means You Have In Your NH-12 406 Pattern Means You Have In Your NH-12 406 Pattern Starting With Wave This Monthly Pattern Starting With Vansh Goals For This End Symbols For This Is Not Show One Thing I Know What's Like Aa Gai 2 D N Order From Were Amazed E That You Pattern Is Getting Started Lips Say If You're Very Few Words Interested Tup tup Tup Number Index 0512 2 F 3 to 4 5 Given December 09 From Maze In The pattern which is having constant and to the con is starting from doing to steel teen pure twin no because every where vinod at how many patterns it's going to have ok so let's give the k a for example lichchvi chuke hu is equal to aa 2015 The World Is What We Are Interested Clear Is Want 14th Pattern That Your Butt Lakshya Vihar Phase Show Will Always Stay Hind On This So Will Love Will Improve World Comment's First Pick Usse Zor Ko Default Invented Jatin Okay Morning Se Quiz Equal To Thirteen Switch Pattern And between number pattern will start first saw your first two this will go from 025 stop near 10 will go from zero 211 this will grow from new york 12th and tell you will go 17 in from 8am words to 35 and ayush per ok morning no One thing is a few cases total 214 and business interested in this also in the middle of his forehead is one thing in your voice your first index and first number has been thinned into it today to apply same logic in this french ok fennel how To How To Get At Index With Which Indicators To Into Me First Number Four That You Your Appointment Thirteen Okay And Not For Each Number How Many Fermentation Civil Me Dat Will Be You Can Come To Know Why All Acts As You Have Enabled For The Formation Set will make with k is equal to two one in the first places pure and minus one for this is the force one minus one parmesan cheese will make with one is equal to two one two three places of worst position show this Jatin yaar k you will do And Minus One A Patrol In Dollars Video No Yes Same Numbers The Show Website Mentally Week Juice Calculating And Tolerance Or What Is Range Or How Many Numbers Of Parmesan Cheese Will Create A Government To Shift Do This Calculation Thirteen Noida 63 The Will Give The Ka Result to back means this is going to my first number I am online at som will put first number from this three layer a ki aapke na ho our number is not reduce to this vansh 2 and that ok and now how to select next number from given Set Nadha Begu * When is equal to three wickets Begu * When is equal to three wickets Begu * When is equal to three wickets that me to select1 number to remove the for no any reduce to three languages free reduce to three languages free reduce to three languages free numbers have to select number four na our k is not going to be easy for all it's not going to be thirty in Fu anything already calculate the first elements what is vansh ke veer and that tweet to calculate sophie dee we already calculated ke vikalp ko thandak mens ware already script 20 numbers and phone numbers were selected soft we will update and ke with hai 10th issue hai us E Will Do K - And You Can Do K E Will Do K - And You Can Do K E Will Do K - And You Can Do K Mode Dip Pure And Minus One Tomorrow Morning Ultimately Doing This You Have A Thirteen Okay Fennel And 12% Actions You Already Fennel And 12% Actions You Already Fennel And 12% Actions You Already Calculated On The Number You Have Selected For The Voice Kids Friend Money Permutations Sorry for the parmesan cheese in it already selected this number 9 forest octol k and what is vansh k me to stitch when you are eligible to 300 for that you and k is going to you can take k mode yellow and minus one day which is going to be in Six Sonth Are Ultimately Doing This Thirteen Modules 6 That's Gold Border Reminder You Have For Date That You Want To Get The Next Element From Your Bad Istri Element That Which That's This Young Man Will Be 9th Team And Tilak Six To Keval Bhai Jaan A Soldier's School to Descendent Bluetooth Turn On This is My Set Will Repeat This Process Sage and Will Find Doctor Sambhavna The Next Numbers OK and You Will Get the Result of Flight Knowledge Take These Example Sentences with Approach Will Discuss Previously Remedy Then Numbers One to Three Subscribe to my channel on four wheel want after number k 2.1 index a 2.1 index a 2.1 index a little going back k divide by and minus one open the mode k aapke these days will update and k with k is equal to k modules hua hai - one factorial not in This world will hua hai - one factorial not in This world will hua hai - one factorial not in This world will discuss and this same pattern will return to witch to the fifth complete the in this world will and in this process will result in all its worst subscribe button - 12351 subscribe hai tu ok so let's sakta hai and results in liquid results here ki History first will select number that from back to so pimple two-three miles from back to so pimple two-three miles from back to so pimple two-three miles switch off doctor and first element ok n Be Easy One Torch Light 25 K Is One Okay And Have Already Taken 3 Gold New Result And You Agree To Be Born In 2nd Floor That Your Knowledge Straight For The Next Nuvve In This Reduced To 30 - One The Walking Improved This Going To Be Easy End Modulo Sutra - Bandh Studio So Let's Go Modulo Sutra - Bandh Studio So Let's Go Modulo Sutra - Bandh Studio So Let's Go Into Be One By Two States Will Give 0f Element Will Take From States Will Give Three Laxative And Nav Liquid The Next K - Aur Yeh Saver Mode Kholo Hai Tu O Ki Bigg Boss Beating In Flying Saucer Minus One So To-Do List Will Give Saucer Minus One So To-Do List Will Give Saucer Minus One So To-Do List Will Give You All in One Okay So Strong Acid I have one from the matrix itself and that is them Terrace 104 A Sleep With Same Process This Time quiz-1 Again my A Sleep With Same Process This Time quiz-1 Again my A Sleep With Same Process This Time quiz-1 Again my line reduced to minus one this module 29 The arranged result we give you will give you results on that a that show will select it and you sir element from index one should they will get the result of 30 select this element so let's go into b4m that nav alag calculate the that city. Open Vaastu Mode Before Echo Interview And Admission How To Minus One Factorial Arrangement Is Zero Two And 1000 Divide By You Are This Time Jobs And Watch To So A1 - Is Jobs And Watch To So A1 - Is Jobs And Watch To So A1 - Is Vansh Sector 34 Point To 2009 And They Will Pick Till Next Elements From Dowry Jai Ho members will be the final setting that will return in the result security from bank factorial of problem Vijendra is notification solid in the end square nor a defense hearing at the first thing every thing is for any to 4 visiting this post that your end The Things That Was Doing Seervi Every Time Before Removing The One Elements With Justice Removing Any Element Is Still After Okay You Should Have For The President Rule In One Four Three Months Solid It Into His Knowledge 24 This Ki and Sandy Online Let's Go Through This Cold Solve The First World We Have Just 120 Days Were Taking One Element From The Result And Were Planning To It's Good To Have And Stringbuilder For The Result Of But Its 19 Number Vivo Define In Just To Generator Numbers For The Giver And Every Time Vipin Yadav Limit From Despair And Which Moved From Its First Minute Is Going To Be Our Set From In Which We Would Like To The Index In The Third Number From The Factorial Use This In Tears Effect Is Going To School When You Want To Calculate The number yes in - 1m - to every time vihar yes in - 1m - to every time vihar yes in - 1m - to every time vihar updating and so will be helpful in that case to calculate the effect toys I have to and ministry of equipment and variable products soft first will do is first will affect start from one and to Land In Village Generator Factorial Number One Will Generate Number 109 Internet Statement Reduce K 10 Will Start From 0 To Calculate The Different Competition Will Return Will Reduce K - - Competition Will Return Will Reduce K - - Competition Will Return Will Reduce K - - Verb - 9000 Number Switch On The Number Will Get Verb - 9000 Number Switch On The Number Will Get Verb - 9000 Number Switch On The Number Will Get Number Two Plus Two Who Is The First Factorial What they are doing this will be generated factorial formula and numbers [ __ ] and they want every where to be formula and numbers [ __ ] and they want every where to be formula and numbers [ __ ] and they want every where to be my first will start with in the native will go to and minus to in ministry debt waiver of soul witch software calculating default ruler updated first will start earth Is One Factorial Day Will Divide Between Under Factorial Of Soul With Jeweled Will Patience To Give The First Indian To Also Printed Posted From The Amazing And Will Vote Will Do Is Will Remove It Also Develop And To The Result For String In The Next Will Update work is 120 already calculated factorial The Means World I have this Will have to deal with values Will draw model with k and Will values Will draw model with k and Will values Will draw model with k and Will update work And will be treated for the number of times Will have different from President Will finally returned from this code And Will keep pure tone third hour medications and 19223 Nanak submit that your bad submit knowledge sir war memory usage what is the education time ok sir 1957 the execution key and memory depression also loot 94572 and life person this video you like it gas acidity problem solution cider Suggest you to write down the comment box asind next video trailer time back to
|
Permutation Sequence
|
permutation-sequence
|
The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:
1. `"123 "`
2. `"132 "`
3. `"213 "`
4. `"231 "`
5. `"312 "`
6. `"321 "`
Given `n` and `k`, return the `kth` permutation sequence.
**Example 1:**
**Input:** n = 3, k = 3
**Output:** "213"
**Example 2:**
**Input:** n = 4, k = 9
**Output:** "2314"
**Example 3:**
**Input:** n = 3, k = 1
**Output:** "123"
**Constraints:**
* `1 <= n <= 9`
* `1 <= k <= n!`
| null |
Math,Recursion
|
Hard
|
31,46
|
1,834 |
Right meaning what are we doing today is daily need for problem single thread CPU let's start d problem basically you have bin given an 2D vector you can say on r of a where are any particular elements you no take out d vector from this you earn four Dot represents something like this a particular task date is starting time is equal tu starting come you know time = 2 and d length of d you know time = 2 and d length of d you know time = 2 and d length of d stars is equal tu something like for so this vector represents a particular task where task is equal tu AK time basically you can say d start in time not starting time but basically you know c p scheduling work so d task come in tu d you know shad url q so this is d time come which is d task come in d when So this like task comes at two seconds and processing time by task leads it's 4 seconds so you can a lot while doing task or else what do you know time which is greater because before you test for not there is no time Equal you task come over every so you can else start time for you and three and four our show on right so and give this asked available you process and will be process and how you will schedule will happen based on days for rules you have your On single see you single friends you can perform only one task times so you will call please one earn you task so for if you start you can only started because de list thank you time which is given so first ask from date one time and you Have tu in nine single thread it men only this will completed at all you know nine van plus tu was equal tu three so de task will draft drain up tu from time gan tu time three not time bikams equal tu three and when time is equal tu three tu task half bin come tu dee you know you should be doing so nine days tu task can be allotted see you dee risk clean of four come van ise still not there it will come after same time now currently dee time ise like three so Aate Time Tel Time 3:20 Have Come three so Aate Time Tel Time 3:20 Have Come three so Aate Time Tel Time 3:20 Have Come On So C Will Choose D Minimum They Have Said OK Aate Most Wonders And If There Is Un Ideal De C P Remand Ideal And Available Task Shortest Processing Time For So This Is D Only Thing You Important Note Over her you know this tu task there so still because her length is kitni hai tu hai so its length is tu so I will choose date wala starting time whose three is whose length is you know three kama tu and dene main after performing discharge Currently the value of my time was three so I gave time three to it CPU so three will take time you so nine time is equal to five nine this toss how also period and between days you I will first process this task because its ship length is one So tha ho you will proceed nine next what will you do time watch currently five you will currently just under 4th number task so you can also write it over every key i am running for kama van task its starting time is my starting time its length is one so it will take you no one second so no it will take your once again so nine d current time is equal tu 6 so abhi one d last element which is left is tu kama four this is basically this The task was started a long time ago It came on D Time = 2 nine Current It came on D Time = 2 nine Current It came on D Time = 2 nine Current time is equal to 6 So 6 + 4 = 10 After time is equal to 6 So 6 + 4 = 10 After time is equal to 6 So 6 + 4 = 10 After processing this toss So that's what you need to do So the first thing is that which is yours of the task Let's sort it by the starting time because you know which task will come first. This task will come first. Give this task will come. Basically you know you should know what order the tasks coming in this order. This is not the order in which C. CPU will be un because same thing happens then question is refill sir my aansor zero van tu three hota cpu will be returned some other way but first of all you know and this is not given is sorted so first do it less Like make it practical because practically this task is coming first at time = 1 but time four is coming time = 1 but time four is coming time = 1 but time four is coming right so time here pe three is not common only that and here pe van kama tu because if this task comes on time van pe So come first na so when you will do this then let me tell you the logic first nine you have sorted it ok basically it is going to happen now you see us one currently we have so many tasks available ok and on time van pe so We have only one task available, if you earn money, then come on here, there is only one, so I will schedule it directly and give it to the CPU. Now as if I have reached time free, like it is written here, I have already given time, if you earn money, I will give it to the CPU. It was reducing and I rewrote the schedule. Okay, so I gave this task to the CPU and when will be its entry timing? What will be its time? On OnePlus 2 and on 3 it will end. Now what will be the situation currently on P = 3? Now what will be the situation currently on P = 3? Now what will be the situation currently on P = 3? My CPU schedule means what tests are there in it. 4 This is there and three are common, right there, so this is your task, which is included in DC PC, which one you take up, my choice. I tu three kama tu a tu this because length was minimum on them shortest processing time so is late and date of structure and use of your p k u and basically vector of advance three kama tu is un vector right vector of inter kama vector Of vector and give greater of actor is ok now basically wheel maker comparison update its you know man lo iski bhi length tu hai aur tu wali ki length bhi tu hai witch van tu take ok obbviesli if seen then let us decide on the basis of tu We have to do it on the basis of length, what will we do if the length of both is same, so multiple task from D, shortest processing time will show D smallest index, so how will this happen, you know this, I don't know this is generally done, so we make a Comparator. Due to which I can see the noise which I need for comparison, I will design it accordingly. Okay, first of all I have to compare it based on the length. Second, I have to compare it based on you know the starting time, so I am taking the minimum of that also. Create something like vector, we can apply it in vector also, we also apply it in Comparator set, there is a little something unique in priority for this, because today you know, we call it min only because it gives us the minimum value but it is exactly the reverse. Okay, that means what we normally do in vectors and sets is that your minimum element is lying on the top of it, so see what we do is that it returns A of zero if it becomes equal, what will we put? Just directly in D because we have not started it, starting you know the starting time, there is not much less but we have come to starting for the first time, right because it can also be like this, starting time you and the other four, we will choose. And basically we also have to return the index along with what was its original index so what I will do is I will keep a pointer to the index and this which is Tascam first okay this give it like this is the real thing since they are doing multiple tasks. There you know three kama tu hai and tu kama tu hai like dust and let's say tu kama tu hai and three kama tu hai theek hai something like date and actually the tasks come in which order the tasks come in this order the right hai meaning test If it comes in the same order, indexing in but question is how to give Rakhi. Let's right question. Next is such a na de Rakhi. Indexing in hoti question is now tu bhi tu hai and 3p2 is question number three, you earn first and you earn later, okay so. We have to print the index, we need to return what we have to return, let us also see the order in which schedule, sip you will schedule and basically we have to return the index, we have also written here again what Victor has to be created, we have to use zero. What does it mean here that zero is written on the first index? What does it mean that first of all we translated zero and you are written? What does this mean? Then we have 012, then we have 3 2 and create a vector inside the task. Return of vector and witch indicators. Like ho in watch order you have process de task to given task in this order so you know now I have sorted so three tu van main ake tu earn tu first a gone now you have will you say that I am going to take now who Sa meet I will take element 2 because obviously its length is small this is the problem I will not take to come at all take three come 2 because of its length to tu hi hai both have equal length and index of three was less see three first Index three earn you earlier you were earning from you so now how can you do this will do date one way to create its mapping that I will create in these that particular one is mine or vector which is my index pe a raha hai but that will cause this problem you know because C has not said repetition is not all let's 3 kama tu is also at this point pe a raha so you will store the index of three kama 2 in the mapping zero van tu three but Actually three common tu ka and next this van also three kama tu now send this tu index so what should I do by modifying this re, how to modify van kama tu kama zero append this inside the current element okay so you Like its index is three so I will append you D, so now I will get its indexing also, because date I need you return in D last, also on the basis of indexing it, I can also run the Comparator here very easily. Like, there is no hassle in this, if we store the indexing in the character map, then it keeps changing, so will we do this basically, appending it is not much difficult, you are zero ilessn, I plus, this was actually quite an important logic in it, which I am less than. Can you understand this, how to return, because in the future, when we will pass in the priority queue, what will we pass in the age of priority, now look at this three kama 2, it would not have been written like this, first of all its length would have been written which is you. This is because look why the party is sorted normally, it is on the basis of the first element, okay now its length is on the second next, we have the length, so here also you are on the second next, brother, what is your index? Ok so tu kama tu is written here index of 2 is written here late se 2 ok index tu hai is its index ok so whom will I do things I will choose tu kama van because of its length you are the index of this van It's because this van came earlier from this you, so those thoughts are the same so this is basically I write here this is basically and this is the index okay let's go and make a Comparator here we make a Comparator return if A1 = b1 here we make a Comparator return if A1 = b1 here we make a Comparator return if A1 = b1 So you must not be one but this of zero is equal you are of zero if is or not both the length is equal then will do comparison based on which key should be shorter is fine and shorter is priority key then it has custom Comparator While making it, I wrote it upside down, okay, these are all zeros, let it be greater, A B of zero, what does it mean that your first index should be small and if the first index is equal, then your second element should be small. What does the second helmet represent? Its index should be small, okay, this is D. Basically, think a little about the priority, you can read it by searching about Comparators, you know, you write reverse in this because part of the in built functioning is a little reverse, okay, generally set and factory. So we can directly say, if like I want it to be small, then this is zero, if we want to shoot in ascending order, then we have to write this, okay, and max is okay, so now let's talk in our current time which we were starting with. Start at what time will we do the simple first test? When did the first test come to us? Option zero earn zero this is d starting time of d first ask how long do I have to run until I have some elements in my priority or else Now look at this, what will be the situation after taking the current panel task, I have shortened it and written it like this, okay, three come, you come this, then four come 1, let's write sir, four come one, this is on the third index, so now it is like this, first. Element I said that first time will be equal to you van because this is the first element and we have only one thing on it, so we will give it priority group and remove it from here, okay not remove, basically we have come as If it was here then now we will move our eye to here and in priority I have got my helmet, okay this is becoming my time here, my equal, you cannot do anything else till three. I will see that this is already done, I am a priority, I am still lying there like a van, and I will append the priority queue to both of them and that priority has also been erased, so when I put the end of this priority. Give it, I took it out on priority and it was time for me, when I got three, I got empty in priority because I have finished this task and I will give these two teams, within the priority you like, you covered, you gave it and I earned three, you gave it to team. Now it comes to the question of what is lying in my year, now I have taken the current, my index must have come down to this point, it is okay because I am giving priority, I am going to keep putting till what is the condition, I will tell you in the party. Look, it is simple that what is your current time, okay, the current time is greater than and equal to you, now the current time is three, okay, so I will go quickly, I will see where I was lying right now, I am here. It was okay, I was lying here and my current time is three, it is okay because when I started I had given this limited team and when I give admit team, then I have given I plus. I also do it, okay, so currently I am lying here, but this thing element has not been added yet, I am just lying here, I have done plus and I am here, okay and now I will see what should be the prior current time. Gya current un time is three like I have processed this and I have not even added this element yet Preet why is it then I will see as long as your current un time is greater than P of I come this currently now you want to see the element If its starting time is small, you know I am common zero, then you will keep pushing it, okay, that means we will post P and K dot. Hey, it has become quite cold, then what will you do, I pushed both the things and I have pressed Dates All Watch It Do Now I have done something Now what is the condition here that how long should we go till I come My lesson is M and why is there a priority if there is some element Now I wanted to tell this Basically you also do not write that take ice of K dot size. There is another condition because the size can also be different because at the last moment you will see that your ice has reached here. Okay, but there is still one element lying in the priority. It is okay, maybe there is more than this, we still have some of this thing, because if we look at the initial, there is nothing, but I = look at the initial, there is nothing, but I = look at the initial, there is nothing, but I = ≤, it became our priority to put it, we did the process, our time got free, then it showed how to do the process. Let me give that if why I should be something okay like I have to put because it can happen in cases that man lo something is not a only that will also tell the case but k is not size so first of all we auto f is equal to you k We have removed the dot top and now because we are emptying it will become empty at some point of time and after that we will not be able to do anything in it, so why the size of the key will be empty here also, okay? Let's see once, first what is happening here, like I have taken off my top and popped it, now it comes to the question of how much will my time increase, okay it is like I am taking a helmet, I have consumed Van Kama Tu. If taken, I will say time will be increased by F off, where was its timer stored, brother, van is the index, its length is zero, so I have made it plus, okay, nothing else, just a lot of seconds, basically, the index is here. It is not done yet like now my time = How much is it three then else time = How much is it three then else time = How much is it three then else I will not go because it has got van in it, now it will start moving again, will check what is the value of i has actually become van at this time. It's fine because like I told you, I came after consuming the van and checked here to see if my T was there. First of all, I had set the T on the van so that I could lift the Paradox. After 10 minutes, I lifted Paras so that I could push. I made it a plus, now I have come, the value on my van is yours, that is why he could not take it here because the value of time was his time and the salary had increased by 2X, so he did not take the earning on priority. We have done the process from Van Kama Tu, now we have come here, now what will you do, you were here earlier also, are still there, now I will check the value of current time, I made it three but if it is bigger here, now you give this less 3. Okay, so you give this less than equal to three, then it will be pushed i++, it will go into it will become 3 ≤ 3, i++, it will go into it will become 3 ≤ 3, i++, it will go into it will become 3 ≤ 3, it will go ahead and give it note less than three, then you will stop here, you will see the size, how much we have done on the priority. Two sizes have been done, both of them have come, which one will I pick? What van will I earn, what will I not come, I had gone to the priority, you had gone to earn zero, you are present, zero priority, I am actually, what will I go to, 2 present is mine, one D is on the first index. And you present time is my third index pe sorry second next so which one will I pick 2 present is my first index pe which is you present okay so I picked this one I popped it from here and the value of time what did I do Yes, I said, brother, make P=5 because I must have done said, brother, make P=5 because I must have done said, brother, make P=5 because I must have done some garden in A, you know, and B. What was its F off Van, yes, go to sleep, what was F1, I think, what did I write here? Index After this, I stored the van, after this I am doing it in this, when we will talk, first 1 will come, then you will come, then three will come, then zero will come, first of all zero will come because its length is just how much is its length, oh God, this also has its length, you are its. You are also of length, she is also of your length, I have done this, but come on, still there is a problem, why did this lunch happen first, but you are three, its starting is you, both of them are of length, but the starting of both of them is very small and yet Like its starting is starting, sorry not the index, its time is small but why did it go because its starting okay so there was a present my tu wala and van wala went so meaning it will become mine okay first of all here in my vector The value of the vector had become zero like this, after doing a run of zero, now as soon as I push it, I will turn off my weight, then the value of my vector will be that brother, you have taken zero also, you have also taken the van, so the answer should be but simple. This means that our answer is correct, okay, so you earn, now you will see that the size of K still means you know no one else, I will not go, okay and then we will see what is the current time, the time should be my five. It is okay, so now you earn, you will also come, becoming four will also come, okay, these four earn, 1 has also entered only, so actually this is one more thing, it will not happen like this, see, this three one, this true one will work, this first three one will work. Will it work, then this one will run, it will be something like this, zero one, you are three, because the four one has come, like if I have run this three, then what is the time, my total has become 5, this four has been entered, now the entry of four will come like this. If I go to take out the top of Van Index on three, then he will not give me three, then what will happen because of the top, this one will also get frocked by hand because like I pushed in it and made I plus, think. Now I came and my plus became plus like these 4 meanings, where was I before, first I gave these two groups, I had said that brother, current time is free, which should give it a greater, you know for, so I left it here, now time. Five is done which is greater than fourth So I pushed it and sent I forward You know I is greater than and no it's done You like n = n is done You like n = n is done You like n = n is done I = n is done and let's not size I = n is done and let's not size I = n is done and let's not size My note was empty and I took out 4 from here and what did I value the time, the timing was equal, you were on 5, my condition was like this, you were earning, and on this, three were common, here you were stopping earning, after this I was here. I had to pay a little less and I had put Victor in the last position, I had put him later and because the situation had become such that here you are 30, the van commentary will leave from here, okay look at the value of timing, we will be six and then Go, this second task of ours will be run on priority, absolutely you know, you earn 2 3 on priority, that will be our empty because we have zoomed this one, bikams mp and vector will be our something like zero one three, you are in this timing. How many of us will go 10 + 28 and that's it, nothing else, so now look here 10 + 28 and that's it, nothing else, so now look here 10 + 28 and that's it, nothing else, so now look here we came, now our I had crossed, okay like now I took zero one three sub here, when did I put this in Victor, when I came, I crossed. It was said here that it is okay, I is bigger than N, here a condition has to be applied, so at this point, like I said that if the number three is bigger, then I will do plus, now it will check whether this element is yours, so check. I can't take ice, so I have to put a constant, so he said, stop now, look at the kit, the size is fine, what is the size, these two have already come, this came and you earned, you had already come and the meaning of van is that you have already come, van com. Three A's had finished, then I said this pop in karales, I have been in it, then I tried to play brother look again, did I come inside the statement, so I have ended, but why's size is still not there, this was the point. What I was trying to tell for a long time and we got this opportunity to tell on this example that when your priority cute van has been scored for Kama Three, okay now if it is a priority then our van has become Kama Three. Tu Kama 2 is left, priority will be yours, but yours is not vacant, but I, yours had become N long ago, okay, here at this point itself, your I=N had become like you have made van com I=N had become like you have made van com I=N had become like you have made van com three in your priority. Pushkar i plus so i checked it out of war so you left i n and you here you take this out then you went back you saw i then equal tu n is done o end and no And because if you write Andal then it will not even check it, meaning in You Know and Give, both the conditions should be true but this is false but if it is true then it will still work, it will not go inside the look because to insert some bugs from the office. But the one whose size is K will go and when it comes to others, that case has not come here, that case is something like this that if your first trans comes, you are fine on the next one and you are on time and its value is late. From 2 and best second task comes your 7 p and its value is from late 2 so the first task will come ok first I will do the value of city and then and at p = 2 I will check and then and at p = 2 I will check and then and at p = 2 I will check that now the value of my current u What will be the second? Let's also check its index. Its index is zero. The index is one, so the length is lying with me. The index is zero, so what will I do? I will pop it. Then my priority key will be empty. Okay and I am here. What will be the value of my I, which is not equal? Okay, the not equal? Okay, the not equal? Okay, the value of my I is N = 2, so there is I, value of my I is N = 2, so there is I, value of my I is N = 2, so there is I, but the priority key has become empty, still it will work, so now what is the problem, what is the value of your timer? Plus made timer equal tu maine plus kitne se hoga ki tu pe tu aaya tha length tu three to timer = 4 it is done ok so timer = 4 it is done ok so timer = 4 it is done ok so timer is mera four you know timer is mera four i = is mera four you know timer is mera four i = is mera four you know timer is mera four i = mera 1 hai mera reach here He is standing here in the middle, I came and it was as if after taking this he had checked that Han Ki Tu give this lace is equal Tu Han Tu, take it 7 Okay, he will stop here and will come out from here. Will change the value to four and here in the answer vector it will also push what is its zero and will make the text that I have already run the one with zero index. If the value of the image is four then now it will check here. So it will check here and it will say. Han less dene hai rather priority tu zero ho chukhi but koi nahi i ≤ city four is not pushed will be okay it will not go inside it because this wild and condition is false here I can't write anything else because both It means this condition is true and what will this push do? Here it is possible because I goes beyond N, so how else can I write not here and I can't but here and that's why it is written. So that this is less and always have to be checked, okay this can be true sometimes like it is not true that the value of T is my four and I am getting the current time of my seven but I am not including the seven. If I could then it will keep on waiting and it will keep on doing so we have to put llls that man take the waiting which is going on and t it is equal tu marks off not, you can write like this if your priority is done then turn off the current time which Your next one is fine because the priority is your MP. Now I am not thinking about anything because the priority is completely empty. Now if you want to take the next element then pick it up now. It is okay because of the current time. We had set for the first time to pick up this element, similarly to remove 7, we will set the current time from this and that's all you have you return everything is correct okay let's comment on it not b d name off How does this happen, what terror happens, just like this, the structure is sorry, the structure is a good problem, it means a lot, I sorry, the structure is a good problem, it means a lot, I sorry, the structure is a good problem, it means a lot, I first wanted to do the mapping with the region, I cleared it in the beginning itself because if element 2 4 is taken again then the value of the mapping. Do nahi ho paayi ye na t plus equal tu f of zero ka sorry ka sign raha hai. Actually I think this is a very big test case and this is actually the last one for me. It is not a matter of logic, it was not simple, it was not even straight forward, but the thing is, if you have read Operating System in OS first, then this will be easy for you, and if you are going to read after this, then CPC for You but the thing about this is its priority I have done it with custom Comparator to date something new and this loss is not new but you form this logic is actually the thing basically it took a lot of time to fill the form of this logic but I Hope I am explaining correctly that if your for example you want to see where your current index is moving and the age of your priority how many elements are there and what is the value of your current timer if the value of current time work which is It has also been done, according to that, we will add elements and insults to it on priority and we will pick the best option out of it and keep doing this. It may be a case that your I know end may be on time and you know all the helmets. There is something lying in the party and you do n't want to add it but that is already lying in priority. You know it's like in this case too, if you had 2, then everything went on, you earned one, you went on, you earned three, you went on, you earned four, you went on. Gaya But Ye Tu Kama Four middle one did not run, so how will we remember it that brother, an element was read in the priority, it has not run yet but the value of I has been done, the mobile cross of four has already been done long ago. I have already done it, but this helmet which has been lying for a long time, do it as well, okay, so this is the thing, it is not the size, that is why we are doing it, and this is just a corner case that in the example I have given, you earn. 7 2, you mean it has reached here but the value at the current time is not enough to take the cell, so we will have to reset the current time and then set it like we did for the first time because initially Present Time How did we know that we have to start from here, we are starting from here because in the list we will start from the first element from where it is starting, there is no point in starting from zero, meaning look at it this way. Now you can keep the value of current timer as 4, it is okay and you do the next test, but either you are entering it because the size of K is lying there and it is not given here. There is no use here. If I am not able to enter this then either you directly make it equal to City. Let's do City Plus. You can also reduce this option. I am short this will I think because the value is also brother 10. Power is 9, you can't increase it till now, it is better to increase it, directly reach the person on time, what he needs next in time, okay, so here I think this will give you will reach on time.
|
Single-Threaded CPU
|
minimum-number-of-people-to-teach
|
You are given `n` tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `ith` task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing.
You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way:
* If the CPU is idle and there are no available tasks to process, the CPU remains idle.
* If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
* Once a task is started, the CPU will **process the entire task** without stopping.
* The CPU can finish a task then start a new one instantly.
Return _the order in which the CPU will process the tasks._
**Example 1:**
**Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\]
**Output:** \[0,2,3,1\]
**Explanation:** The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
**Example 2:**
**Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\]
**Output:** \[4,3,2,0,1\]
**Explanation****:** The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
**Constraints:**
* `tasks.length == n`
* `1 <= n <= 105`
* `1 <= enqueueTimei, processingTimei <= 109`
|
You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once
|
Array,Greedy
|
Medium
| null |
1,953 |
hey everybody this is larry this is me going with q2 of the weekly contest 252 maximum number of weeks for which you can work hit the like button hit the subscribe button join me on discord especially if you like these contests i me and so a lot of uh smart people usually join the discord to kind of talk about the contest right afterwards so if you're into that if you're looking for buddies um join the discord come hang out uh okay so with this one i actually spent quite a bit of time especially compared to other people but this was a really tricky one i think this is not going to be an interview question if that's some you know just to get that out of the way because this is more of a code force problem and if it's a code first problem i think it's a maybe like a diff to b or maybe diff to c but a very easy c um because this is a logic problem maybe you call it greedy maybe logic this is a really awkward problem really weird problem and you just have to kind of um just believe in yourself i suppose during my ritual contest i definitely download a little bit i don't i thought about things until i cannot think anymore and i just kind of submitted hoping that you know the proof by ac is there is sometimes that i use and abuse too much in code for us um but that said gold by ac only works if you have a lot of experience and a lot of practice because one because you know on a subconscious level if you've done more problems you'll see patterns and think about it even if it's not on a conscious level or not on a level that you can prove per se mathematically but that's okay i'll try my best to explain this but this is one of those things where knowing the answer you can explain it a little bit easier um because like ah i know the answer so it's either explained but to be honest it was a little bit tricky to come up with it so and i think as because this is a virtual contest i am more articulate about my thoughts as i'm doing them during the contest so you know after my explanation feel free to keep watching how i can progress to the solution this is kind of an awkward one and a weird problem in general but the way that i initially thought about is okay um what is the like i was thinking about greedy solutions and the most greedy one i thought would be to um do some kind of cue or a bina or another cue while a cube with a priority queue right a heap where you know you take the two max milestones uh and then kind of do them like consecutively right um i actually don't even know i think that would work um but or that works in theory and i think that's a easy-ish greedy and i think that's a easy-ish greedy and i think that's a easy-ish greedy however each milestone is 10 to the ninth so that so from that i knew that wasn't really good enough um and then i just kind of went for a lot of scenarios of um the thing that i focused on is the max milestone because i think different trend you could see this while i'm doing this live but if you have a lot of now let's just say you have 10 or something like that right well you know the easiest way is just to interleave them one at a time right so you could do one two three four five so this is a perfect interleaving and in that sense um you know that's how i get solu um if the max number is a certain way so from that i'm trying to figure okay how skewed can it be how uneven can it be right what if this was 15 and this is five well in this case i would start with the 15 and then do you know i prayed about a lot in my head um how to figure it out um and thinking about whether this would work in this case i was work so i thought to myself okay what if this was very skewed right and it just kind of is with one of the examples as well but let's say you have i don't know 40 10. well what does this mean that means that here well the optimal thing is just you know combine the rest of them say so now this is 20 and then here the optimal strategy would be to take the number that's more than half um interleave them and then add the last one for the big number for the last one so that's kind of my strategy about thinking about this um i don't know if this is a good strategy or when i submitted it to be honest i did not i mean i thought it was a good idea and i couldn't figure out a counter case i just spent some time trying to you know reason around it but when i couldn't i just kind of downloaded a little bit to be honest so um yeah and the way that i did it is actually and again because i did a sword but you actually don't need a sword you can actually let's do a linear uh to get the max and this thing would still be true so there's a linear time or one solution um i did it wrong and again because i sorted it but imagine you just have to max it and cover this instead um because as you can see i only use the max anyway everything else is a total so you can do this in linear time constant space um and the thing that i did was that okay if the biggest component is less than half a half or less then you can just do interleaving right because you can effectively combine all the you know you're going to leave in a way such that you get all every task done otherwise we do the thing where we get the total we subtract it from the max so this is basically um what we talked about right we combined the rest of the task into one mega task if you will and then you just interleave them two by two and then you add one for the big task if you want to go to that um to get this answer uh yeah so if you do it correctly this is gonna be linear time constant space let me know what you think let me know how you did uh maybe the different funky solutions um did you struggle did you do well let me know uh anyway you could watch me stop it live in the contest next and as a virtual contest i was more articulate than usual so let me know uh okay see ya i was trying to be too clever okay youtube say what end projects one of the milestones me one monster in one point let's work every week same project for every two consecutive week okay one maximum weeks okay this is a real problem uh let's see n is 10 to the fifth margin is 10 to the nine so we have to do something smarter um i feel like i've seen a variation of this problem i don't quite remember what the situation is so maybe that's a it's like a weird greedy i think but we'll actually put something like that every weekend i mean you can obviously just do i think dance is something funky like the biggest number times two or something like that um or the second biggest number maybe how does this get so this is three five this is okay is that all the edge cases so max is because you can always pair with volume or it's always optimal to pair the max so that means that is n over two so it's max and i'm trying to think about the odd number where it goes over by one so am i even right i don't even know this is such a weird greedy problem um so if there's exactly nine for five that's okay this is eleven five ten i guess that's okay two is that right is that true no i think that should be eleven then like we have five one or something like that you know if it's five one it should be eleven so i think that my math is a little bit wrong or even if i have something like 5 what's the answer here right the answer is not because my algorithm would be 10 but 11 is at least the answer it might not well this actually is 15 but this is a weird problem i don't know if i know i'll do this one just eh there's a lot of numbers though i mean some sort of greedy i'm trying to think what makes sense in terms of greedy well if it's a lot of ones or if it's not two so there's a lot of numbers so must have something to do with the max number right so the max number is more than half what happens if someone like this then is actually so if it's even it's good if it's distorted then it's at most uh max over one or something like that max times two plus one is the no if what is what am i thinking about like in this case what happens if it dominates and one number is bigger than half of them okay so if the number is less than half then you could do it for every number or the entire thing if it's one number is more than half then it's half is the uneven part the max is this right i feel like i'm like just guessing here to be honest let's do it um maybe a little bit yellow on this one uh so if the biggest number is bigger than half right so this times two is greater than total whatever is equal which equals still v total um okay so this is less than or you got the total then we return total otherwise then it is the total minus milestones minus one is this thing times two plus one maybe but i think i'm trying to justify the plus one well if it's more than half then you always start that one and then do the other one okay let's give it a yolo i actually don't know if this is right at all so uh let's at least make sure this is right okay what a weird problem uh yeah thanks for watching hit the like button hit the subscribe button join me on discord let me know what you think about this problem other problems whatever you need to do i'll see you later to stay good stay healthy take a mental health see you later bye
|
Maximum Number of Weeks for Which You Can Work
|
finding-mk-average
|
There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the `ith` project has.
You can work on the projects following these two rules:
* Every week, you will finish **exactly one** milestone of **one** project. You **must** work every week.
* You **cannot** work on two milestones from the same project for two **consecutive** weeks.
Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will **stop working**. Note that you may not be able to finish every project's milestones due to these constraints.
Return _the **maximum** number of weeks you would be able to work on the projects without violating the rules mentioned above_.
**Example 1:**
**Input:** milestones = \[1,2,3\]
**Output:** 6
**Explanation:** One possible scenario is:
- During the 1st week, you will work on a milestone of project 0.
- During the 2nd week, you will work on a milestone of project 2.
- During the 3rd week, you will work on a milestone of project 1.
- During the 4th week, you will work on a milestone of project 2.
- During the 5th week, you will work on a milestone of project 1.
- During the 6th week, you will work on a milestone of project 2.
The total number of weeks is 6.
**Example 2:**
**Input:** milestones = \[5,2,1\]
**Output:** 7
**Explanation:** One possible scenario is:
- During the 1st week, you will work on a milestone of project 0.
- During the 2nd week, you will work on a milestone of project 1.
- During the 3rd week, you will work on a milestone of project 0.
- During the 4th week, you will work on a milestone of project 1.
- During the 5th week, you will work on a milestone of project 0.
- During the 6th week, you will work on a milestone of project 2.
- During the 7th week, you will work on a milestone of project 0.
The total number of weeks is 7.
Note that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.
Thus, one milestone in project 0 will remain unfinished.
**Constraints:**
* `n == milestones.length`
* `1 <= n <= 105`
* `1 <= milestones[i] <= 109`
|
At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements.
|
Design,Queue,Heap (Priority Queue),Ordered Set
|
Hard
|
295,789,2207
|
92 |
hi guys welcome to tech geek so today we are back with daily lead code channels problem that's reverse linked list2 so this problem is elite code median level question and it's a record medium 92 now you guys have gone through the question that says reversing a linked list so it's kind of a modification to this where you have been added few constraints so if you know how to reverse a linked list then you can definitely go through it don't feel that you won't be able to do it just read the question think about how things could go on okay that's how you should approach a problem let's see what the question says that you have been given a head of a linked list that means uh you have a pointer that will point towards this head you have two integers now these two integers are left and right what does this left and right do now left and right very first just that left will always be less than or equal to right reverse the notes of the list from the position left to right and now see you have a link list okay and you have two values so in short what they want to say is uh they'll give you two integers in between those integers that means there would be a linked list to so you have to extract the sub link list and then reverse this linked list and join it again with this okay that's what they expecting you to do now let's see this question in a very good way okay let's see this is your linked list okay this goes from one to four and five okay so this is your linked list that's given to you now if in case you have to just uh reverse instead of doing this if you have to reverse the linked list there was some process that you followed right let's not contain anything that says that you have to go up with like left or right or anything is given you just know that you have a linked list and you have to reverse it right if you talk about this thing then what's the process that you'll follow the process that you will follow is some way equals to that you'll take a pointer you move it like this right or you will just try to make this as the next of this as this and then that's how you go up right there are various ways you can do it i'm not just specifying one but there are various ways you know how to approach this problem now what if you have been given a position okay now position is also not a pointer you have been given some numbers so first of all you need to find the value of this numbers you have to check until how much is it required so what you will do initially you will traverse this list you will check as soon as you get the starting point as you get as soon as you get a number that's equal to left start your counter until your value is equal to right okay so this counter will count all the values in between this linked list and as you have a counter what you have to do is you have to store these values in a list okay let's say we doing this it's quite messy okay initially the head was here or you can take some dummy one also it came at 2 right now increment your counter is now 1 and it will start in the list we'll add the list elements here unless we added 2 we moved the pointer here count became 2. add the value becomes 3 again come here check is it equals to right yes it's equal to right stop there itself that means add this increment this and now come out of this loop okay that's how you know would happen now we have two variables okay this was head and this was a dummy one going on now we know instead of this all and yeah before moving we'll move this pointer here itself now what you would do is from head instead of to start eliminating this opposite way until the counter is there okay so this index will be aware of that count of three so three minus one two so add this as a new node and next of this will again be a new node and two will now point towards the next of this one i hope this is clear now let's see how this question will go on simple traversal first of all uh until the value is less you'll add this elements or you can find directly the count of it now it's totally upon you which process you feel is easy for you okay then coming towards or traversing in the left direction you'll traverse until you get another link that means uh now for adding still first you'll traverse directly that means the same thing which we did here it was just one let's say we had one more so if we had one mode we'll traverse until we reach the point here okay now until then add it up and now you will check for the list in the opposite direction extract and head dot next should point them and there should be one like there was head that's a result so there should be one pointer that will point towards so this is basically an easy one and if you ask what's the time complexity so it's just order of n because you're traversing it and if you ask the space complexity as you're storing these elements so it would be order of k okay so k or you can even say it as order of k okay that's how the problem would be solved now if in case there's any query anything that's still pending out or anything that's not near to you do let me know in the comment box thank you
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
341 |
hey everyone this is side hope you're doing good so let's start with the question so the question is flatten nested list iterator so you are given a nested list of integer nested list each element is either an integer or a list okay so there is a nested list class that is given to you and in that so it's a interface so in that you have integer or a list whose element may be may also be integer or other list implement and iterate and to flatten it okay so you have to implement a nested iterator class so what it contains a constructor which initialize the iterator with the nested list then you have next function which is written the next integer in the nested list then you have has next or has next which basically return true if their element is present or not okay so it should be like this so this is the result so it will be calling like this while it dot has next if it returns true then you have to call the next function otherwise just written the result okay so let's understand with an example okay so we have to implement a nested iterator class in this we are passing a list of nested integer okay so as you can see this is a nested integer that is given to us so this is an interface and it contains two things one is integer another is list okay so if what we will what we can see by let's understand with this example so we have this one two one okay so if we start from here we have to give one okay then we'll move further so then we again have one so we will give one okay then we move further we come at this position then this is two so we give so as you can see there might be a integer and there might be a possible list also okay so we'll move further so first is like you have to complete the internal list then you have to go to the next element okay so we will complete this so this will be one and we'll move further so this is one okay so this is the final output that we have to give for this input okay let's see for this case so we will start from here we will give one then we'll move further and this is also a list so we'll give four then we'll move further then we'll give six and then this three bracket will complete and we got our final flattened list okay so this is that one so i hope the question is clear to you what we have to do now let's see how we have to implement it okay so if you can see what we are doing is every time like we will take initialize this list into some list okay then what we have to do we have to like if the current is a list let's say this is a list then you have to go deep dive in this list only okay so if you can see for this is a list then like this is the element you will just take it now after this is a list so first you have to complete this then you have to go inside this six okay so for this we need the recent element that is or you can say that the current element every time and we have to insert it so we can implement this question like iterator can be implemented by various method like q link list and stack there are other more but let's say we will implement true stack okay so we'll use a stack okay and our stack is of type of nested integer okay so let's take an example so this is the given one two one okay so what we will do at the time of constructor like at the time of this call we will initialize this nested integer list into a stack and how we will initialize we will start from the last okay so we will just take the element so if we give the indexing 0 1 2 we will just insert this because we are taking a nested integer type so we will take this 1 then we'll we come to this index we'll take this 2. then we'll come to this index we will just insert this one okay so this is our first step create or initialize stack okay then we have to give the implementation for next method and has next okay so let's give the implementation for first next method okay so what we will do for the next it will be like we'll call the next we will check if has next okay let's is it null if it is null then just written null else what you have to do you have to give the stack top element okay stack dot top and this is nested integer so we'll do integer also so get like this method we will call this method inside get in teacher okay so this is for next like it's pretty simple now let's see for the has next okay so how we will do it will be like okay so your hash next is it need to check whether your current top element if it is list then convert it into an integer okay so what we will do we will check so while we will check whether stack dot peak basically our top elements as you can see this is a list that we how can we check whether this is list or an integer we can check from these method actually these three methods are given to us so if it is an integer it will return true if it is not an integer it will written false okay so we will check it like is integer okay if it is false that means this is list what you have to do you have to take this list you basically have to pop this list so we'll pop this in the variable so we will pop stack dot pop dot its method name is get list okay so we will do get list and you will basically call your initialize function again initialize this list also okay so what it will do it will initialize from again from the last so this will take one as a list and this will start from here so it will be like one insert then it will be take one okay after this you just return finally if your stack is empty okay if your stack is empty you just return true otherwise it will return false okay so let's i hope the approach is clear to you let's so let's debug it so whenever that has next call so it will check whether has next is there or not so you can see the element is there and it will convert that list into again an integer so it will take the element and it will just do stack dot top so it will pop this and it will print one similarly when next call so it will pop one then again it will whenever next call it will again pop then whenever call was to this so it will check whether this is a list so you have to convert this list into an integer so it will be again a one and you again pop this so you will get one so this is the final output for our given input i hope the approach is clear to you so let's write it let's write the code for this so what we need a stack of nested integer okay so first step is to initialize our stack and we will call the finish let me initialize one sec and we'll pass this nested list to init okay so let's write the initialize function first so void initialize okay then you have to pass this nested in teacher list inside this nested integer your list so what you have to do you have to go from the last so for end eyes list dot size minus 1 i greater equal to 0 i minus and you will just do stack dot push list dot get off i so irrespective of whether it is integer or is it list you will insert everything in the stack so we have completed our constructor call so let's complete our next so we will check whether has next so if has next written true then you have to do something if it return false then you just have to return null because there is no element after this so if it is true you just have to do written your stack dot pop dot get in teacher okay so we have done with the next function also let's write the hash next so has next is just simple so you just need to check return it's like stack dot is empty okay so if your stack is empty just return true otherwise written for okay so if your stack is empty that means it will like your has next returns false so we will do the ampersand over so it will return the reverse of that now we need to check whether our stack is not empty and your current like a top element in the stack is it's like stack dot peak is list okay so get uh what's a function name is integer okay is integer if it is in if it is not integer do something so what we will do we will of this list store stack dot pop and we will just pass it to our function okay i think we have updated that code so let's run it okay let's see if it submit or not yeah this is accepted let's submit it so yeah our question is submitted and our streak is also start from again so the time complexity is like what you are doing is every time you are in first step you insert all the element into a stack and whenever there is a list you will convert that into a stack into a integer so if you go with the time opposite its order of n and for the space we are using extra space for the implementation so that's also an order of and hope you like it thank you for watching video and do join the telegram group if you're in doubt any concern thank you
|
Flatten Nested List Iterator
|
flatten-nested-list-iterator
|
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the `NestedIterator` class:
* `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`.
* `int next()` Returns the next integer in the nested list.
* `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = \[\]
while iterator.hasNext()
append iterator.next() to the end of res
return res
If `res` matches the expected flattened list, then your code will be judged as correct.
**Example 1:**
**Input:** nestedList = \[\[1,1\],2,\[1,1\]\]
**Output:** \[1,1,2,1,1\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\].
**Example 2:**
**Input:** nestedList = \[1,\[4,\[6\]\]\]
**Output:** \[1,4,6\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\].
**Constraints:**
* `1 <= nestedList.length <= 500`
* The values of the integers in the nested list is in the range `[-106, 106]`.
| null |
Stack,Tree,Depth-First Search,Design,Queue,Iterator
|
Medium
|
251,281,385,565
|
90 |
hi everyone welcome back to lead coding so in the last video we solved the question subsets if you haven't watched that video make sure to watch it now we are moving to another problem that is subsets 2. now in this problem there is just a slight difference we are given duplicates in the previous problem we were not given duplicates now we will see what problem arises if we have duplicates for that we will take an example so the example i am taking here is one two now i will try to find out all these subsets of this using the same algorithm that we used in the subset problem okay so that's why uh you should watch that video and you should know how did we find the subsets of a given string or a given vector using backtracking and recursion all right so we will go to each number and for each number we will have two options the first option is to take that number into consideration and the second option is to ignore it okay so first we are on the number one for this i have two options i can either take it or i can ignore it so first i am ignoring it so this is uh my set this is one of myself it is empty because initially it was empty now also it is empty because i ignored one what i am left with is 2. i will be left with 2 n2 okay and if i take 1 then in the set 1 will come and the numbers which are remaining are 2. okay now again for the number two the first two at the index one we again have two options so here we have two options the first option is to take two uh and the second option is to ignore two first of all we are ignoring it so in this set we are not going to include anything and the number which is left is the last two and here we are taking it so the set was empty now we are taking two here and we are left with the last two here also we have two options the first option is to uh ignore this two so we ignore this one is there in the set and one will remain we are left with the last two and here we are taking these two so one and two will come into the set one was already there right so that's why one and two will already come into the set and two will be left now for this one again we have two options first is to ignore the ignore this two if we ignore this the set is empty if we take this 2 will come into the set and nothing will be left because we reached till the end of the array now here also we have two options the first one is to take ignore this so we ignore this only 2 will be there in the set this is the set only 2 will be there and if we take it then 2 will come into the set here also we have two options one is already there so if we ignore this two one will be left if we take this two one and two will come into the set again we reach till the end so nothing will be left here also we have two options the first is to ignore this two so if we ignore this we already have one two into this set and if we take this then one two okay so we were able to generate all the eight subsets right one two three four five six seven and eight now the problem because of these duplicates is we will be having some duplicate subsets as well now where are those subsets can you locate them so here we can see we have one two and here again we have one two this is duplicate here we have two and here again we have two this is another duplicate we don't want to include these duplicates it is given in the question the solution must not contain duplicate subsets return the solution in any order now uh see we can see here one two three four five six only six subsets are there only six unique subsets are there so we don't have to include the duplicates here otherwise if we were allowed to have the duplicates we would have used the same algorithm but now we need to make slight changes in that algorithm that we used to find the subsets in the previous video in the previous problem we have to just change it slightly so that we can just ignore these duplicates okay so uh let me just erase it and then try to see that how we can do that i'm just deleting the last level here so let's first consider this part so the important thing is if we are ignoring this two we should also ignore the next two because both these elements are same so if we are ignoring this we should also ignore this okay so let me just try to demonstrate what i mean basically here if we go to the left hand side we are ignoring this particular two so in the next step we will only have one choice that is to ignore these two as well so if we do that we will have an empty set and we won't have the two that we are having previously okay we were having these two sets but we won't be having this why so because we came to this side if we ignored this particular two right if we ignored this particular two then we came to the left hand side and because we ignored this two we should also ignored this two because they both are same in value that's what we have to keep in mind so we will not have this choice of taking this particular two we will only have a choice to ignore this and we will only have this empty set okay next so if we take this 2 if we are taking this 2 and going to the right hand side here we are picking this 2 and we are going to the right hand side then we will have again 2 options the first option is to ignore these two or to take it okay so if we ignore it we will be having two and if we take it we will be having two and two okay so we only have to keep in mind that if we are ignoring a value if you let us say if we are ignoring this particular two if you are ignoring this value we should also ignore all the values that are equal to this we should also ignore all the tools which are coming in future all right now we will see how we will how we are going to code this efficiently but just wait for that let me just uh try to make it more clear with the help of examples now here again we can see there are duplicates so let me just get rid of these levels as well so we came here so basically we came here to the left hand side if we ignored these two okay now as we ignore this two we should also ignore the next two so we will not be allowed to go to the right hand side by picking up this two okay because we will have to ignore this two as well using the same logic so just getting rid of this we won't be having one and two here only one will be there and the only op because the only option is to ignore these two so that's why okay and we came to the right hand side by picking up these two and if we pick up these two we will have two options for the next two as well we will we can either pick it or ignore it so here we have two options either to ignore it or to pick it so here we can see we will be having only unique subsets at the end one two three four five and six unique subsets and that's what we need so the only thing that we need to keep in mind is if we ignore x is an element if we ignore x we ignore or we should ignore all x okay so this is what we need to keep in mind and if we pick x like if we consider x into this set then for the next x the same value we will have options to at the pick it or to ignore it but if we ignore it we should ignore all the x's now this will be more clear with the help of the code obviously in the code i will tell you how to do this so one of the best way is to just sort the given array okay so if we start to give an array let's say um if we sort it one two three it will be much easy to compare uh the x's all the same values right it will be much easier to compare the same values we can just compare it with the previous value right so by sorting it becomes very easy to compare that if the last value was same or not okay now let us say we are here at this 2 then we will see what is the last value if the last value is same as this then we will see if we picked the last value or not so in case we are ignoring the last value we should also ignore this value which is same as the last value all right so nothing is different from the subset problem that's why i'm just copying the same code here copying the same code and then i will just slightly change it so here we have the exact same code but name of the function is different that is i'm just copying this and pasting it over here and deleting the function name now this is the exact same code and let me just run this so that it is clear that this is the same code see we are getting the correct answer but with the duplicates now we have to ignore this duplicates okay so for that the first thing that i told is to sort the given array i'm just sorting the given array num start begin num start and after this sort all the elements with the same value will come together so these values will come together and it will be much simpler to just check them we can just check the current value with the previous value if it is same okay so if nums of i if it is equal to the previous value there is nums of i minus 1 now before checking this condition i should make sure that i is within the boundaries so i should be greater than 0 okay that is then only we will be able to compare with i minus 1 if i is equal to 0 in that case i minus 1 will not exist and it will give me an error that error is segmentation fault all right so if both the values are same if the current value is same as the previous value in that case i will see if i have ignored the previous value okay if i have ignored the previous value i should ignore this value as well by ignoring i means i will not consider it into the set so here we were taking two decisions the first decision was to take x take the ith element the second decision was to ignore the eighth element so if we have ignored the previous element which is same as the current element we should ignore this element as well okay we will not consider it okay for that i will keep a variable in that variable i will mark if i have picked up the previous element or not okay so let me name that variable as previous now this previous variable it could be a boolean variable so if i picked up the previous element i will mark it as 1 or true if i didn't pick up the previous element i will mark it as false if i ignore the previous element this value will be false so if it is not i am just making the note of it so if i ignore the previous element i should ignore this value as well so if this is the case i don't have an option to take the ith element so how to do this like i have to take the note of this whole expression and then put it inside it then so that i can just ignore executing this code of selecting the ith element right instead of doing that what you can do is i can just bring this up i can always ignore this and if this is the case i can just return after ignoring this element right and if it is not the case i can just consider this element and then move forward now as i include one more parameter previous so let me just make previous here in previous or let me just make it a boolean type okay bool previous so this previous we will denote that whether i have picked up the previous element or not so here if i ignore this element this will become false and if i picked up this element this will become true so in those cases in which i have not picked up the current element and if the next element is same as the current element i will just ignore it and then return from here i will not consider it and go ahead okay i hope it is clear now from here also i will just pass it as false let me just try to run this i hope there are no compilation errors yes it is giving us correct answer let me just submit it now all right it got accepted now once again this is 2 raised to the power n this is exponential time solution and it is taking of course exponential space in the worst case it might be possible that all the elements are unique in that case i will end up making 2 raised to the power n number of sets so the space complexity in the worst case is also 2 raised to the power n exponential okay so this was a pretty simple straightforward solution you just have to know the solution to the subset problem that we have covered in the previous video if you haven't watched that make sure to watch it and make sure to subscribe to the channel and press the bell icon if you want more such content in future and please leave your likes and your suggestions and your comments down below
|
Subsets II
|
subsets-ii
|
Given an integer array `nums` that may contain duplicates, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,2\]
**Output:** \[\[\],\[1\],\[1,2\],\[1,2,2\],\[2\],\[2,2\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
78,2109
|
338 |
Hello Hi Guys Welcome To Algorithm Smart Easy Will Go Through 3028 Problem Middling Challenge Give No Negative Interior Number No For Every Number 102 Calculate Number Of Representation And Toys Example Of Representation Of Numbers From 200 To Hai Here Multiple Ways You Can Solve This Problem Will Go Through each of them in detail in the video who is the first method is by using sperm count in this will repeatedly flip blast significance debit the faster 12081 to the number 1091 how to calculate the top card will follow these steps will cost initial is variable account Fiji phone will start with number and look forward till the victims get phone this time will prevent account and updates number with and operations with its previous number and comes and minus one play list sunni hai to initially will have account zero-valued to initially will have account zero-valued to initially will have account zero-valued one number gets reduced 201 Performed End Operation Will Initially Calculate The End Of 765 Increment Account The Result Of The Nation Comes Out With Six Vacancy This Flip Blast One With And 720 Again Will Perform Depend 6 And Fight Half Hour To End Comes For Continuing For Android Free Games Free Number Put the number 90 that on reaching here the time complexity of the algorithm add it to the number of solution number of birth number 10 complexity of the algorithm plus news channel subscribe button 2012 form number with example a mathematical e.t. On Facts Can Be a mathematical e.t. On Facts Can Be a mathematical e.t. On Facts Can Be Represented S P F X And A piya 353 and two plus 12222 plus one will tire after 2nd year they will update you breaking this system is the tree-plant method is breaking this system is the tree-plant method is breaking this system is the tree-plant method is this race third is dp plus most significant but unlike the lancet fifth walking with the most significant this time is the The name of the one that captures the look of the representation of and is adding one to the most requested for minor representation of phone similar if it I want the significance of the representation of different just one removed from the number one number for removing 140 phone numbers seven Number Three Do Subscribe To E Waited For The P Afsari Begum Pure One Plus Two Which Is Pet One Plus One And Pious 1020 Plus 90 Representation Of What We Can Be Expressed Subscribe Now To Receive New Updates Breaking This System The Trees Method Is A Moving Onto the 4th propose day test dp plus liquid surya will apply vpn list previous bittu final acid number to the number two elements in detail a specific seven daily significant battery total 2712 test one effect one week number 13 inches diner representation of 100 number one is phone Number 738 Representation Friendship 751 Actress Divya For Next Generation Will Get Liquid Plus Liquid Discuss One Number Opposite Directions Will Be Reduced To Function 1200 Acid And Previous Approach S2 Time Data Past In Which Is The Answer For The Number 7 To 80 Mathematically Two To to all so much thanks for watching video please like share and subscribe channel for more videos in interview problems video all video problem statement comment it
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
1,620 |
A Hello Everyone Welcome To Record Programming Roaming Open According To Police Problems From The Relationship Between Promise Day 6 Minutes Less Quantity Lucknow 209 Most Used And You Will Also Be Given Credit Meeting Comet Person Mission Incomplete 500 1000 Death Tower This Controversy December Edison Katori Notice Milne Aungi One Point and Political Leadership Quality Factor Late Formula Quite Effective One Plus Distance from This Point Where Political Party Ki and Later Quality at Klug Colgate If Possible All the Best From This Point Sukh Sampit Only for Drawing from This Point to That Point You for the end of the day and hear fire into final quality are defined network aa 200 unit collector rate possible point se z pen more quality at this point e find no quality in ki handi then air multiple congress member network quality this the smallest reckoned 16 Geography Mirwaiz Father Went to Express and According to take every point undertaker be our country till such fault point 100 grams the point by taking distance from the ministers and quality of all the best quality is duplex you take first ever saw you the destroyer of the distance from this point to all the best Person Quality And Quantity Not Quality And The Mid Point Of This Serum Quality General Class 5 Chapter Obscene Kushwaha No You Find Us On So Let's Go To School And Check Out And Other Drugs Addiction 992 Serum What We Have Taken Against Registration End Subscribe Best Quality Never Seen On School Roof Fruit Of Solitaire Patlu Pinpoint Birth Query Parameter Show August Current Works Of Quality Of Points Born On 244 A Man Arab Unit One Thing That You Need To Be A Member Is The Distance Karungi Hai Protein point accept rotting hormone up to hundred units double no entry sudhir with contact that loot vikas giri computer's distance of speculation subscribe that force friend stop accept center depend eastern railway station hospital to z current is tomorrow morning rent in quality apps side To the journey to the point has developed number of auspicious someone else has been the quality signal quality pimple try is the best place for more than love updated on that and lag problem kishan dehat told you want and run luta do you want to Listen to the best friend Who is I fell asleep Natya Senior School In-charge I fell asleep Natya Senior School In-charge I fell asleep Natya Senior School In-charge Principal The content is half popular Saurav Thank you for watching Place to provide feedback Thank you
|
Coordinate With Maximum Network Quality
|
check-if-array-pairs-are-divisible-by-k
|
You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**.
You are also given an integer `radius` where a tower is **reachable** if the distance is **less than or equal to** `radius`. Outside that distance, the signal becomes garbled, and the tower is **not reachable**.
The signal quality of the `ith` tower at a coordinate `(x, y)` is calculated with the formula `⌊qi / (1 + d)⌋`, where `d` is the distance between the tower and the coordinate. The **network quality** at a coordinate is the sum of the signal qualities from all the **reachable** towers.
Return _the array_ `[cx, cy]` _representing the **integral** coordinate_ `(cx, cy)` _where the **network quality** is maximum. If there are multiple coordinates with the same **network quality**, return the lexicographically minimum **non-negative** coordinate._
**Note:**
* A coordinate `(x1, y1)` is lexicographically smaller than `(x2, y2)` if either:
* `x1 < x2`, or
* `x1 == x2` and `y1 < y2`.
* `⌊val⌋` is the greatest integer less than or equal to `val` (the floor function).
**Example 1:**
**Input:** towers = \[\[1,2,5\],\[2,1,7\],\[3,1,9\]\], radius = 2
**Output:** \[2,1\]
**Explanation:** At coordinate (2, 1) the total quality is 13.
- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7
- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2
- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4
No other coordinate has a higher network quality.
**Example 2:**
**Input:** towers = \[\[23,11,21\]\], radius = 9
**Output:** \[23,11\]
**Explanation:** Since there is only one tower, the network quality is highest right at the tower's location.
**Example 3:**
**Input:** towers = \[\[1,2,13\],\[2,1,7\],\[0,1,9\]\], radius = 2
**Output:** \[1,2\]
**Explanation:** Coordinate (1, 2) has the highest network quality.
**Constraints:**
* `1 <= towers.length <= 50`
* `towers[i].length == 3`
* `0 <= xi, yi, qi <= 50`
* `1 <= radius <= 50`
|
Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0
|
Array,Hash Table,Counting
|
Medium
|
2301
|
449 |
Sohe gas is 70 third day today serial is in dc release binary search history so let's move on to that question and before that let me tell you one thing that there is also a question called serial agent dc release binary search tree on let code. So this will be done automatically, meaning binary, it is a type of binary tree which has a specific property that the numbers will always be small on the left side and will always be big on the right side, otherwise we will apply a separate algorithm for this, so before that let me tell you. That if you do that then the binary question will be more clear and you will understand what this serial means. Here you have to make a string in advance, after that let's first understand it on the notebook that the question is. So this is the 73rd problem and we are almost going to have this question and there is only one BT, there is a difference in it, okay, what is the difference, you understand that and if you are not doing civilization then understand that also, it is okay, once it will be more helpful, okay. So, if we make buy entry in it, then it will be sorted, then you will understand easily. Okay, let us take a binary surgery 53714. Okay, so how will we make it? Five above, after that, free and seven, the way we made it. If we do, then now there are different methods We will have to go backward, forward left, what is the version of this, so if we have to make it, ultimately, we have made it serial like this, how we will make it, this is what we have to understand, what is the technology. This is ours, what is your mood, what is the root, here too there is a root, this is the first root, so the root is taken, after that what is three, what will come on the left, what does it mean in binary, that small ones remain on the left side. What happens on the right side? When they become big, then three Han's smaller than 5 are placed on the left side, that is, one smaller than three is placed on the left side. If it is small, then it is okay. We will place it here. So, it is set. I mean, how do some things get passed, it is the same, I will tell you now, if there is such a case that 200 seven punches have to be put here, then you will say, let's put it here, how can it be neither on the right side, sorry. On the right side there are big numbers, on the left side there are small numbers, so eight is bigger than 5, but here all of them should be small. If we increase it by 7, then Han Bhai, this thing is correct, that is why we will come here, okay, understand. So I have to see this and then we do the code, its binary search tree, let's open it, everything seems to be open, everything is done, including submission etc., it is everything seems to be open, everything is done, including submission etc., it is everything seems to be open, everything is done, including submission etc., it is happening successfully, actually in this we have serialized this. It is easy to do, we have given you binary, it is in a string form, I named answer, look at answer, took an empty list and DFS, we created a function inside note, if we have an empty node i.e. there is no note then empty node i.e. there is no note then empty node i.e. there is no note then return nothing. And if there is something then append it is fine in spring form and for how long we have to do this, that is, we have to do it from the left side as well, we have to do it from the right side also, by doing this, we will call this function with the root value. Note value and whatever gets appended will be added to the list. If it is with com then this is done. Our serial is so clear in string form. This was easy. This is the tricky part if you see here I have written if note returns data because what if. When I was running it, a case was being added like this example, there is an empty list in it, so is there any benefit in making the empty wait, is there anything in it, so if it is not there, then return on. If there are two characters then make it wait for data, so for this data dot plate, we divided it from Kama because I had joined from com only, so after plateting it, extracted the data and taught the answer in list form, ok now. This part is easy to see, if you understand, then we have defined DFS, the answer will be inside it because our answer will come between lower and upper, otherwise we will update it later, that is a different thing, so if our answer is not in our list. So turn on return. Even if our answer is not in between these two, turn on return. It will definitely come in between. It is ok. Say any number - between. It is ok. Say any number - between. It is ok. Say any number - Infinity plus remains in between infinity. Is it not initially? How do the changes happen after that? We have popped from the answer to get a note. The first one is fine, so our open one looks like this, we can also butter it. We had noted root equal to tree. This is what we have made above in trainod. We are going to make it in the class. So what is the initial, which will be our root, that trignod will be zero. Now we have to do this for the left and run it for the right, so what are all the values in general in the left, if it is run it for the right, so what are all the values in general in the left, if it is run it for the right, so what are all the values in general in the left, if it is small, then we kept the lower bond the same and routed the apart. We kept the value, whatever the value was, it will keep changing and for the right we ran DFS and left the list the same as aparbound, we kept the value of root, sorry lower bound, we kept the value of root, but now we kept the bound as aparbound, okay Because we want to read the answer, if the big answer comes on the right side then our maximum was initially, it means we will have to change the lower one, so this technique was just small and we will return the root, so our Binary output will be A, rest you can check the binary tree also, okay let's go.
|
Serialize and Deserialize BST
|
serialize-and-deserialize-bst
|
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a **binary search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
**The encoded string should be as compact as possible.**
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The input tree is **guaranteed** to be a binary search tree.
| null |
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Search Tree,Binary Tree
|
Medium
|
297,652,765
|
87 |
Hey everyone, today we will be given a string S which is given here as S1, okay you get a string, okay and we have to make it equal using the following algorithm, here we have been given some algorithm, okay first. So if the length of d string is one stop means here then they said if the length of the string becomes one then stop here second if the length of d string is greater than one then if the length of the string is more than one then Something else has to be reduced and what has to be done here is split de string and nine in tu non empty substance. Now the string given to us is rakhi na uso two non empty substances we have to split aate un random index is any random index. date is if d string is s if string means man lo this is my string ok now it is my right now I have to split it into two springs so see I have looked at the string carefully that this is my string I have separated it And A T was taken out separately, okay and this is the divided part, right, man, this is the The line here is given to us in the question, okay, random decide, you swap D, you substance, you keep dem in D, now the order is there, what you have to do is, neither are these two substances, these are X and A, either means these. So I don't have to swap, okay now if you swap, that means either you don't swap it, then how will S remain like this and if you swap, what will S become? A + what will S become? A + Why do we have to swap this string here, we have to bring it equal to S2, so look, this is our R G A T, this is our S tu string, okay and this is our string, so when If I swap them with each other, then this string will become equal to S2. It will definitely become so. So both of these means, overall you do not have to do anything. It is okay to tell whether this string is becoming equal to S2 by swapping or not. is apply step one recursively on H of D tu substance and by given D tu string S1 and S2 of D se length dekho here pe se length ki string de rakhi hai return true if S2 it is sorted string of S1 means swiping S1 if If it is equal to S2, then true answer has to be returned otherwise false, then it is our problem because it is our problem. Now let us understand it a little more, so see here, this is ours, this is what we have given, this is ours. Let me write an example here, okay, now here I have split this string from this point to this point, what have I done from this point, if I split this further, then what will happen, yes, this will happen, this will become ours. Now look, if this is my string That is, if D length of D string is this one stop is okay then here also I make it like this and I make it in this way of course now it is okay to see here about if I split this then what will happen A will happen Its length is van, hence I cannot split it further. If I make this and this into a T, then what will it become? I have said that if my s.length is equal to equal van then stop it s.length is equal to equal van then stop it s.length is equal to equal van then stop it means here at this end place then we do not have to do any operation at all. If these inches then we do not have to do any operation. Now see this carefully, observe this one. Like a trick, it's okay, this is our tree and this is also our free one, okay, those on which I have put a circle, this is ours, this is the leaf mode, this is ours, so now I tell you here that whatever non-leaf note Right, go there and swipe both her and her kids, I am saying, go there and swipe both her kids, okay, so I am here on IGR, okay and what have I done here, I have done this. I have swapped it, so now how will it become, look carefully, it will become our rug, it will definitely become RJ and we had not done anything on it, so it will remain like this and what will become of the string? When the edge becomes 80, then see this S1, when we swapped the two children of this nonlif node, then this S1 became equal to ours, became equal to h2, became equal to S2, okay, so this is what happened here now. Let me tell you the opposite, this is what S2 is, look here we have to make S1 equal to S2, so either you make S1 equal to S2 or you make S2 equal to S1, it is only one thing. So I make S2 equal to S1, it is only one thing. So I make S2 equal to S1, it is only one thing. So I told you that this is S2, okay, go to its non- told you that this is S2, okay, go to its non- told you that this is S2, okay, go to its non- leaf note and these two means go to its non-leaf note and go to its non-leaf note and go to its non-leaf note and swipe whatever childhood it has, then what will happen, this is R Ban. So how will it become GR? And what will happen here if it still becomes equal to S2 S1? Even then what is the answer? Okay, so now the point here is that whether we Will we swipe the non-lif note? Will we swipe whether we Will we swipe the non-lif note? Will we swipe whether we Will we swipe the non-lif note? Will we swipe all the non-lif nodes? This is all the non-lif nodes? This is all the non-lif nodes? This is not the case. Here you will say that if you swipe only the non-lif Here you will say that if you swipe only the non-lif Here you will say that if you swipe only the non-lif node, then you have got it done, but we will do it. We will not swipe it because look, if I swipe this non-life node, it will swipe this non-life node, it will swipe this non-life node, it will never be equal to it. Okay, so we will not swipe all the non-life fluid, so we will not swipe all the non-life fluid, so we will not swipe all the non-life fluid, it is given here, not either our X + A. Yes or our either our X + A. Yes or our either our X + A. Yes or our y + y + What do people do? Okay, now I say, where can we make cuts here? Look, if I am writing their index, then where can I make cuts here? If you can make cuts here, then how can you do it differently? Write done ok otherwise I can cut here then write GR separately and AAT separately otherwise I can cut here then write GRI separately write AAT separately otherwise I will cut Where can I put it here, so how can we write it? We write GRIA together and write T separately. Okay, we can make it in this way. Similarly, in this string also, we write it in these four positions. If cuts can be made, how many total cuts are being made? Look, see the position of the cuts. Van tu three four, whatever is the length of our string, the length of the string is 5, it is being made till one before that, so many cuts are being made, it seems to be fine. So in the same way we will cut and see whether our string has been swapped or not. Okay, so now let's see, in this question we will do actual stopping. No, its concept is a little different. They have said to swap. You think that we will swap, meaning of course not by writing that swap function, this will not happen. Now see, I made a cut here, so how much have I made of it, made it like this and in this too, I made a cut here, okay, these two trees have become ours. Okay here, we have made the cut here. Now I am telling you here that we have two choices. How many choices do we have? There are two choices. Don't do the first choice. Okay, I am naming them. I am making the cut, right? I have made a cut here, so if I name it left, I name it right, then it is okay, then left and whatever is right, meaning when the self is not there, then the left part will be equal to the left, meaning whatever left part of this train. That will be equal to the left part of this train and the right part of this train will be equal to the right part of this drink because we have not done vaping here. Okay, so now I went to the left of this. So how many trains do I have and also where did I go left means where did I break the string from where to where I took S van from zero to K ok and also took S2 from zero to K We are okay, we are talking about the left part, so that much has been taken, now I ask here, now see S1, what is my GRA, okay, the length of S1 and the length of S2 are equal, so will you say that it is equal? So it is, then I said, okay, it's a good thing, now look ahead, is S1 equal to S, is it not at all, still at this point, S1 is not equal to our S2, okay, so I tell you, let's split it, who knows further? And if we get equal after splitting, I split it further, now look what is our length, here is our length, so is our van and what is our S1, S van is G and So Our equal equals, you have not come and here both our lengths are also not equal. Look, we have not got equal from the left. See how the stream is getting split. From the right string to the length of the string, how is it getting split? Till what length of the string is it being split, this is our right string being split, GK is equal, it does not happen at all, okay, so what have we got from here too, we have got false, now look, left hand right, what will I do here. I will do left and right because look friend, if I have to make S1 equal to S2, then its left right part should be equal to its left right part, that means when both the values are true then only then our answer will be true, so values are true then only then our answer will be true, so values are true then only then our answer will be true, so now see when we have So we mean, when I took Gar and Rag, okay, considered it as S1 and considered it as S2 and put the choice of no swap for them, that is, we put the choice of no swap, that is, we do not swipe it, then what did we get, the falls came, so now we choice. You will see that it is okay when I noted, I mean when I did not swipe both the strings, when I did not swipe the string, then my answer is false, so I will tell you once I taste it, okay, so now pay attention. So see, when I swap and S1 is made up of my left and right, then when I have done the swap, then whatever is on the left of S1 will be equal to the right of S2. Of course, the left will be equal to the right of S2. You should see, if I have this now and this is okay, I am calling it left right, so this is S1, this is S2, so what is the left of S1 equal to, what is the right of S2 equal to and S1 Whose right is equal to, whose left is equal to, only then swipes will happen, okay, so we will check like this, so now we have this gar, okay, and this is what I have: What is S1, what is I have: What is S1, what is I have: What is S1, what is GR, what is S2? I have RG. Okay, so now let's see how the left side of S1 will come. The left side of S1 will be our zero to Whatever length we have, length means whatever total length we have, now you will understand well that whatever length we have, remove the cake from that amount and take the rest, see how much length we have here in this entire string. Where are you, where are ours, we have put it on our van, we have put it on 2 - 1, so from van to you, from van to 2, it means that there will be only this much string, if you take that many, then how much S1 has gone, S1, then my dear. A went and look S you B is mine G A is S you B is mine What is A G A means the left side of S1 is satisfied, our condition is satisfied that the left side of S1 is equal to the right side of S2. It is exactly right. Now the second thing we check is whether the right of This much will come from S, and how far will its left come? Left of S2, this is what we are saying right and this is what we are saying is left of S2, so this will go from zero to K. Okay, if it will come from zero to K, then this is Both are equal to each other, meaning our second condition is also satisfied that the left one is equal to the right one and the right one is equal to the left one. So what answer has come from both sides in the swap? We have got true. Okay, so when I have There are so many S1 and so many S2, so I came to know that when I swapped the S van, then my one became equal to this van, S became equal to yours. Okay, so what came from here, there are four things which need to be kept in mind. Firstly choose do it or don't swap ok second there will be star operation this is the biggest concept of our problem ok now the third important thing is S1 should be left in the swapped one ok and what is happening in no swap Whatever is the length of our string, it will be one less than that, this is how much our splitting will happen, so these four things are points, they are very important to solve this question, very important, okay, now let us look at its code. Before seeing the court, there is one thing in this problem that here our string is getting split, so the problem will be repeated but because our string is getting split, our string is changing in every step. Both of our strings are changing, okay, so what will happen here, both our S1 and S2 are changing, so here we will map it, whose income will be of bull type, okay Now look, now my house. We will shrink the length of both, okay otherwise what will we do, we will call a function for S1 and drink upper for S2, I have created a pay key here, okay and in it I will store all the values, okay now we are here. But if we cut what to put, where will they be from, I will also take our length, okay, I have taken this S1 dot length, okay, earn A+, okay, earn A+, okay, earn A+, okay, now I made a mistake here Answer = Now see, here I will keep 24 vanes, okay So look carefully here, I will call the function, then it will go to the left, so it will go to the left, see, now see, the right remaining part of our string, so from where will it go, how will it go to whatever length we have and so on. Next, to me, what has become of us, it has become our choice It has become our swap and in this S1 is on the left, whose equal should it come, on the right of S2 and whatever is on the right of S1 from zero to K, from here Whatever length we had, what did we do, we took out the length from K to the length, so it will be done till here, okay, so this is what happened, our right is done, now let's see what else should happen, together it will become our left, okay now. The answer and choice of the same thing because what to do is okay otherwise what can happen that what do we do from here in our S1 Whatever map is there in ours because we are searching for it and if we find it in the map then we will search for it again. Will solve it a little or wo n't solve it at all. If I change its order further, see if it is RGIAT then I would have made it ATI, then let's see the answer. We are ready for this also. Here you will get the concept clear if you watch the video. If you liked it, please like, share and subscribe the channel. Thank you so much.
|
Scramble String
|
scramble-string
|
We can scramble a string s to get a string t using the following algorithm:
1. If the length of the string is 1, stop.
2. If the length of the string is > 1, do the following:
* Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and `y` where `s = x + y`.
* **Randomly** decide to swap the two substrings or to keep them in the same order. i.e., after this step, `s` may become `s = x + y` or `s = y + x`.
* Apply step 1 recursively on each of the two substrings `x` and `y`.
Given two strings `s1` and `s2` of **the same length**, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`.
**Example 1:**
**Input:** s1 = "great ", s2 = "rgeat "
**Output:** true
**Explanation:** One possible scenario applied on s1 is:
"great " --> "gr/eat " // divide at random index.
"gr/eat " --> "gr/eat " // random decision is not to swap the two substrings and keep them in order.
"gr/eat " --> "g/r / e/at " // apply the same algorithm recursively on both substrings. divide at random index each of them.
"g/r / e/at " --> "r/g / e/at " // random decision was to swap the first substring and to keep the second substring in the same order.
"r/g / e/at " --> "r/g / e/ a/t " // again apply the algorithm recursively, divide "at " to "a/t ".
"r/g / e/ a/t " --> "r/g / e/ a/t " // random decision is to keep both substrings in the same order.
The algorithm stops now, and the result string is "rgeat " which is s2.
As one possible scenario led s1 to be scrambled to s2, we return true.
**Example 2:**
**Input:** s1 = "abcde ", s2 = "caebd "
**Output:** false
**Example 3:**
**Input:** s1 = "a ", s2 = "a "
**Output:** true
**Constraints:**
* `s1.length == s2.length`
* `1 <= s1.length <= 30`
* `s1` and `s2` consist of lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
| null |
700 |
Hello hello guys welcome back to tech to join this video will see how to search and key given in this poetry which is also known as best solar system code 15th june channel lotus no problem give way to find the se request to search for key three idiot Problem of Thursday Subscribe Now Latest Research From This Point To That Is Not Yours Will Not Be Able To Find The Channel Subscribe Statement Solution Trapped The Property Of The Day Jindal Factory Should Be Let The Giver Not Fair And Always In The Center Should Be Greater Than The Value Five 14 A Property Tasty Advice Pet's Values In Subscribe Sudhir And subscribe The Channel subscribe to the Page if you liked The Video then subscribe to the Page if you liked The That I Must Know In It's A Tree In Its History The Valley Between The Range Of Minimum To The Way Shrill Subscribe And Property Widows Property Subscribe And Subscribe This Is Not Here 5317 Property notes1 Chut Pauline Grain Jab Photo Forward Undervalued Members Tasty Assigned One To The property of Tasty so let's not look at the forum well in this algorithm where giver BSP and they request you so much for that 16 2012 247 subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page that is Basically letter this point sorry for his present must be present in the writer of the woman es will make a doll now no hero is not for you can see the he is equal and so will return the point to 40 only one who will be written letters from This Is The Will Not Doing So Will Not Be Able To Know Who Will Certainly Not Know What Is The Time Complexity Log In Celebs Like Subscribe And Go To Order Woman Because You Can Have Elements In Ascending Order And Elements In Descending Order Which Will Create After Acute Renal OK So Sachin Scooter Is Nothing But A Linear Search Swadeshi Central Government Is Open Today Latest Not Look At The Code Shown In This Code Were Give The Root Of The Tree And Observe Every Twist Noida Current Point Appoint Into The Room And Simply Apply Aloo Which Will Search For Given And Will Not For The Time Complexity Of This Will Not The Statement Subscribe Thank You Are Not Able To Find The Value Of Karo Hu Is The Current Will Be Point Mintu And Null Value Assigned Bandh Samiti Vighn Solution In Different Languages Subscribe Like Share Different Languages Subscribe Like Share Different Languages Subscribe Like Share and Subscribe
|
Search in a Binary Search Tree
|
search-in-a-binary-search-tree
|
You are given the `root` of a binary search tree (BST) and an integer `val`.
Find the node in the BST that the node's value equals `val` and return the subtree rooted with that node. If such a node does not exist, return `null`.
**Example 1:**
**Input:** root = \[4,2,7,1,3\], val = 2
**Output:** \[2,1,3\]
**Example 2:**
**Input:** root = \[4,2,7,1,3\], val = 5
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5000]`.
* `1 <= Node.val <= 107`
* `root` is a binary search tree.
* `1 <= val <= 107`
| null | null |
Easy
| null |
1,996 |
That today be loot number to complain problem you are play and director attend Bluetooth come attack I think so this problem is that China chapter's trick or and properties any festival about China that were attended qualification graduation half hour subscribe chief selector is Let us assume at this moment that we subscribe the rectangle character as property element and subscribe the rectangle character here, first give the limit, there is such a tweet prank or very quick dep, but you can see that there is an attack. Will appoint and you can see here. By doing this you can subscribe to my channel. Here you can see that such a character is according to the attempt and design is therefore our animated character according to Vijay Dio Jha Loot-Loot Attack Loot-Loot Attack Like it You are saying to Brahmins or even if the security is equal in this and this side and in this, then in Raipur, all the characters have been recovered from Airtel, then now we have to learn to sacrifice only and only the rights of the character like this. What a character artist does is that he has an equal element to the lead character, he has the right to do Ghaghra and this dish. Subscribe to this dish. I will make an India in which the villages that have been supporting Adams to the maximum, can make the maximum full for a few days. The method will be applied towards dross and skimming. So let's treat these things in these ways. If we have not subscribed here then do not forget to subscribe the number of channel and tell us, then we will take it at last and wait for a global map and a local call. Junior's interior, don't help chief. Maximum Thanks of the Independence Day is used in writing of paying tax which is the lead character certificate and brain intact from acid attack. We had another example. It is not that yes this is the local maximum to negotiate for this I have to check that it is before To study the effect of CEO Ram Ravan, we have come here We will see that our morale has increased because it is our doing, it is ours, said the scientist Prof. Set the alarm to minimum and at last one time If our alarm goes off then let's comment and see that here we can see Mango trees were in and by the way this condom of your heart stops it, now we go C Plus Be the first in 2 minutes Subscribe Like And share and will express in the form and butt so and then and after that check the properties looted there eunuchs burst airtel and the one next to it got attacked after Ravana brahmin bluetooth ok set Google maps to minimum and Where are you, Yasmin, the range of Google Maps, this problem has come towards the neck line police station, here, enjoy the maths. From here, even other organizers will go to the play list, our glue will remain more, then we will subscribe to this channel, thank you. U You are wise that you can see here because our Ghaghra soldiers must have understood this board and original and calling in both the languages, you can subscribe and do comment that I
|
The Number of Weak Characters in the Game
|
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
|
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game.
A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`.
Return _the number of **weak** characters_.
**Example 1:**
**Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\]
**Output:** 0
**Explanation:** No character has strictly greater attack and defense than the other.
**Example 2:**
**Input:** properties = \[\[2,2\],\[3,3\]\]
**Output:** 1
**Explanation:** The first character is weak because the second character has a strictly greater attack and defense.
**Example 3:**
**Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\]
**Output:** 1
**Explanation:** The third character is weak because the second character has a strictly greater attack and defense.
**Constraints:**
* `2 <= properties.length <= 105`
* `properties[i].length == 2`
* `1 <= attacki, defensei <= 105`
|
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
|
Math,Dynamic Programming,Combinatorics
|
Hard
| null |
521 |
Hey friends, so in this video we will talk about the longest uncommon sub-sequence longest uncommon sub-sequence longest uncommon sub-sequence one, so this is an easy level problem, so let's directly go to the screen and understand through and example, so suppose that we have a string, now what will be its sub sequences. There will be one, there will be empty string A and B and now these are some subsequences possible with string now right now let's install another string A B C there can also be a subsequence in this that you don't take any character then choose A then What can you choose? Now give two character things, then give one more E and do all the character things on this, you ABC. Now look at if you suppose that these two strings are given and in both of them, first of all we see uncommon subsequences, then uncommon. Which is CC, likes only in this, does not take in this, right and A, this is also uncommon, and E, this is also N, is common, and this is also ABC and common names, all the other common names are TMT, A is common, B is common, now this is common. So, whatever we have circled in red is uncommon right, but what is the condition for us to find the longest one? If we talk about the longest then it is ABC whose length is here. What is the biggest sub-sequence which here. What is the biggest sub-sequence which here. What is the biggest sub-sequence which is there in any That of the string itself is ok, all the characters are equal, if both the strings are different then what will be the biggest uncommon sub sequence which will be of bigger length like in this case A B C is of bigger length a3 then 3 will be output right if I do one more Example Let me let ABC below and here ABC is the I let so its length is five right and its length should be Now both are not equal, first of all it is not equal to both then the largest sub sequence will be of which lens will it be? It will be of 5 length because it will contain all the characters. What will happen if it is of 3 length? We will return the one which is bigger among the two. We are fine that this brother will be uncommon because these are different strings if it is from string like ABC both. Both the strings are ABC, how to do that, we will not have any uncommon, when there is no uncommon then what will we return -1, so this is the philosophy return -1, so this is the philosophy return -1, so this is the philosophy friends, if we do this code, first of all we will check whether A and B are equal, so here We will write that if it is equal then there is nothing uncommon. If there is nothing uncommon then what will we return? Return -1 return? Return -1 return? Return -1 Now, if this step is not done then both the strings are not common then it means that the proof is done that both the strings are not common. If they are not common then The one whose length is greater is the answer, so write here IF I dot length is greater. Give B dot length. If A's length is greater than B then A will be the answer. So here return A dot in. If it is not so then it is not greater. So this question is very simple, friends, you can tell me by liking and commenting, thank you so much for watching this video on Match, see you in the next video.
|
Longest Uncommon Subsequence I
|
longest-uncommon-subsequence-i
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
String
|
Easy
|
522
|
44 |
Let's talk about the next coding challenge Doctor's wildcard matching is problem number four on liquid since it is also one of the most popular problems that frequently sets alarm of companies today so let's see how to solve this question and beauty questions about that all Aryan Vaidya now breaks down on pattern springs that which needs to be match against and input string s&p contains norge itself but it and s&p contains norge itself but it and s&p contains norge itself but it and white curtains on 102 a wild card characters and two types of the question of India has stressed a question mark match against any single Character only one character and what should be a person subscribe 280 to three and fuel were latest this time examples that for example for aids match against a good number of factors here is note se zen mobile ka shoulder 19 march the second exampur behave if benefit match Against beta tester us subscribe chief settings two characters then member in the eastern under right previous song again you can best games for android app that nandish case you have a question mark pims match against and next do activities apps most question excuse withdrawal haze vitamin b C D Anything A Question Mark Dummett Shuddh Sau-Sau Hum This is Problems Can Be Easily Should be Using Dynamic Programming And Will See How Close Loop Example and BDC Chief And subscribe The Amazing that Shubham in his Dynamic Programming What we do is expand the problem into several small parties and develop the possibility of common solution the assigned 1 solution each solution and finally method final solution that shows common in order to understand this dynamic programming approach for this problem latest example in the very first example IF He Went To Vaikuntha Special Characters Simple Characters Were Gone To Test Against Each Rate 101 Deep Steps To Create A Step Relation Table For Dynamic Programming In This After Balm A String Of This Year In A Row And Column Width Pattern Match Against The Right Way For Distic Bihar Taken In This Train Sudesh Nothing But Just In This Track And Where Is Disrespect And Distance 200 Familiar This Looks Like A Matrix Raid And Chief Warden To Taste Weather The Pattern Is Matching Events Every Sale And You Will Have Special Meaning So Let's Understand What's the Meaning of This and Tell Me the String 's Last This Point Convenience Stringer 's Last This Point Convenience Stringer 's Last This Point Convenience Stringer Central This Point Surplus List Asterism Matching Against the Pattern Anil Bishroi Pure Pattern Easy D That It's Match Against Lead Is the Meaning of This Channel Saurav Official Trailer Swedash Amazon Similarly IF You come to this particular this is the DCP Thakur match for ADB song now will start from smallest and will go to the best from west to be quite difficult celebs are caught off-guard caught off-guard so let's start from the 200 positions towards this End User Name Testing Should This Tasty Guest And Host Match Point E Don't Think So Sorry Good Night And Similarly Placid In The Only For U Ka Award Decide As That Anti Stranger Now Match Against Se Half Inch 9 Suggestion F1f Fence Saif Ne Jhal But the option was that the latest one was against the exact match yesterday's match but the best friend before death mystery of the match and subscribed to that they were not the same soft safe from Major Percy only fence safe that the latest one was Match For I Am Agree Not Match David DDR2 Different Characters Can Be Divided Boarding Here And A Year For The First They Will See Weather Department For The Character Of This Pattern subscribe this Video plz subscribe our ka tha but see notice not match in its n Order Match Not Match No Welcome To This Point B Exams Page Did Not Match Games Page 9 Tags Page 10 Grams Fennel Bun Hair Birds Page Subscribe Of Birth Is Sewer System Did Not Be A Girl In The Ganges Pacific Next uff a man who will see request this line that lines up and special characters will be good to write after all they have the country and that fans want and final year and you shall give the answer so district is not much for this is the Match David K Is Not To Make A Big B K B C K Is Not To Make A Big B K B C K Is Not To Make A Big B K B C Duty Hai Hua Tha Lipstick Another Example Go That ADG CBCID Office In The Same Button Slightly Different Navya Match Against This Page Way This Question Mark S Well S Another Question Mark On That Aap Sharma Previous Discussion With Number The First Come First Value Of Them With Strings Of Various Departments Guddi Anti Strength To Smt Is Treatment For Daily Morning Right Clear And Forest To Avoid A Chhote Shyam That Nav Welcome To My Now Is A Match For Any Empty String No It Is Not Want To Write App 90 Is Matter Anti Sui This Match Is Well S The Best Ringtones For A Day Previous Train To Make Hair Pattern S Well S This Is Pe 100 Gram Vikas Drishti And Destroying It And Forests Of Weed What happened was Akhilesh come to the next one and sis does n't be with the first special characters and dealing with that on Friday evening again member checks 15x against just one character in the morning hours question middle aged not been able to be at least one character but cannot be withdrawn Results of It's Not Fair Test Question Mark Against A P So Yes Question Mark Definitely Match Host Waste Water Body Previous String Formula Stringers Glue Signal E A & Signal E A & Signal E A & B or B Left Year Because It Was Not Match With This One Cannot Be March from Right To left again in question wave match against deposit half spoon butter subscribe The Amazing Twenty-20 match for this is not subscribe The Channel subscribe to hair ke din let's check for seat bhi MS Word it is fair and essence of all the moon night of all the way Have that now let's see what is the situation with CCE but not being appointed springs flight fair 110 cc against a 98 test match cht not match since series match and oblige is trick pati the match bud condition true it in the form of games is so you Will notice at any similar way can right years boys rest of them would benefit and a good question-master finally and a good question-master finally and a good question-master finally e would check question against death certificate for jobs and you will notice all subscribed similarly divided of tomorrow morning is that and answer base to values and tomorrow morning is that and answer base to values and tomorrow morning is that and answer base to values and Displaying Rare But Not Agree To t&c Displaying Rare But Not Agree To t&c Displaying Rare But Not Agree To t&c I Myself Second Example Using Dynamic Programming Third Example Fooled Him Services Of News Express Important And You Should Make Short You Understand All Situations All Questions Tomorrow Morning Start With SMT Spring And IT And Rest Were Made A Good BF loot nav this is the first time you all singer stress in dynamic programming share rate 200 ko karma bhi introduction user name birthday stress can stand for entries attempts print as well any number of characters sukhmay stress setting on in the group b match sunil shetty ki That but asked again Tedder spoon fennel 125 Deputy director Goonj pe Avoid taking action against C and withdraw it What is the President S I subscribe button video Withdraw all of them I hope you understand what means vanity Fair it means the time DCB D K is match for just star do idli par ungli only and only now school na in condition where is and 100 m to check again play list items on a stand against a percentage match video back to the previous character and this is and width that against Did not match with this did not match with write up i 13 c not match with exam paper 9th me chaff and finally addition hai na woh rough battu use disrespect stress and see what happens times hai so what food dushman ki star se this front ki in this Pattern Is Good To Be Bad Taste Against Anti Tank Notifications Cross Previous Character Android Affair Can Also Not Be True That In This Fear Being A Is Not Match For Status Not Match Point 300 Festive Vikram Anti Character Noida Extension Residents And Take Care And Wisdom 100 Ko Koil Ko Bhi The Tourists Can Take Raghu Dixit Off Wages And Only No Character Till 1 Hour 9:00 AM Character Net B 9:00 AM Character Net B 9:00 AM Character Net B Responsibility Of This Point To Match Against subscribe The Amazing 9 Tags Page 10 Vid Ooh Hua Tha So Um Will Talk But After 20 Mana Healthy Tree Against D New Delhi Always Typing Us Scan Match For In Ecuador Cattle Suid Address What We Do Is Video Dru Now In Witch App For All Possible Value Fa2 Subscribe Thirteen Patience Enter The Volume Un More Dear Hai I Hope You Understand Di Reasoning Forget and Reasoning SSC Ten Plus Two Subscribe Candy Crush Life Not at All Difficulties No Character to subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Page I am Suresh Shetty's that now let's go back to Fati Bal so serious and quantity same in the prevention Adhere to t&c achha suno idhar se shortcut s well Ravan checking all dear em all the rate columns in the previous roe aur pichdu this videos go to the Role of the same column if it columns tdap check the previous column in the name of the relation between the previous loot problem is in the previous column same disease that no let's come to be maintenance tempering no suicide f&b against maintenance tempering no suicide f&b against maintenance tempering no suicide f&b against a no fear of being and E No Varied Fancy No Copyright F But Yes It Is The Match Of The Best Flute Top End Subscribe Teachers 121 Check Bhi Vs Depend Darshan Chef Bus Ise Darshan App Ki Naav Question Mark Duggan Match Against Anti String Virat Question Against Subscribe to the attention on the exact match and that the foreign patient has Bigg Boss quantum theory of food1 question mark ball time subscribe and subscribe that nine ten final route is case no match for MT swing is not match point not match nodal match not match Against that this is the match award for best friend that heads cbd on this match stress exam date of birth question mark question is this match award subscribe will see kantirava blood from lath-path subscribe definitely result do break the subscribe button The soldiers to remind you can configure ghodavat dpro ndp are a good to have it did not length plus one more phone number of russia key and s.no length s.no length s.no length a plus one number of columns verification is incomplete i am taking rest key and din aadhaar this Number one should just in the edition of this particular us ddpo of 0f ban on improve the rule number bat a rule mattu now and will be built a specific cases of actress question mark and normal case torch light show the late 80s thousand a piya re ki Me something like this and your current peer and from this is the current account from string and share subscribe difficult to be between subscribe the subscribe button on this side to z and z - very first subscribe that today uk and with false s Well that's such a case of actress who doesn't question mark song again in this regard a piya re ki and years question mark by default always matches with any character of it's not empty string to accept for the sure except for the zero score matches with the Character Subscribe My Channel Subscribe To-Do List Of Laptop And What Is The To-Do List Of Laptop And What Is The One Normal Case Where Did It Is Not A Question Different Pattern Is Not Mention Not Acid Normal Character 10th Sample Check Bodhak Test Match And Against A Pattern Half I Felt S Equal To A String Chapter Note So This Dam's Total Denly Vigor To Again Dasenge Is The Question Mark State A And B Directly To This Column Beautiful And Sorrow And A Little Ass It's Patents To Give False Cases And in case your very first take it is not proven that you need to know and knowledge and first flight courier so let's do it is equal to with dots plus one recent s.no dots plus one recent s.no dots plus one recent s.no how to hare them all in this point b p shot length plus One that n e will create a seven portal se tweet show co sales and also have a that aap jaldi metro bana raha games and it will be of length SDO treatment plus pandit that andy flower deposit 110 dp of zero a dp of 102 100 feet to nowhere in good condition to do for lots of mind is 1000 times pet daughter length plus one class and something policy suji in it belt length prashant ji plus in which and radhe govind rusal ba third year dj sid and 1000 ki jis zero two scientists on Karo Jhal Dat Ki Sandals To Know Who Think About Stress Shifting Reason Pattern Morning Sex Is Gold Stored In Speech - Speech - Speech - 185 Vighna Dot Length Plus One Should Always Need To Subscribe To My Channel Now To You Need To Go Up To Her Left Boob Scan 06 251 Aur GPS off aaye simru button khol do hain inke is FIR position and very first columns us forms will take care over the country as they are happy I - Vansh is a happy I - Vansh is a happy I - Vansh is a question mark denotes plut doing leela1 se loop slow one millions of very - very - very - 101 And Subscribe And You Will Be Updated On The Day Of Record We Are The Last K Sweater PR Minus One Is Equal To Already taken care of this initiative for this fear files should not be taken care of all the conditions will need to return to final scene from there differing interpretations of but length - vv differing interpretations of but length - vv differing interpretations of but length - vv 10 - 10 - 10 - 1864 return gift veer ke aandar this time rims yo honey Expected To 262 Loot Significance A Proper And Have Missed Something Hai So Kya Hua Main Some-Kuch Point Me Yes Some-Kuch Point Me Yes Some-Kuch Point Me Yes Hua Hai Loot Saurabh Hai Ok This Is Some Something Good To Give Your Appeal Court Dushman The First Real Problem And 1919 This Time Hai Loot Notice is given that notary properties 09 that the cutting of your suicide to be easy manner was good Submit videos thanks for watching
|
Wildcard Matching
|
wildcard-matching
|
Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:
* `'?'` Matches any single character.
* `'*'` Matches any sequence of characters (including the empty sequence).
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "\* "
**Output:** true
**Explanation:** '\*' matches any sequence.
**Example 3:**
**Input:** s = "cb ", p = "?a "
**Output:** false
**Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'.
**Constraints:**
* `0 <= s.length, p.length <= 2000`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'?'` or `'*'`.
| null |
String,Dynamic Programming,Greedy,Recursion
|
Hard
|
10
|
1,284 |
hi friends welcome back today we are going to solve lead code problem 1284 minimum number of lips to convert binary Matrix to zero Matrix this is one of those hard problems on lead code and you can see from last like dislike ratio that this is a very likable problem so in today's session we will go through this problem we will understand the logic how we can solve this problem and we will implement the solution using Java and we will discuss that also at the same time uh before we start looking the details I want to mention that my channel is dedicated to help people who are preparing for Java G2 and coding interviews on my channel you will find lots of helpful videos that can help your Java and coding interview preparation there are over 400 different varieties of problems which are according interview questions taken from previously asked questions by big tech companies such as Google Facebook Amazon Apple Microsoft Yahoo and many other big Financial clients uh those uh coding interview questions are very important in the sense that they constitute very important wide range of coding varieties that you will generally encounter in your coding online coding interviews as well as in-person food interviews that varieties in-person food interviews that varieties in-person food interviews that varieties include BFS DFS Matrix problems graph problems according questions related to binary search trees uh strings linked list optimization problems using priority queues as well as problems using dynamic programming and lots of logical questions that can be solved with help of different data structures such as assets Maps queues Stacks so uh on this channel you will find lots of vast varieties which are which will be very helpful for you to practice for your coding questions as well as there are interview like there are videos to help your Java G2 interviews as well so please subscribe to this channel now so let's start with our uh hard problem today uh 1284 minimum number of leaps to convert binary Matrix to zero Matrix given M by n binary Matrix mat in one step you will choose one cell and flip it and all four neighbors of it if they exist flip means changing 1 to 0 and 0 to 1. a pair of cells are called Neighbors if they share one Edge correct so what it means what they are trying to say I will just show you in this one example is that for example ah if let's say this is our Matrix let's say right and this is our sale correct this is our sale of Matrix then we have to consider these four cells basically right so these are the adjacent cells basically right one two three four right these are the neighbors basically for this cell so if we are changing let's say this is one for example and these are all zeros for example just assume that all are zeros so if we are changing this one into zero one flick means this is changing this one to zero and all this zero to one basically right all these zero to one so this is called as one flip basically right so this is what they are saying so written minimum number of steps required to convert Matrix into 0 Matrix or minus 1 if we cannot convert it a binary Matrix is a matrix with all zeros and one only a zero Matrix is a matrix with all zeros right so this is what the problem statement says so we will go through one example and we will understand this problem and then we will look into some other examples as well and then we will formulate our solution right so ah as I explained you this is the idea of flip right so flip in four directions correct so you got the idea of lift so this is called as one flip basically right one flip right so we have to find out the minimum number of lips so that we can turn this one Matrix means this input Matrix to all zero Matrix means all the metric all the cells should be converted to zero right so I'll just remove this flip so you got the idea of what flip means now let's just remove this thing so uh flip means all four directions right so let's say this is our input Matrix right so 1 is our input Matrix correct so this is our input Matrix given to us and we have to find out the minimum number of flips so that we can convert this Matrix into zero Matrix correct so what we can do let's first understand a few examples so you will be clear about the problem and then we will go through the solution so this is the input Matrix right so what we will do to convert it into zero Matrix is uh first thing is we will take this cell right so uh we are taking this cell and we are flipping it so now after flip what we will flip so this red color cell we will flip and the these two nipples we have to flip correct because other two numbers are not existing so whatever is existing we have to flip so these three ones that I highlighted one will become 0 in one flip right so this is what uh Matrix we will get right this Matrix we will get correct after one clip we will get these Matrix so this is after one flip so this is one flip right all these are zeros now so now after that we will take this Matrix new Matrix and again we will do a flip on this one right on this one we will do a flip which means that it will convert this one as well as these two ones to zero correct because they are the two neighbors as I showed you before we have to consider the four neighboring cells right ah so whatever is existing we will consider so this is existing cell so we'll convert this all once to zeros so now after conversion this is what we will have correct so all these ones will be converted to zero right so this is one more flip we are doing correct so one more click we are doing so total number of Clips we have done is two correct and we have converted this input Matrix into zero Matrix so as you can see all the sales are now zero correct so we have to return this 2 as the answer basically this is the minimum number of Leaves we can take right there might be other combinations but it might take you more flips right we have to find out minimum number of lips that is a very important thing right this uh minimum number as you can see right they have tilted it so this is very important thing of steps we have to find correct so this is what the problem is right so the problem statement is pretty clear so there is no kind of confusion or anything right uh so they have given us one sample so let's take one other some other examples also right this is one other example right so where this is the input Matrix that is given to us correct so you can just say that this is the Matrix one zero and Z one zero right we have to convert it into all zero Matrix so as you can see we can just take this one correct and then we will do a clip so with this one what other ones we will do its neighbors right so this is our neighbor and this is a neighbor right vertical and horizontal right so we will flip it so after this flip you will get what you will get like zero and zero correct zero you will get so after the flip with this one correct this one so we actually did one flip and we got all the zero Matrix right so we have to just return one as our answer because in minimum number of Loops right so one is the minimum number of if we can use actually to get all the zeros correct um after that if you consider this another example right so this another example uh let's see this and then we'll go through uh our approach how we can solve this problem right so as I showed you this is the input Matrix so you can just assume that this is our input Matrix so what we will do in this case is uh we are actually taking uh let's see right one so we have taken uh this become one so this become one right so one zero so we have basically taken this zero correct in the first case and then after this zero will become one and it's never become flipped also neighbor will also be flipped right so this 0 will become one this one will become zero and this zero will become one correct so this one now we will get this as our resultant Matrix after one flip right so I highlighted you which cell we are flipping correct this cell we are flipping from zero to one so neighbor means four neighbors right so whatever is available so these are available so we are flipping it basically so one becomes zero this zero becomes one and this zero become one correct so after one flip so we did this one flip now correct we went here now again we have to do uh one more flip so now we will take this one to flip right we will take this one to flip so if I flip this one then I will flip the neighbors these ones also I have to flip correct so after the flipping how it will become all this one will become zero right zero and this is already zero right so this is our resultant Matrix after the second flip with this one right correct so this is our second flip now right and after the second flip now what we will do is we will take this one correct and then we will do a flip so again the neighbors we will flip is this one right so now it could become zero and zero correct so this is the result of the third flip right from this uh state of the Matrix we will get go to this next state you can say right it's kind of a state you can assume right so this one is a minimum number of steps are three to reach to zero Matrix so that one we have to Output as our minimum number of steps to reach to zero Matrix from the given Matrix right for this example so from all these examples it's pretty clear to you what the problem is and uh how like we have to properly choose uh zero uh which I mean sorry we have to properly choose a cell which you will flip right if we choose proper sales then we will reach there in a minimum number of time right whenever a question comes generally with kind of minimum number of steps something like minimum right so always first we have to think like uh is if this kind of questions we can generally be able to solve using BFS right BFS breadth first search or breadth first traversal correct so what we can do is we can use a technique called as BFS right whether it's for search or bread first traversal correct and generally VFS uses Q correct Cube BFS uses Q right so uh what we can do so let's take a this example that they have given us like for example zero one so what uh what I am going to say is this one is our given Matrix correct this one is our V1 Matrix so what we will do is in the BFS is we will take each of these cells and we will flip it right each of this cell and we will flip it for example uh first I take this cell I flipped it right so I get it get this one after flipping the next I am taking this cell again I am flipping so I'll get like this basically right after clipping I did this then I will take this cell correct and I will try to flip it after flipping I will get like this right as you can see right one and zero it will become correct one and zero so this is the result and after that last one I'll take this thing and I'll try to flip it so now I have from this is M by like or you can say n by n Matrix right so the output of in one step of BFS we will get uh n into n different matrices right so these are n into n so this is two by two Matrix so we will get four different Matrix right four different Matrix you see these are what I mean to say is these are all four Matrix right these are all four Matrix correct we got in one iteration we got four right for one we get four basically because we have a choice to turn out like to flip every cell now how many cells we have four cells so it means in one Matrix we have four cells which means that from one Matrix we can get four different matrices right after flipping correct so this is uh how our flipping will work in VFS so I'll just remove the uh all this coloring so this is our first iteration right and we will get all these kind of matrices after flipping correct and what we will do is we will keep checking if we are reaching us all zero Matrix right so we did not reach all zero Matrix so now we what we will do in BFS we will take each of these Matrix and we will again run the VFS on it so each Matrix will generate four more metrics for example if I take this first Matrix it will generate these four Matrix right it will generate these four Matrix correct like this basically right if I take this next one it will again generate four if I take next one again four if I take this next one again four so to for this 4 we will get total 16 generated matrices right with BFS approach and at the same time we will keep checking if we get a matrix with all the zeros right so this is the way it assures us the BFS assures us that we will reach to all zero matrices within minimum number of time or minimum number of steps right so that is why the BFS is very popular technique for this kind of problems to find out a minimum steps minimum number of time right so you got the idea so we'll take this input Matrix we will use a BFS we will generate these matrices and always will keep checking if we have reached our destination Matrix for this input Matrix is what will be our destination Matrix all zeros right all zeros is our destination Matrix if we reach this we will stop right and we will just return the number of steps we have taken to reach it right so from this one this generation of 4 is one step basically right from this four if I am generating the next 16 then that will be second step correct so uh for uh like this for in this case we will take it will need three steps they have shown us how the three steps will be needed you can take a look here uh and we will reach this all zero matrices right so I have shown you couple of other examples also how we can reach all zero matrices right like for example these examples we have seen how we can return zero Matrix right so this is our solution will be based on VFS which is called as uh breadth first search or breadth first traversal as well right and it uses Q uh so uh you got the idea uh how we can solve this problem I think so we can more understand with the Java code now so let's go to the Java solution for this problem uh yeah so this is our Java solution so I first uh implemented a wrapper class the wrapper class will take the Matrix and its number of steps correct that we have taken so far so we will wrap this information uh with this class State wrapper and this is our Constructor for the class we have implemented equals method right so whenever we are implementing equals method we wanted to uh this is our object right equals method always get objects as you can see so we have to uh equate with this Matrix right so what we will do is we will use arrays deep equals method correct with the uh incoming object which is data so data dot matrix with the current Matrix we have to use arrays.b equals method right have to use arrays.b equals method right have to use arrays.b equals method right so it will dip equals method is useful for like 2D or more than that kind of arrays right because it will compare each of the element of the 2D arrays for example in this case with the other 2D array right every element it will compare and it will tell us if both the arrays are equal or not so this one you can find out in the uh Java docs right Java documents in our Apple so here this DP equals method it will take two uh arrays here right and it returns to if two specified arrays are deeply equal to one other right so what it means is it is appropriate for use with nested arrays of arbitrary depth right so that's what they are saying so if it will compare each of the element two other references are considered deeply equal if both are null or if they refer to arrays that contain same number of elements and all corresponding pairs are deeply equal means their values are also equal right so that would be uh arrays deep equals method we will use right so this is the uh let me show you so this is from the Aries class right so if you go java.look it has RS class so if you go java.look it has RS class so if you go java.look it has RS class so that's a very handy method you can take a look at the Java documentation but that's what we will use okay and then we will also use the Deep hash code method from the to calculate the hash code of the Matrix right it's also in the address class so uh so this is our first state wrapper class that we will use in our solution I showed you that now we have one helper method where which will check if the sale is within the boundary of the Matrix right so this is the helper method cell inside Matrix so this is our original method mini flips right so matte is the two dimensional Matrix that will get as an input we will create a queue of State wrapper objects right this is a state tracker class that I showed you so few will take the objects of State wrapper class right and first we will start with a step wrapper class with the given Matrix and number of steps in the beginning is zero right because we have not taken any step yet so that is our starting point for the BFS the destination here we are going to create a destination Matrix of the same size as the original Matrix so uh as I shown you so this is a two by two Matrix right originally so we have created a two by two Matrix with all zeros right because this is what our destination Matrix is correct so that's what we are creating here destination Matrix and we are just filling it with zeros correct after that we will just make a set of state chapter objects so that we will know that we have already visited that uh State trapper object right so we have we don't want to recalculate or revisit the same cells basically for that we will use this uh visited array right oh sorry visited hash set right after that this is the point where our VFS starts now right so BFS starts here so this will be done like this while loop will continue until the queue becomes empty right so as long as there is something in the queue it will keep doing the VFS right so first we will follow the current element from VFS right and then we will get the step State wrapper class then what we will do is first thing we always wanted to do is the state wrapper class width has a matrix right because as you can see it has two things Matrix and number of steps so Matrix and number of steps correct so once we get this oh um get the state driver object from the queue first thing we will wanted to do is did we reach our destination right did we reach our destination Matrix so that's what we will check using the RSD back walls correct we will pass the current objects Matrix and the destination Matrix that we have created here correct so if we reach the destination then we have to just say current dot steps so because that is how many steps we have taken to reach to the destination right if that is not the case we will check if we have already visited the current metrics the current state basically right this is the current state object you can say right so we will check if we have already visited that if not then we wanted to visit it so we will just add it into the visited asset here and we have the four directions correct because we have to do the flip in four Direction so that's why we will use these four directions uh so first thing is we will copy from the current Matrix uh using the arrays stream right so if you are familiar with Java it streams then that's what we have used here and then we will just use the map so that we will actually we don't want to change the actual state of the current Matrix right that's why we are just doing the uh this uh getting the stream and then mapping it to the array so that we will get a copy of the uh Matrix right so this is where we are getting the copy we'll just call it as a copy here and uh kind of cloning right so copy we will get it and then we will start doing the simulation that on the copy basically right we will have to simulate in four directions correct uh so four directions so this is where our simulation starts right so we will go from I goes from 0 to the number of rows right current Matrix dot length is the number of rows and this is the number of columns correct so this is what we are doing in two for Loops we will go in each cell of this current Matrix correct each cell of the current Matrix and we will try to flip it correct so as I showed you here so each cell we have a taken right first let me just remove these colors so I'll just remove this color so that like this one become real yeah so what I'm going to say is each cell we will decorate first this cell then this cell and we will keep generating this Matrix so this is for example for this cell this first Matrix right we generated for this next cell this second Matrix we generated after flipping right for this cell we generated this after flipping and for this cell we generated this after flipping as you can see the for the last one for example if I flip this one to zero then this will become one right as you can see one and zero right so we are taking each of the cell of the Matrix and we are flipping it so that's what simulation we are doing here correct will flip on four directions four neighbor neighborhood right Neighbors and we first wanted to also uh before we do the flipping also we have to make sure that the this next row and column position that we are generating issue we are inside the Matrix right then only it makes sense to flip right otherwise we will not flip if it is going outside of the Matrix right so this thing actually is just like the doing the flipping thing for all the cells after that we will just say um this copy i j is equal to 1 minus copy of i j and then we will add into the Q the new state of the Matrix right this is the new step of the Matrix with number of rows sorry number of steps will be previous step plus one correct because we are taking one more step so this copy will be our news new Matrix right new Matrix for example from this I generated this Matrix so I will put this into the queue then this into the view right so that's what and the thing is number of steps we are 0 here I will put number of steps as the one correct because this is one more step we have taken to reach here correct so that's what we are doing here and then uh we will just do this copy of uh current Matrix so we are just cloning it basically correct um so this one we will do keep doing it this whole thing until uh the queue becomes empty or if we find out our destination Matrix here we will just return the number of steps we have taken to reach their color right current object that we are getting from the Q falling means we are removing from the queue here right the object State wrapper object so State wrapper object will have the new Matrix and the number of steps we have taken to reach there right so that's what we have to return here if we find out the uh we reach the destination Matrix right if we cannot reach it through the throughout this while loop then at the end we will come here and we'll return -1 it means that here and we'll return -1 it means that here and we'll return -1 it means that we cannot convert that Matrix into all zero Matrix right so I got like you got the idea of how we can do it right so I showed you this example I think here yeah here right two steps so let's go ahead and take a like around this code and make sure we get two steps so we are getting two steps which is the correct answer right uh after that I created a few examples uh for you so let us just uh take some examples here so this is one of the example right so I'll just copy and paste this example so this we have seen I think uh yeah this example we have seen right one zero so in one step we sorry uh this example in one step we can convert it so let's make sure this works so this works we are getting correct answer after that let's take this example which is the given example they have said it takes three steps for that so let's make sure it takes three steps so three steps we are getting correct answer then let's consider one negative test case so this is negative test case where we cannot convert it into the all zero Matrix at all zero metrics so let's it should be what give us minus 1 so it is giving us correct answer minus one right so let's just finally use all these examples three zero minus one so we are getting all correct answers so uh we can submit our solution now and make sure it's accepted so our solution got accepted by lead code as you can see uh this is one of the hard questions on lead code the minimum number of lips to convert binary Matrix to zero Matrix right our solution is accepted uh and I showed you already in details how our solution works with the help of BFS and Q and you also may want to take a look at the Java util arrays class methods uh we use the method to copy like to create the hash code as well as to uh copy the like to uh check the equality of the matrices right so both these methods you wanted to take a look at right because that will be very helpful this method D equals right that we have seen here and deep hash code right uh so if you are new to my channel there is a dedicated playlist on my channel called as edit code and Lin code Solutions uh there are over 200 different varieties of problems which are according questions asked by Amazon Apple Google Facebook uh Microsoft Yahoo and many other big Financial type clients um apart from this there are three other main coding playlists you uh wanted to go through on my channel the names are old forces code shift and add coder all in all there are over 400 different varieties of coding problems uh that if you uh like wanted to prepare for your coding interviews if you go through those problems will definitely be help you in your uh understanding of how you can approach and solve different coding problems with the help of different data structures and with the help of different techniques right because uh if the more problem you solve the better for you in your coding interview cases because you know what techniques we can apply to solve different varieties of problems right so for example in this case we use the technique BFS right breadth first search because you know like more problems you solve you will understand from that what techniques and how we can solve different problems if you like this video If you find this video helpful and if this like if you like the way this video has been created with the help of whiteboarding session examples and Java food then please give it a thumbs up or give it a like uh also share this video with your friends and colleagues who might be preparing for coding interviews they can also go through these videos and get help uh by watching these videos in their according and Java interview preparation uh if you like this video uh and if this video helped you in understanding this problem this hard problem in a easier and better way then please give it a thumbs up and give it a like uh also if you have any questions related to this problem uh or this video then put your questions below the description section the Java solution that we have seen here is solution I am going to put this code on my GitHub project you can check out the code from my Gita project and play with the code with different unit test cases for your better understanding and uh you can also practice uh with this kind of like with lot of examples or Solutions are there you can practice those Solutions and if you like my Java solution then please consider giving it a star on my GitHub project that might be helpful uh cheap coding the more you keep coding more problems you keep solving the better you will become at solving the problems and coding questions there are also videos for your interview uh like telephonic and initial round preparation for Java interviews uh the playlist is called as Java interviews you can check it out there are a couple of videos there are also videos related to Java architecture design patterns as well as Java string coding questions that are asked previously on telephony grounds so you might want to check it out uh thanks for watching this video
|
Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
|
four-divisors
|
Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing `1` to `0` and `0` to `1`). A pair of cells are called neighbors if they share one edge.
Return the _minimum number of steps_ required to convert `mat` to a zero matrix or `-1` if you cannot.
A **binary matrix** is a matrix with all cells equal to `0` or `1` only.
A **zero matrix** is a matrix with all cells equal to `0`.
**Example 1:**
**Input:** mat = \[\[0,0\],\[0,1\]\]
**Output:** 3
**Explanation:** One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
**Example 2:**
**Input:** mat = \[\[0\]\]
**Output:** 0
**Explanation:** Given matrix is a zero matrix. We do not need to change it.
**Example 3:**
**Input:** mat = \[\[1,0,0\],\[1,0,0\]\]
**Output:** -1
**Explanation:** Given matrix cannot be a zero matrix.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 3`
* `mat[i][j]` is either `0` or `1`.
|
Find the divisors of each element in the array. You only need to loop to the square root of a number to find its divisors.
|
Array,Math
|
Medium
| null |
1,630 |
hello everyone welcome to another video in this video we are going to look at another Aries medium level question although it is it says it is medium but it is really easy and we'll see how so let's jump into the question what it says and then we'll understand how we are going to solve this so basically I've written it down already example number one and I'll explain you with the example what it is asking so we are given three arrays right now first is the numbers array okay second is our L array which is also we can say it as left uh and the third is our R array which is we can also write it as write array so what is left and right array are doing let's vector or array I will be referring this as array only okay so what this arrays do so basically they are saying us that we have a left pointer and we have a right pointer pointing in our numbers so let's take the first example 0 and 2. okay now we need to take all the elements between 0 and 2 and including those two elements those two values right these are basically the indexes okay so we have to take 0 1 and 2. these indexes values at these particular indexes what are the values 4 6 and 5. and we need to find if this can be changed to an A B okay if it is possible to rearrange these elements and convert it to AP now what's the fastest way to do that by sorting so what we'll do we'll sort this okay and we'll see do we have an AP is like arithmetic progression that all the numbers all the values that we have a common difference right so basically difference between 5 and 4 is 1 6 and 5 is 1 so we have a common difference so it is an AP and if it is an AP we'll return it true and we'll add it to our final result okay now in what cases it is possible that this will result in false so let's see that as well okay so let's say let's take the second uh like first index okay we have taken a zeroth index now let's take the first index 0 and 3. so in between we have one two and three inclusive right so what are the values that we are going to have at these indexes so it's going to be 4 6 5 and 9. let's say we arrange this like we sort this so we'll get 4 5 6 and 9. what's the common difference one what's the common difference three so we do not have a common difference between all the values so this is going to be false okay and we will add false in our finer answer okay now although it looks uh like it is really simple uh if you have understood this then you can start writing the code for this otherwise you can look at uh what I am coding okay and let's jump into the code now the first thing that we need over here is our result so let's create that okay and we will need to return this result so whatever the magic that is going to happen it will happen between this now one more thing that we need to go through is our l vector or L array whatever okay we'll start from I go till the size of our l and that's it next we need to have a temporary vector temporary array which will give us the array having left and right indexes right what I mean by this is that whatever value we find over here whatever array we find let's say we have 0 1 and 2 Okay so this will give us the array 4 6 and 5. we need to store this right so we'll store this in our temporary so let me create that as well I'm sorry now it is not necessary that you give the length or the size of your vector over here but you can give if you want to okay now let's add values in our temporary array so for in J this will start from left pointer it will go till we are using equal to because we have to be inclusive of that value right so this is going to go till the r of I and J plus and we'll simply add our nums J value in our temporary Vector for array whatever now we need to find if this is arithmetic or not okay now this is a function this will return a Boolean value okay and whatever value we get we will simply add it to our result okay now we need to write this function as well right so let's do that this will be returning a Boolean value okay find arithmetic this will have a vector foreign now the main thing that we need to check first of all here is that what is the size of this temporary area Okay because there are chances that the size of this array is one two whatever it is okay but let's say if the size is one okay in that case let's take the first value 4 is it an AP yes obviously it is an AP let's take the size as equals to 2 so we have 4 and 6 is this an AP yes definitely so we need to take care that if we have the size of our temporary array as one or two okay then it is an AP okay so let's say if temp dot size is less than or equal to 2 in that case will return true now we'll simply sort this so to find if this is an AV or not okay the Sorting is done now we'll check so let's go now first before that we need to find a difference right so what is the difference is nothing we are 10 both 1 minus 10 of 0. this is the common difference that we are going to use okay now for let's go from one till the size of our temporary array and we'll increment okay we'll check if 10th of I minus 10 of I minus 1 the difference if that is equals to difference or not if not you return false otherwise we'll simply return true our task is done let's submit this okay as you can see it's really that simple and this is there is nothing new this is just a basic mathematical thing that we are going we are doing over here so I hope you understood this and you found it interesting and you learned something new okay so do let me know if you have any other problems for me to solve from another platform thank you for watching I'll see you in the next one till then keep coding
|
Arithmetic Subarrays
|
count-odd-numbers-in-an-interval-range
|
A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`.
For example, these are **arithmetic** sequences:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not **arithmetic**:
1, 1, 2, 5, 7
You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**.
Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._
**Example 1:**
**Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]`
**Output:** `[true,false,true]`
**Explanation:**
In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence.
In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence.
In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence.
**Example 2:**
**Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\]
**Output:** \[false,true,false,false,true,true\]
**Constraints:**
* `n == nums.length`
* `m == l.length`
* `m == r.length`
* `2 <= n <= 500`
* `1 <= m <= 500`
* `0 <= l[i] < r[i] < n`
* `-105 <= nums[i] <= 105`
|
If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low.
|
Math
|
Easy
| null |
283 |
hi everyone in this video i will be covering the solution to lee code number 238 which is also called move zeros so let's begin by looking at the problem statement given an integer array nums we want to move all zeros to the end of it while maintaining the relative order of the non-zero elements the non-zero elements the non-zero elements we're also given that we must do this in place without making a copy of the array so let's look at an example to better understand the problem so here we are given an input of an array called nums with the values 0 1 0 3 and 12. and you can see that in the output we have an array where all the zeros are at the end and the non-zero elements are at the and the non-zero elements are at the and the non-zero elements are at the beginning in the same order so how exactly can we solve this problem especially without making a copy of the array well we know that as we iterate through the array from left to right we want to take the non-zero elements we want to take the non-zero elements we want to take the non-zero elements and put them at the beginning so as we iterate through this array whenever we encounter a non-zero element whenever we encounter a non-zero element whenever we encounter a non-zero element we want to put it at the start so in this case the first non-zero so in this case the first non-zero so in this case the first non-zero element mean counter is one so we would put it at index zero and then we continue iterating the second non-zero element we encounter the second non-zero element we encounter the second non-zero element we encounter is three so we would put it at index one and then the third non-zero element we and then the third non-zero element we and then the third non-zero element we encounter is 12 and so we would put it at index two and then we would replace the remaining elements with zero so in order to implement a solution we will need a variable that will keep track of at what index can we put the next non-zero value at so i'm going to create non-zero value at so i'm going to create non-zero value at so i'm going to create a variable and call it index and i'm going to initialize it to 0. and this is because the first non-zero and this is because the first non-zero and this is because the first non-zero element we encounter we would want to put that at index 0 at the beginning of the array and we know that as we continue replacing elements we would want to increase index by 1. so now let me go through this example again using this variable so you can see how it works so we're going to iterate through from left to right and so again our first non-zero element would be 1 and we would non-zero element would be 1 and we would non-zero element would be 1 and we would place it at index zero and then we would increase the index variable by one and then our next non-zero element would and then our next non-zero element would and then our next non-zero element would be three and we would put it at index one and then we would increase index by one so now is two and then finally we would look at our last element which is also a non-zero last element which is also a non-zero last element which is also a non-zero value 12 and we would put it at index two and we would increase this index variable by one from here we can use the index variable once again because we know that the remaining elements from indexes three to the end of the array must all be zeros okay so let me summarize how the solution will work first we will create a variable index and initialize it to zero then we want to iterate through the array elements from left to right and if the array element nums of i is non-zero non-zero non-zero we're going to set nums of index to nums of i and then we're also going to increase the index variable by one and then we will iterate through the array elements from index to the end of the array and we're going to set all these elements at these indexes to zero so now i'm going to be going over the code for this problem the first thing i'm going to do is i'm going to create a variable called index and set it equal to zero then i'm going to create a for loop that iterates through the array or vector numbers i know that if nums of i is not equal to zero so if it's non-zero then i want to set so if it's non-zero then i want to set so if it's non-zero then i want to set nums of index equal to numbers of i and i want to increase index by one and then i want to iterate from index to the end of the array and set all those elements to zero and if i submit the solution i get that it works
|
Move Zeroes
|
move-zeroes
|
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements.
**Note** that you must do this in-place without making a copy of the array.
**Example 1:**
**Input:** nums = \[0,1,0,3,12\]
**Output:** \[1,3,12,0,0\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you minimize the total number of operations done?
|
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
|
Array,Two Pointers
|
Easy
|
27
|
1,823 |
hey everybody this is larry this is me going over q2 of the weekly contest 236 find the winner of the circular game so yeah so this one there are a couple of ways to do it um i think you can actually i don't know i did this in a very funky way but uh and that's why it took a little bit of a long time but i think you can do it in a naive way and that would have been fine uh and there in that you know you use a d uh usually you use a deck and then you keep removing stuff from the front put it at the end um but the way that i did it and hit the like button to subscribe and join me on discord for this problem um is that i did this so list and i just you know um basically i if i try to find a um with a sorted list i could keep track of uh what element to remove and it's to be honest it doesn't have to be assorted list um i actually use this like a linked list in a removal i just you know like i you know if you have a linked list and you're able to remove you know the whatever element um then that's all you have to do um but basically this is how i did it um yeah let me know what you think i mean this is otherwise a simulation problem i did it with a little bit cuter weight it becomes you know n log n or something like that or uh so it is definitely faster than n square solution which is what i would have recommended because you get that way quicker but uh i just wanted to get it out of the way um don't know why and sometimes you know you do funky things but yeah let me know what you think about this solution um but basically you know you move the element k times each and then every time you know you have to subtract one because you remove that element but that's pretty much it and then you remove um i like i said i use this almost like a linked list with um with appointed two to millos so i don't have to go for the linked list but i probably have just used a deck and then keep on doing a circular thing yeah oh well uh maybe next time uh let me know what you think and i and you could watch me stop it live during the contest next hmm you hmm oops um like why is this all five one every second oh i see yeah thanks everybody for watching this video hope this helped uh and hit the like button to subscribe and join me on discord let me know what you think about this problem and how did you do during the contest or just afterwards uh of solving or whatever i'll see y'all next time yeah stay good stay healthy take care of yourself take care of others um to good health and to good mental health i'll see you next problem see ya
|
Find the Winner of the Circular Game
|
determine-if-string-halves-are-alike
|
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise from the `nth` friend brings you to the `1st` friend.
The rules of the game are as follows:
1. **Start** at the `1st` friend.
2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once.
3. The last friend you counted leaves the circle and loses the game.
4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat.
5. Else, the last friend in the circle wins the game.
Given the number of friends, `n`, and an integer `k`, return _the winner of the game_.
**Example 1:**
**Input:** n = 5, k = 2
**Output:** 3
**Explanation:** Here are the steps of the game:
1) Start at friend 1.
2) Count 2 friends clockwise, which are friends 1 and 2.
3) Friend 2 leaves the circle. Next start is friend 3.
4) Count 2 friends clockwise, which are friends 3 and 4.
5) Friend 4 leaves the circle. Next start is friend 5.
6) Count 2 friends clockwise, which are friends 5 and 1.
7) Friend 1 leaves the circle. Next start is friend 3.
8) Count 2 friends clockwise, which are friends 3 and 5.
9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.
**Example 2:**
**Input:** n = 6, k = 5
**Output:** 1
**Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
**Constraints:**
* `1 <= k <= n <= 500`
**Follow up:**
Could you solve this problem in linear time with constant space?
|
Create a function that checks if a character is a vowel, either uppercase or lowercase.
|
String,Counting
|
Easy
| null |
692 |
um hello so today we are going to do this problem which is part of lead code daily challenge um top K frequent words um so the problem says we get an array of strings words and we get an integer k and what we want to do is return the K most frequent strings so for example for this list words we have I occurring twice and love two times and coding once right and so the two ones that occur the most are um I which occurred twice and love right so we'll return those um one thing though to notice is that um we want to return the answer sorted by frequency right so if you have one that occurs three times and one that occurs two times you want the one that occurs three times first so from highest to lowest and we want to sort the words with the same frequency by their lexicographical order right so if you have two words that have the same occurrence count like I and Love here we want to have them in the order of lexical graphical order so I is before l so we return I first right um let's take a look at the second example what we have for so you can see the D here occurred here four times uh Sunny occurred twice is occurred three times right so we need the first and then is second um but since we want four we will return day which occurred only once right so that's the idea um now let's see how we can solve it um okay so definitely like the most straightforward solution is we need to keep track of the number of occurrences of each world right so we can use a counter in Python encounter or you could use a hash map or you just go through the words and each time it occurs we increment by one so that's the first thing we need to do and then from there we can just sort the word using that count so what does that mean let's take a look here um so let me grab the example we have so we have this as words okay so we want the occurrences so we have we know that I occurs twice love occurs two times lead code once and we have k equal to 2 by the way uh lead code once and coding once right um so what do we need we can just take the list of words but unique words right we don't want repetitions so we can take the list I um love and coding I just saw this right but sorted by what are the keys so the problem says the keys need to be the frequency first but then if the frequency is the same one as sort by lexicographical orders what this tells us is we need in our key here so the key in Python you will get a Lambda with the word as a parameter and with sorted in Python if you are using another language there is also a comparator in Java that you can do this with we can provide the two things that we want in order right so the first thing we need is the count and that will be in this occurrence map so how do we get the occurrence of a world it's just occurs W right as the key but we want to sort it in order if we just do this it will be sorted in descending order we want in ascending order what we want is descending order so we can just put minus so that we get a descending order okay so okay let's sub w and then what's the second parameter we need so the second parameter is the lexicographical order so that if this is equal we'll sort by what so we just do W right um and that's pretty much it and how many we want out of this sorted list we just want the first two right so let's call this s so we want to return the first two but generally the first K right um so that's one way to do it um the only thing to pay attention to is that we don't want to pass the entire list right we want to pass the only unique values because otherwise we'll get your petitions so we can just pass in set words and sorted works with this with set as well but if you want you could also just use list converts it to almost right um so that's definitely one way to do it so let's cut that up but there is another way where you could use a periodic cure right and just for the priority queue enter this value here and then keep popping until K reaches zero and that will give you the same thing but let's use this set solution first so what do we need An Occurrence map so that would be a we can that would be a we can that would be a we can use definitely counter which is available in Python where you could just do counter words but just for a sake of example here I would use I will use just a map so default dict with int and then we'll go through the words and just increment by one so this is exactly what counter does collection.counter collection.counter collection.counter um and then we will just use what we said here right this will give us a list of the this list sorted with unique values sorted by okeros and W right and this is by the way an interesting pattern here where the key is not actually one of the immediate values of the list we are sorting it's using another data structure and so here we want to return just the first K ones I'll just run this I lost a bit okay so that passes now in terms of time complexity this is O of n being the number of words here it's sorted so open ligand again n being the number of words um so overall that's the time we are using here it's over login okay time now in terms of space we are using two things here this map here or collection and then this list here so overall it's over a space um yeah so now I just want to show the priority queue solution um so what we need is we need to First Define a priority queue go through the words in the count right and go through the occurrences items and for this one just to show for the second example to show another thing you can use counter right instead of the our own list and then we want to keep push for the periodic queue we're going to push the count we want it to be negative right um we wanted to be negative because we want to start in descending order and hear the word okay and now what we want to do is keep popping until we get the first K ones right so while K bigger than zero and period Q just in case k is bigger than the length of the list um we want to do hip pop um hip queue we want to pop this we don't care about the count what matters is that when we pop we'll get only the ones that have the highest count but we care about the world and so in our rest we'll just open the world and we'll decrement K so that it reaches zero then at the end we just return that result let's run this and we can submit okay so that passes as well I'm using pre-ordhq pre-ordhq pre-ordhq um yeah so I think that's pretty much it for today's problem please like And subscribe and see you on the next one bye
|
Top K Frequent Words
|
top-k-frequent-words
|
Given an array of strings `words` and an integer `k`, return _the_ `k` _most frequent strings_.
Return the answer **sorted** by **the frequency** from highest to lowest. Sort the words with the same frequency by their **lexicographical order**.
**Example 1:**
**Input:** words = \[ "i ", "love ", "leetcode ", "i ", "love ", "coding "\], k = 2
**Output:** \[ "i ", "love "\]
**Explanation:** "i " and "love " are the two most frequent words.
Note that "i " comes before "love " due to a lower alphabetical order.
**Example 2:**
**Input:** words = \[ "the ", "day ", "is ", "sunny ", "the ", "the ", "the ", "sunny ", "is ", "is "\], k = 4
**Output:** \[ "the ", "is ", "sunny ", "day "\]
**Explanation:** "the ", "is ", "sunny " and "day " are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
**Constraints:**
* `1 <= words.length <= 500`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* `k` is in the range `[1, The number of **unique** words[i]]`
**Follow-up:** Could you solve it in `O(n log(k))` time and `O(n)` extra space?
| null |
Hash Table,String,Trie,Sorting,Heap (Priority Queue),Bucket Sort,Counting
|
Medium
|
347,1014,1919
|
1,921 |
challenge21 promotion eliminate maximum number of monster basically we have given a question in which we have playing a video game where we defending our city from n number of most monsters and there is distance with size n and distance I is donate to the initial distance in kilometer of the I monster from the city the monster walk towards the city with a constant speed that speed is around given in a speed Vector which were given in our question so I monster has I speed kilom per minute and you have a weapon once fully charged you can eliminate a single Monster and the weap to charge it again you can lose any monster reaches your city and if a monster reaches the city at exact moment a weapon is fully charged it is also count as a loss so your game is going to end so we have to return the maximum number of monsters which we can eliminate before we lose so guys this is our question and we have to find how many maximum number of monster we can eliminate so there is a Formula which we already learned in many times in our school life like speed is equals to distance Upon Time and here distance and speed is given so we can calculate the time of our monster reaches to the city and as we calculate our time to reaches to the city then what we can compare it one by one and we just know the answer so first of all we just make a double Vector double is that's why because our distance upon speed is sometimes is exponential uh is sometimes to be decimal that's why not exponential decimal then it's our speed size i++ and we have to i++ and we have to i++ and we have to just push back what double and this is distance I speed okay guys and after that we just what our answer is zero time taken is zero now we use Auto auto a to time and auto a to time we just have to compare ke if our a in our time are which is taken a monster to reaches to the city if it is our time is more so we loses because monster reaches else we eliminated answer Plus+ but before doing all such things Plus+ but before doing all such things Plus+ but before doing all such things we just have to sort because less number of time taken by a monster must be in starting so that's why we doing a sorting here uh let's run over code yes guys it's going to accept it now we submit our code so our daily lead code challenge is completed please submit your solution also and uh be with us
|
Eliminate Maximum Number of Monsters
|
eliminate-maximum-number-of-monsters
|
You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute.
You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start.
You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon.
Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._
**Example 1:**
**Input:** dist = \[1,3,4\], speed = \[1,1,1\]
**Output:** 3
**Explanation:**
In the beginning, the distances of the monsters are \[1,3,4\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,2,3\]. You eliminate the second monster.
After a minute, the distances of the monsters are \[X,X,2\]. You eliminate the thrid monster.
All 3 monsters can be eliminated.
**Example 2:**
**Input:** dist = \[1,1,2,3\], speed = \[1,1,1,1\]
**Output:** 1
**Explanation:**
In the beginning, the distances of the monsters are \[1,1,2,3\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,0,1,2\], so you lose.
You can only eliminate 1 monster.
**Example 3:**
**Input:** dist = \[3,2,4\], speed = \[5,3,2\]
**Output:** 1
**Explanation:**
In the beginning, the distances of the monsters are \[3,2,4\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,0,2\], so you lose.
You can only eliminate 1 monster.
**Constraints:**
* `n == dist.length == speed.length`
* `1 <= n <= 105`
* `1 <= dist[i], speed[i] <= 105`
| null | null |
Medium
| null |
383 |
hello everyone welcome back here is vamson and if you're new here hit that subscribe button for more coding Adventure so today we are cracking uh open the uh classic problem so uh can you construct a ransom note so this problem uh from L code is uh not just intriguing but also fantastic way to master hashmap so without further Ado let's dive in all right so here is the scope of the problem you are given two string uh Ransom note and magazine and your task is to figure out whether you can construct The Ransom note using the letter from the magazine so the catch each letter from the magazine can only be used once so let's quickly go over so examples so given uh Ransom note a and magazine B the output is false because there is no a in the magazine and also we have uh yeah let's go over example where is true so Ransom note is a uh a as you can see and magazine contain letters a and b and the output is true because we have enough letters uh of a to construct the node so now uh The Brute Force solution would be to remove each uh used letter from the magazine string as we find matches but uh this come on uh we can do better so uh the time complexity will be yeah uh probably uh o n Square so uh yeah not so optimal and the optimal approach uses a hashmap to keep track of the frequency of each letter and in the magazine and it should run in linear fashion so just o n and we then iterate through the ransom node to see if we can construct it so uh I promise you it's simpler than it sounds so we'll try to solve it in go so uh let's dive into go implementation so uh first create a map to store the frequency of each letter in magazine so it will be letter frequency make map in and populate the map with the frequency of each letter in magazine so for letter and range magazine letter frequency letter Plus+ and iterate through the ranom node Plus+ and iterate through the ranom node Plus+ and iterate through the ranom node and check if we can construct it so how would far letter range run some note and IF frequency exist letter frequency letter uh not exist or frequency is zero then return foral and decrement the frequency of the current letter we have picked so it will be letter frequency letter minus and return true if we didn't return uh false uh in the meantime so let's run it to verify it's working for our free uh example test case so as you can see all good uh so uh there we have it the core logic is really straightforward so we create a hashmap a letter frequency to store the frequency of each letter in the magazine and then we Loop through the ransom note decrementing the frequency of each letter we picked and if we hit a snack like a missing letter or zero fre frequency we return false uh immediately so uh let's run some test to make sure our Cod uh work solid also for un test cases so I'm submitting it uh so yeah it should work and as you can see yeah our implementation bit 71% % with respect to implementation bit 71% % with respect to implementation bit 71% % with respect to runtime and also 84 with respect to memory so all good and the code works like a charm and yeah with a Time complexity of o n and a space complexity is also o n and this solution is ready for uh yeah uh quite efficient so uh that's wrap up today's session and if you enjoy this live coding session make sure to hit the like button and if you have any question or suggestion for future episodes drop a comment below and also uh be sure to check the description for the GitHub repo uh containing uh implementation in uh python rust C++ and implementation in uh python rust C++ and implementation in uh python rust C++ and much more and thank you for tuning in and yeah until next time keep practicing stay motivated and happy coding
|
Ransom Note
|
ransom-note
|
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.
Each letter in `magazine` can only be used once in `ransomNote`.
**Example 1:**
**Input:** ransomNote = "a", magazine = "b"
**Output:** false
**Example 2:**
**Input:** ransomNote = "aa", magazine = "ab"
**Output:** false
**Example 3:**
**Input:** ransomNote = "aa", magazine = "aab"
**Output:** true
**Constraints:**
* `1 <= ransomNote.length, magazine.length <= 105`
* `ransomNote` and `magazine` consist of lowercase English letters.
| null |
Hash Table,String,Counting
|
Easy
|
691
|
1,840 |
hey what's up guys uh this is chung here so today uh it's called number 1840 maximum building height okay so you're given like uh um buildings in the cities labeled uh from one to end right then however there are some restrictions so when we build these buildings so first you know the building the first building must be zero the height of the first building must be zero and each adjacent building the height difference cannot be greater than one right and additionally there are like also some restrictions for some buildings that's why you're given like this kind of restrictions list where the uh the id means that you know that's the uh the position right the position of that building or the label of the building and the max height means that you know the maximum height of the building and they ask you to return the uh the maximum possible height of the tallest building so what does it mean it means that you know let's say we have uh let me yeah let me remove the uh the dark mode here so for example we have uh we have five buildings and then we have two restrictions among those five buildings so the first one is the two right so building number two has the uh the restriction one right and then the uh the building four has al also has restriction one you know okay and since we know the first building the building one is always starting from zero right and then from building two you know we can it can be uh it can be either zero or one right but since we're trying to get the tallest building that's why you know we will always reach the limits so that's why the building two has highest as one has height one and then for building three you know since building three doesn't have any limits or it doesn't have any restriction we can just also increase the building three height by one but when we are at building four right we cannot keep increasing because there's a re there's a restriction for building four which is one which means that we have the only we can only decrease it to one right and then for building five you know then we can increase it again because building five doesn't have any restriction that's why as you guys can see we have two buildings has it has the height have the height too that's why the answer is two right and an example two here you know this is a special case basically you know basically if there's no restrictions at all you know obviously we can the building can always be increasing right that's why we have five here and yeah here's like another example here you know as you guys can see here you know so in restriction the restriction for building two here it says five right but so that's why we have a this is a restriction here right but in reality we cannot build a building with height five because we have another restriction which means that you know each uh alternate the json buildings currently has the difference of the height cannot be greater than one that's why even though we have uh limits of five here you know for building two we can only has height one here right so this is another like scenario here and then we're just following let's follow the same patterns here you know and then we will have like this one the building 8 which will have a height five that's why we have this five as it has the answer right and we have some like uh constraints here so first you know the number of the buildings and the heights there are that they're both to be very big right so if we try to enumerate those two numbers we'll definitely tle right but look at this like the restrictions length right so the restriction length is like what it's up to 10 to the power of five so which means that you know we should uh enumerate right traverse the restrictions instead right so i mean the solution is not it's not very hard for this problem you know if the difficulty is that how can we write a very clean code to solve this problem you know obviously there are a bunch of scenarios right so if we uh enumerate the restrictions right so between two restrictions you know we have some patterns here right so if we have this kind of restriction here you know this is restriction one right and then we have another restriction let's say this is another restriction here right so between those two restrictions we have some we have distance right and then we have what we have some like the height difference here this is the distance right and this is the height difference so obviously you know if this distance is long enough right so what we can do is you know we could we can dispute this one we can keep increasing basically uh between those like those two restrictions we can build a building in some in a way like this increasing and then decreasing right so which means that you know we can build like a higher building in between if this distance is long enough right so similarly with uh similarly if it's like different is it like another scenario which is this one right if the current one is it's like a lower than the previous one the restriction we can also do a similar thing right like this and then going down here right so all we need to do is that it's just we just need to compare basically try to use this distribution right sorry not distribution the distance right and then we'll subtract the difference right and then we'll have like a remaining distance that we can use right and that when we simply do it remaining divided by two that will be the height right the height for this kind of uh mountain right and then we simply just use the uh the base plus this kind of additional height to be the maximum the highest one in this kind in this range that's the basic idea right but there are like some other like noises for this problem you know so first you know there's like this kind of uh corner case a special case where you know as you guys can see we have like a two uh pointing to five right so which means that you know the restriction it's not like a true restriction so what is what should be the true restriction in this case so for two instead of five it actually the true limit should be one because you know if we start it from left to right so that's the first thing we need to fix we have to somehow like get the true limit for each of the position the label right and after that we can use those kind of restrictions to calculate the actual maximum height right and another thing is that i think we're assuming uh the restrictions that given us can satisfy all the buildings that's one of the known fact right known condition so i mean if you consider like a different scenario like the okay if the current one is taller than the previous one or if the current uh restriction is like it's lower than the previous one or if the other one is like they're the same blah right and then i guess it won't be a very easy implementation right so like i said so the first step first is that we have somehow update the restrictions to truly reflect the uh the limits at each of the label and then after that we can just use those kind of uh we can use that the two limits to calculate this difference and then also this kind of distance to calculate the maximum height right um so let's try to start coding you know the coding actually is not that difficult you know so first you know i will handle this kind of the special case which is the if there's no restriction at all so by the way since this restriction is kind of long you know i'm going to remove this one to make it easier so if there's no restriction at all so we all know we simply return a minus one right and then the second one is that you know since we're going to calculate uh the highest buildings uh by uh between each restriction we need to sort the restriction right from the smallest building from the first building to the last okay and then we need we're going to update right update the risk the restriction from both sides so what does this one it means that you know let's say we have a building right we're building like this and then we have like a building right in the middle right and then we have another building on the left side okay so at the beginning let's say we have a let's say this is two uh this is five maybe and then we have uh seven so at the beginning you know the limit for the restriction for this five let's say is this ten okay and then for the two here so for the re restriction two let's say the uh the limit of this one is seven no it's not seven let's say it's five let's say this one is five and this one is two plus this one is also five okay so what should be the true limit for this building five here if obviously it should not be 10 because we cannot simply build like a building at this location with height 10 because if we look at from the left side you know at the position two here we have a limit of five which means that you know the highest we can build at here is what is five plus three right which is eight because you know there are like three differences here there are five minus two is three so that's why you know if we look at from left side the biggest building we can build is eight and if you look at from the right side right so we also have five here but the difference is what it's seven minus two right so instead of eight it's seven in this case so which means that you know to be able to find a true limit for like symbol for like a specific building we have to compare we have to look at from both the left side and right side and there's like another edge case which is the uh anyway so let's try to implement that you know so first i would try to start from one to m okay so the m is the length of the restriction right so the restriction of i dot one right it's going to be the minimum of what of the restriction i'll just copy and paste this one of iron one of what of the previous one right after the previous one which is if we look at on the left side plus the difference right the difference between the current one the distance and the on the previous one right but there's like a azure case here you know corner scenario where the refer for the first one you know but since we're only starting from the second one you know for the first one we still want to make sure this one is also like compliant uh it's also updated so to do that we can do a little trick here we can simply append uh another element into the restriction which is the one zero right that's gonna be the first one actually in this case we'll make sure the first restriction will also be updated so that's from the left side and similarly from the right side right so from right side i can simply copy and paste so instead i will just do a m minus two minus one and the minus one all right so this one similarly uh i'll just do a i plus one right and then this one is i plus one minus i in this case right so after this one we'll have like for each of the buildings we'll have the two uh limits and then i can simply just update the final answers by doing this right one to m right so we have id one right so the first one is id one and then we have a uh limit one right limit one is going to be the restriction right of i minus one that's going to be the first restriction and the second one is the id two and the limit two is going to be the restrict restriction i right and then the answer will be the maximum of the answer right dot what we can handle two cases here you know because this l1 l2 one it could be either this one is higher or this one is higher but regardless which one is higher we will always use the one who is higher to get the uh as a base that's why you know we can simply do a maximum of h1 dot h2 right actually so we have a we have distance right so distance will be what would be the id 2 minus id 1 right so this is the distance between those two restrictions restriction buildings and then we have what we have the uh we have the difference right so the difference this is the height difference actually so height difference right so that high difference will be uh absolute of l1 minus l2 right and then we'll have the remaining right so the remaining means that we have the remaining a distance that we can use to build like a higher heart building in between right just like how what i said right if we have two buildings right so after subtracting this one is going to be the distance minus the height difference right after bringing the lower building to the uh to the same height we have some remaining distance we can use to build like higher buildings right like building this triangle right so that's why you know we can simply uh plus this one plus a remaining divided by two now since we're building the triangle right the highest building we can go is just a half of the distance because after going up we have we still need to uh the same we need the same distance to come down right yeah so and then we simply we can just return the answer in the end but i think there's still like a corner case we haven't considered which is the last restriction right because uh after the last restriction you know there's a this could be another scenario that you know the highest buildings exist between the last restriction and the end right so let's say this one is the last restriction and then we have a n minus one we have an n in the end in here because between the last restriction and to the end we can always keep increasing the length the height until we have reached the building end right because there's no restrictions after the last one that's why we have to also consider that one so to do that um in my case i simply just do another max comparison in the end basically for the last restriction between the last restriction and end i just do this right so the base is the last restriction right and one right that's the limit for the last one and then plus the n minus the restriction minus one zero right basically this one is just that calculate the highest building we can get after the last restriction right and then we compare that one with the answer and there you go i think that's it right so if i run the code yeah l1 out l2 here limit maybe i'll use height one h1 h2 this is easier i think okay yeah there you go right so time complexity obviously we have we only have one sort and then some parallel uh for loop that's why it's unlogging right no it's not unlocked actually it's m log m right n is the total so total like nodes but our complexity is the length of the restriction right times log m yeah that's it i mean this one you know the uh the solution isn't that hard to come up with the hard part is the uh how can you how can we handle all these kind of noises the about this kind of restriction and all different kind of scenarios right cool i think that's it for this problem and thank you for watching this video guys stay tuned i'll see you guys soon bye
|
Maximum Building Height
|
minimize-hamming-distance-after-swap-operations
|
You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109`
|
The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance.
|
Array,Depth-First Search,Union Find
|
Medium
|
1308
|
1,624 |
hello and welcome to another video in this video we're going to be working on largest substring between two equal characters and in the problem you're given a string s and you want to return the length of the longest substring between two equal characters excluding the two characters if there's no such substring is turn negative 1 and a substring is a continuous sequence of characters within a string so in this first example the optimal substring is the empty string because the two characters are over here and in second an example there are no duplicate characters or actually no there are sorry there are two A's so the optimal substring is BC right in between them so that's two and finally in the last example there are no duplicate characters so you want to return negative one so let's say you have a string and we're going to draw it um with an array so let say you have a string like this and we'll have some characters so let's just say we have like a and a over here or maybe let's have an A over here a b c a c b d a c right so there's a few ways to do this one way is to just kind of like do a Brute Force like you just start at this character and you literally just go to the end right so we can just be like okay let's start here and let's find the last location we don't even have to find the last location of a we can just go from whatever character we're at we can go to the end and we can just check like okay is that the same character if it is how long is the substring between those just by using the NC so in this case it would be like a substring of length zero and we check here is this equal to a no let's move on is this equal to a yes calculate the length here and then keep going all the way to the end then you start the second character and you do the same thing so you start this a and you just keep going like you know every character then you go to the next character and you go from that one all the way to the end and that's going to be like an N squar solution right so essentially start at every character look for a matching character figure out the link that substring and just return so that's fun way to do it um the better way to do it though is actually to pre-compute these ahead of time so what pre-compute these ahead of time so what pre-compute these ahead of time so what you can actually do it's going to be pretty simple is you can just have a hash map and this is pretty common type of problem where you we need to know like the first and last location of a character in a string right so we just want to know like where's the first location where's the last location and then we could figure out how long that substring is in between so the way to do that is pretty straightforward you just Loop we can kind of demonstrate this as well we so we can show this and then we can have like a dictionary so essentially whenever we find a letter like here we're going to say okay we don't have this a before so we're going to store it in our dictionary and whenever we find a letter and we didn't SE it before we'll just have an A tle of or an array of two numbers right its current index and its current index then if we find it again like here we see we do have the key of A before so we found it again so we can just remember we want the start and the end index so the start index will always stay the same and then anytime we find a character that we already have we can just update the end index to the current index we'll update this to one then we'll keep going and we'll say okay we don't have a c so let's add a c in here so C with remember start index will be the same then we keep going D we don't have it in here yet so let's add in a d so 33 a we do have an A so let's update that a end index to four C we do have a c let's update that to five a we do have it so let's update that to six C we have it so we're going to update it twice so after both of these it'll be eight and finally B we don't have it so let's put it in so B will have now we basically have an array of 26 characters m maximum right no matter how long this is or we have a dictionary of 26 characters maximum which is great for space because this can be a billion characters we'll still only have 26 characters maximum and every character will have a start index and end index then we just have to go through our characters so for example these are our characters right so let's make this a little bit bigger so let's say we have we don't even care about the character we really just need to start and end index for all of them so let's say our star and in index for a is 0er and six so how long is the subay between these two characters and so we can take a look so 0o and six is here so the sub array is here so it should be five right so basically you can kind of work this out the way to get the subay between the two characters is end minus start minus one right so if you have these two then this is five let's say you have something like these two this would be 8 - 1 - one which would be six which is - 1 - one which would be six which is - 1 - one which would be six which is six characters and so on right and the nice thing about this is if our start and end are the same let's say they're like two and two when we do this we will just get negative 1 right 2 - 2 - one so just get negative 1 right 2 - 2 - one so just get negative 1 right 2 - 2 - one so we'll just get negative 1 then we simply go through all of our values and we just maximize this so for this will be five right n minus start + one this will five right n minus start + one this will five right n minus start + one this will be five or sorry n minus start minus one so you can write that down n minus start one so here um yeah we will get five then here we will get negative 1 and here we will get negative one and we just simply maximize right we go through all of our values we maximize TR one it's going to be these two are going to give you the maximum and it's going to be five so that's kind of how you do it um pretty straightforward you just need to recognize I need to find the first and last index of a character in a string because the first and last index of every character will give me the biggest possible subarray with that um W with the substring in between those characters right like if an a occurs here and a bunch of other places to get the biggest substring in between a is you want the leftmost A and the rightmost a which is the first and last occurrence of the a that's pretty much it and let's code it so we can just have like locations or something loocks and we'll just say for um we can enumerate this so for index value in enumerate s if the value is in here already then let's just update the end index so we'll just say locks value one let's update that to be the current index and if the value is not in here then let's put in at the start an index and the same Index right so like here it'll just be I think I need to tab this there we go so now finally we're going to have a dictionary of start and end locations now we just need to go through and maximize it um yeah you could do this in one line so I'll do the like normal solution then I'll show you how to do it in one line I think you can do it in one line anyway so normal solution is just make a result go through all the values so we can just say like four start end in locks values right so all the values will be these two PS we don't really care about the character we just care about the values and then just maximize the result here so we can just say result equals Max of result and end minus start and like I said if a character has the same start and end Index this will give you a minus one so that's fine because we do want to return minus one if there are no duplicate characters this will Auto do it for us so you can return result here I think that should work see where we have invalid syntax so it's because this so this should be zero uh let's see oh n minus start minus one okay here we go so this does work um the efficiency is kind of all over the place so um so the way to do this in one line just if you're curious about python syntax is you can do this so you can say return Max and then we can just get a list comprehension here so I think we can say like uh start or sorry it be like this be like n minus start minus one for I think you can do something like start end in locations. values think that'll work so you basically get a array of all of these values um and then return the max value so let's see if that works there we go so that also uh yeah that also does work if you were curious about doing one liner either one of these is fine okay um yeah so let's do the time and space for this one uh so this is going to be essentially We're looping through our string once and then we are looping through our characters but because s is only lowercase characters looping through the characters is basically going to be constant time because there's only 26 character Max like this can be three billion this will still be this part will be o of one so I'm going to say this is o n and the space I'm going to say is 01 just like in my previous videos because there's only 26 characters Max you could say o of like different characters if you want it to get more specific but I'm just going to write o one because there's only 26 characters so the string can be billions and whatever trillions of characters and our dictionary will still be only 26 so yeah I think that's going to be all for this one so last problem for the year so hopefully you guys enjoyed that one and if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
|
Largest Substring Between Two Equal Characters
|
clone-binary-tree-with-random-pointer
|
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "aa "
**Output:** 0
**Explanation:** The optimal substring here is an empty substring between the two `'a's`.
**Example 2:**
**Input:** s = "abca "
**Output:** 2
**Explanation:** The optimal substring here is "bc ".
**Example 3:**
**Input:** s = "cbzxy "
**Output:** -1
**Explanation:** There are no characters that appear twice in s.
**Constraints:**
* `1 <= s.length <= 300`
* `s` contains only lowercase English letters.
|
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
133,138,1634
|
1,802 |
hello everyone welcome back here is Ben Hampton and today we will tackle another daily challenge from this code maximum value at a given index in a bounded RI and let's dive in the problem asks us to find the maximum value at a given index while also adhering to some specific condition the goal is to construct an array of positive integers wherein the sum of all the elements does not exceed a given maximum sum and the difference between adjacent number cannot be greater than one so to tackle this problem we are going to use combination of greedy approach and binary search so in our code we Define a helper function get some that calculates the minimum sum of the array given a specific index and value and we compute the sum of both left and right side of the index for each side if value is greater than the distance to the boundary it forms an arithmetic sequence otherwise it form a sequence ending or starting in value and a sequence of one so we need to remember to subtract value on the end so uh first defined get some self index int value in and count zero and now compute the sum on the left of the index if value greater than index if the value is greater than the index it form an arithmetic sequence so count plus Value Plus value minus index times index plus 1 divided by 2. and else otherwise it form a sequence ending in value and a sequence of one so count plus value times divided index Plus 1. okay so compute the sum on the right of the index so if value greater than n minus 1 if the value is greater than the distance to the and it form an arithmetic sequence so count plus value minus and index times 1 divided by 2. so else otherwise it form sequence starting in value and sequence of ones so then we use count plus Value Plus One value divided by two plus index minus value so then subtract the value as it was added twice in the above calculation so return count minus volume so this is our helper function and now let's move on to the core function of max value so we initialize search space with left and right pointers and we then perform a binary search checking if the sum with the current middle value doesn't exceed the maximum sum so if the sum doesn't exceed the max sum we moved the left pointer to Mid if thus we move the right pointer to Mid minus one and this way we are continually narrowing our search space until we find the maximum value that meets our given criteria so let's code it so first we initialize left right 1 Max sum and perform binary search so while left less than right mid left plus right plus 1 divided by 2 check if the sum with the current middle value doesn't exit maximum so if self gets some index meet and less than Max sum if it doesn't move the left pointer to Mid so left meet else if it does move the right pointer to Mid -1 -1 -1 so write equals mid minus 1. and return the maximum value that meets the criteria return left yeah and here we have it so this is our implementation of this algorithm hopefully it will work so it's approach with uh great approach including binary search so for test cases yes so for example if we have input N4 index 2 maximum six so output yeah correct as two and that's it with this approach we can efficiently solve this problem and to remember key here is to understand how to use binary search to our advantage and also working out with arithmetic to calculate the sum so let's run it for unseen test cases yeah so for unsynthesis cases we also passed and completion stack day 12 so stick yeah and our implementation beats 29 and with respect to memory 53 so all good and I hope you found this video helpful if you did make sure to hit that like button share it with your friends and subscribe for more coding challenges and tutorial and solutions and until next time happy coding
|
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
|
783 |
Hi gas welcome and welcome back to my channel so today our problem is minimum distance between BST notes so let us see what has been given to us in this problem statement, here what has been given to you, root node has been given without one. OK, so what we have to do is to return the minimum difference between the values of other two difference between the values of other two difference between the values of other two different notes in the OK, so what do we do? Let's understand this through an example. What have we given here? Without research tree, the root note of binary has been given and what we have to do is to find the minimum difference between any two different notes. It is okay, so here if you do not want to see this in the form of a trick, it is given in the form of It would have happened if you had been in the form of Eric 2 4 3 6 1 This element is here right here 2 4 3 6 1 These are given Hey If I would have told you to find here the minimum between any two numbers Difference So what do you do? Compare the H element with each element. Okay, compare it with this, see how much A is there, compare this with this, then do this with this. Meaning, wherever you find the minimum, finally you compare them all and find the difference and wherever you find the minimum, you return it. It is okay if this is the order you were getting in sorted. If it was yours in sorted then how would you find it. Let's see what will happen in such a situation that you will compare this element with this element, that is, what you will have to do is solve this problem on square, if this is yours, what is yours is sorted, that is, 1 2 3 4 6, then you How will you find the difference, then you will compare this to this, here you will get WAN, okay, will you compare this with this or what will you do with this, what will you compare, what won't you do, why won't you because look because we know that this is sorted if this is between this Which will be the addition element, will it be less in the difference between these two? Today, if you are compared with all these, then we will find the difference of these two. We just need to find the difference of these two elements and find the difference of these two adjacent elements. Then there is a need to find these two adjuncts. There is a need to find these two adjuncts because both of them are adjuncts and the difference between them can be less. So let's see what is coming out here. A van is coming out here, a van is coming out here too, and the difference between these two is that you are coming out, so minimum what is the van coming out here? It is not given here. Now see what we have seen. So we have given binary search tree. So in binary, what can we get in sorted? What can we get in sorted? When we do these order traversal, what do we get in binary tree? This is found in your ascending order, see how, what will you do here, how to do these orders, we first start looking from the left, look and then see if it is left, then move towards the left and then see if it is left. Is there a left then where does it go to the left? Now we know that there is a tap, so we come back, so now we come to the middle, now look what is there, look at the left side, then look at the note, then look at the right side, in this way we If we have to do it then we have seen the left side, now we will see the middle of it, when Meet says, we will see the note, what is the van, then it will be the van, it is ours, then the right side is down, you got its tap, then from here you come back because you visit the van. Now you are visiting the left side of it. You have done it. Before this, what are you doing now? If you are visiting this note, then what will happen here, you will write it here, okay, then you will go towards it now. If its left is left, first look at its left, then go visit this note and write this note here, okay then go to its right, first you left, then do the note and then right of it, you visit and then come back. You have visited it totally left side right side and now if we go here then what has happened to the left of this note, what has happened to the right, now if we go here then the shop of four has gone left, after left now I have to see the note. So what happened to our note, here it will be four, okay then we will go to its right side, so there is six on the right side, what have we seen of six, if we have not seen the left, then we will go to the left side, if there is a tap on the left, then we will come back to this note. Will visit and will write here then go to the right of this which is tap, so we will come back again like this, what we do is order these here, so look at yourself, did you get it, did you not get it like this? If we get it in the order, then what do we have to do, we have to sign the difference, when we look at one side, here we just have to find the difference of these two, we have to do 23, then we have to do 34, we have to do 46 and In all these we have to compare where we have got less, okay so what will we do in this way, if we solve this problem, then what will we do in this, how will we find the difference, so like you will move from here to here, okay? So what you will do is take an element here, log answer in which you are going to update the answer that the final answer will be yours, will you take this as initial, this is the max of log in max, it is ok now and we will keep one as previous, if we say previous then what is here? First, let's take -1, okay, so -1 for this, previous First, let's take -1, okay, so -1 for this, previous First, let's take -1, okay, so -1 for this, previous -1 for this, -1 for this, -1 for this, previous this for this, because what we have to do is if here, what is the previous of this, then their difference. We have to find, when we are here, what will be its previous, now we will find its difference, when we are here, what will be its previous three, then we will find its difference, when we will be here, then its previous four, so in this way we We will find the difference and in this case we will take the previous man -1, so in this case we will take the previous man -1, so in this case we will take the previous man -1, so in this case we will not find it. Okay, we will skip this case. We will keep the condition in such a way that both of these are running on the previous man -1. What will we are running on the previous man -1. What will we are running on the previous man -1. What will we do if we don't find it? Okay, so what will we do? First, we will visit the left side from here, that is, if we order these, we will go to the left side, then we will go to the left of this, okay, now here you have got the tap here. What have you got? Now that you have got the tap, what will you do with us? We will not go back otherwise we will take the man who is the previous van, what is the previous one now? If we have -1 then we will previous one now? If we have -1 then we will previous one now? If we have -1 then we will not find it but we have come on this note. So what to do, update this note from van to the previous one, okay, updated it, then go to its right side, tap on it, come back, okay, then go here, we have visited the left side of it, now in the middle of it, i.e. this If we are visiting the note, in the middle of it, i.e. this If we are visiting the note, in the middle of it, i.e. this If we are visiting the note, then before visiting this note, we will see what is its previous, is it not -1, is it not -1, is there anything other than mines van, not -1, is it not -1, is there anything other than mines van, not -1, is it not -1, is there anything other than mines van, okay, then we will understand that we have its previous and we If we have paid Rs. Is it more than this answer ? Is it more or less? Then we will ? Is it more or less? Then we will ? Is it more or less? Then we will update it. From van to van. Updated from van. Then what will we do with this note. Now we will go towards this side. So we will update it. Tu se ok hai tu se humko. We will update it, first we will find the answer, then we will update it with you, then we will go towards its left side, now what do we have to do with it, we have to visit its right left side, we have gone towards its right side, so we have to visit its left side first, which is It is null, we will come back, now we will visit the note, if we visit 3, then before visiting 3, we will check whether it has any previous, is there anything other than -1, is it han hai tu hai, so anything other than -1, is it han hai tu hai, so anything other than -1, is it han hai tu hai, so what, find the difference of both, then 3. And if you find the difference of 2 then you will get 1. If there is already Van then Van will be the answer. I am yours, this will be 1st April and we will also update the previous one. From three, now we will go to the right side of it, tap this is back. We have visited it will come back from here, it will come back here, so what have we done with four, it has visited late, now we will visit it on this note, four is the previous of four, we have kept three, so these two We will find the difference. First we will find the difference. Van will be the answer. If you do 100 in the answer, if you already have van then let it be. Now what will we do? Now we will make four on the previous here. Now we will move towards six, so the one on the left of six is the null, so the one on the left of six is the null, so the one on the left of six is the null, this is back. Now we will visit this note, if it is six then it is 6 - 4, will you is six then it is 6 - 4, will you is six then it is 6 - 4, will you update it because it is more, what do we have to do, if we want to find the minimum, then we will be paying the minimum here, so the van here is less than before, so let's use it. Let's also check the diary. We have finished visiting all these notes and what will we do with the final answer in this answer. What will we do with it and return it. So I hope you have understood what I do now, let me show you the code also. Look. What is this, what have we done here, it has given us a minimum difference in BST, we have given this function to ourselves, okay, in this we have given you the root, what we have done is by calling a solve function and turned the answer here. So, here we have taken the answer and the previous, we have taken the previous as mines van and we have taken the brick max answer. Okay, now let's see what we have done in this question function, so whenever our route is null, we will be back. We will go to the previous function and vice versa. We will keep moving towards the left. Okay, so we will check whether the previous one is our -1. If whether the previous one is our -1. If whether the previous one is our -1. If not, then find out the answer. How will you find out the minimum answer which is the previous answer among the two and which we are going to find? Which is the minimum among the two, it will be updated in your answer, so how will you find the root value - what to do with the previous value which is your value - what to do with the previous value which is your value - what to do with the previous value which is your previous value, min it from the current value, then the minimum which will be updated in the answer and you will get the previous value. You have to keep updating, if you move properly from the value of root, then in this way your solve function will be damaged, then finally you will return the answer that you will store in it. Okay, so I hope you have understood this, if you liked the video. So please like share and subscribe thank you
|
Minimum Distance Between BST Nodes
|
search-in-a-binary-search-tree
|
Given the `root` of a Binary Search Tree (BST), return _the minimum difference between the values of any two different nodes in the tree_.
**Example 1:**
**Input:** root = \[4,2,6,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,0,48,null,null,12,49\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `0 <= Node.val <= 105`
**Note:** This question is the same as 530: [https://leetcode.com/problems/minimum-absolute-difference-in-bst/](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)
| null |
Tree,Binary Search Tree,Binary Tree
|
Easy
|
270,784
|
974 |
hello everyone welcome to question coder so in this video we will see question 974 that is sub array sums divisible by k so this question is a really popular question and it can be asked in an interview for coding interviews for like big tech giants like google amazon facebook so let's see so it's a medium question and it is also uh like media like question and let's see the problem statement given an array a of integers return the numbers of contiguous that means continuous all the indices are continuous non empty sub arrays so sub arrays is like if this is average that is given so sub array will be four five zero so no index in between can be skipped so that is continuous that have a sum divisible by k so as it can be seen from the question title also sub array sums divisible by k so we have to return the number of sub arrays that is we have to return the count of the sub arrays whose sum is divisible by k so in this example so you can see this is the example that we're given and here the k is five so the total number of sub arrays that are divisible by five you can see are seven so here you can see this sub this is also sub array so whole array can be also taken as a sub array so this is a whole array then this sub array and you can see all the indices will be common oh sorry continuous you can see five zero minus two minus three so this is a problem statement so it is fairly simple to understand problem statement but the problem is a bit tricky to understand so let's see so you can see the constraints also so length or the size of the array will be ranging from 1 to you can see 30 000 and 30k or you can see this array size also the elements of the range of the elements and then the value of the key so let's see how we can approach this question in an interview so let's see so the naive approach that you can think of for this question will be to check for all sub arrays and divide them by k and check if it is divisible by k or if the modulus of that particular sub array is divisible by k then we can simply increment our code so this name approach will simply use two for loops first we will maintain a result variable which we have to return then we will run two for loops so first of all i will run from here then we will run j from this point till n so it will check for till this point okay j will run for this then i will come here okay i will come here and then again j will run from i till n so it will check for all sub arrays so first it is set here okay j is here at i j is at zero so we will add it to some sum is zero so we will try to modulate take the some modulus k so if it is divisible by k then we will increment our result if it is not we will incremented j so he will keep incrementing for every i j will keep incrementing and it will calculate the sum of all the like sub all the elements from i to j and then we'll check if it is divisible by k then we will simply increment our result so this will be naive approach so it will take o of n square time and space complexity will be o for only because we are just maintaining some variables we are not storing anything we are simply maintaining the variables that we have to written so this is a fairly simple approach but it will not be uh it will not get submitted on the lead code or any platform but the interviewer will be happy to see that you have paid the brute force approach now you he will ask you to optimize it further and to submit on neet code also on the platforms also you will have to optimize the solution because n square is uh easy approach and it cannot be submitted uh very simply so let's see the approach so here as you know we have to find the sum of the sub arrays so we have to find the sum then divide them by k so to find the sum we need to we can use a prefix so it is also called as cumulative sum so it is actually if we this is our array these are indices to do to find the sum to that particular point what we can do is we can maintain a prefix sum or a cumulative sum so it will be actually this at this point you can see at this zeroth index sum is four yeah it is two now you can see at this index so sum is at first next sum is four plus five so it will be actually you can see this four plus this five sum that at this point and some uh the current value that it we have so it will be nine now if you see here current uh sum at this point will be actually four plus five plus zero so it will be given by this sum that is till first index and the current element that is zero so it will be nine now for this it will be seven you can see nine minus two so here nine seven minus three it will be four now here it will be five you can see and calculate the whole sum so that at the last you can see this five is the sum of whole array that we are given so this is what prefix sum is and now as you know we have to find the divisibility so we have to find if it is evitable or divisible by k or not so what we will do is we will simply instead of storing this as it is we will store the remainders of this so we will calculate the modulus of that value so to calculate the modulus we will use the k that we are given so you can see the modulus here that we are given is k so let me write it so k is 5 actually so 5 you can see in this example k is 5 and this is our array that i use in this example also so at every point at every prefix index what we will do is we will keep or write the modulus of that value so 4 modulus 5 will be actually 4 only if the value is less than the value that we are using for taking modulus if it is 4 actually you can see if this value is less than this value that from which we are taking modulus so it will be simply the answer will be that value only four so it if it is less than this five so that is four okay so here for this nine the modulus will be again four or four because you can see you can you know that if we divide 9 by 4 so the middle 9 by 5 that is k so our remainder will be 4 because if we will divide it by 1 so remaining would be 4 so that means this current value will be 4 okay now at this point again 9 modulus 5 will be four at this seven modulus five will be actually one so it would be uh if you see one then two will be left two will be coming here then if you see this four so four modulus five again it will be four now eight at this point five divided by five or five modulus five will be zero so these are the modulus value that we are showing and why are we storing the modulus values as you know we have to find the division if it is divisible by k or not to do that we will use the modulus we cannot use the sum so we instead of storing the sum we will use the modulus values we will calculate the sum and their modulus value and we will store them and use them and now why we are using this modulus or if you don't know what is this modulus actually if you see if we divide because 9 is you know that 9 is not divisible by 5 but if you divide 9 by 5 you can extract a 5 from it and 4 will be remaining and 5 is the multiple of 5 so actually if you are performing a modulus operation on a particular element with some other element then this element will take out all of its factor from this number and the remaining that will be left is not the factor of that number so the element that will be left is 4 now if you try to divide 7 with 5 okay so you can divide 7 by 1 okay 5 by 1 you can see so it will be actually uh minus 5 okay minus 5 then output will be 2 so that means we have taken out 5 which was divisible by 5 and the remaining value is not divisible by pi that means we have taken the multiple of 5 from that particular element that we are dividing with 5 so that is what our modulus operation is now why we are using this modulus if you see here the values are coming same you can see four and this is where our output will lie so this is why we are using our modulus so at this point you can see this four okay this is a four value so it is not divisible by five so that means our if we are maintaining our answer so we will also use we are using prefix sum and now to maintain or to maintain the map or to maintain the occurrences of frequency of these modulus we will have to use hashmap so hashmap if you don't know hp is actually simply a key and value pair so if key is one so though its value is so it is actually a key a value pair so in this okay if we try to make a hash map so for this four will be our key so we are maintaining the remainder as our key and its occurrences at frequency at the last if you see at the last this frequency of this map will be actually four you can see four occurs four times so its value will be four so this is what we are doing and now how we will you be using this hash let's see so at this point you can see this four our answer is zero okay our answer is zero at this point if you see four is not divisible by five so that means nothing will happen so if you see here again four is coming a k in four is coming that is when we are adding this value also then when we are adding this five value okay so output is nine so that means nine was here and when we okay four first four was here okay when we try to modulus it with five so nothing will happen four will come only four will come okay when we add five to four that is next element so it becomes nine so if we try to do nine modulus five as i told you five will extract all its factors so its factors will be extracted so the meaning will be four so that means there was a multiple or there was a sum which was divisible by five that's why nine is not there becau but four is there so and we will check in hash map we will be storing our value so first we will show zero as the first key value pair because there will be a point where like if you see in this example let me tell you if you see the this some of the whole array is 5 so that is also divisible by 5 so it is 0 is occurring so that means we will use it afterwards so before you have to show this 0 and 1 okay 0 is the value and this remainder and this is the pair or the frequency of it so now if you see at this point when we were here there was no value 4 in the map so we will maintain 4 value and we'll set its value to 1. when we come to this point you can see this 4 now if you see this 9 is divisible by 5 but 4 is remaining that means 5 is extracting its value and 4 is again coming so when at a particular point here if 4 is coming and again 4 is coming okay after adding some values also these are the values and we are adding this value so here you can see 4 was here when we added 5 again we were model taking modulus of 5. so 5 was extracted so that means this 5 had no change on the sum that we were using so again the sum remained 4 only so that is why we will now you can see the occurrence of four is one so our output will be actually four plus okay four plus the answer so answer is zero so you can see the output will be one at this point we have our two sub okay one sub array whose who is divisible by five and how is that you can see a result will be one so how is that as i told you if we get same value same values that means that the value that we added to the particular point had no change because we took the modulus of it so it got extracted so there was no change to that means there was a sum which was divisible there was a sub array which was divisible by five so that is why we took five now if you see in this area that we are given so if we take five value so 4 is not visible okay 4 is not invisible if we take 5 so 5 is divisible by 5 so it is also one of the sub array you can see here you can see this is also considered as one of the sub array and our output is one at this point and this is true so i will explain you or more with the algorithm actually so let's see so uh this will be okay this is the same example and this will be the algorithm that will be we will be using as i told you for calculating the prefix and we will have to use the array so why not we don't require this er actually because we are not querying anything we can simply maintain a variable which will be like we can maintain a variable sum we can enter a variable sum which will be having the total sum till that point so until this point some will have value four okay till this point some will have value four plus five that will be nine okay till this point it will be four plus five plus zero so it will be nine so why not to simply maintain us some variable instead of maintaining an array which will also optimize the space complex complexity so this will be one thing that we instead of calculating prefix some uh in the sub s array we will simply maintain a variable so you can see this is our variable that will be using for calculating the prefix sum and this will be the result that we have to return and we will have to initialize map also so at first we will add a key value pair in the map so if our map is uh here i am letting the map so the value here is 0 and 1 is the frequency of that 0 so it is 0 okay now we will traverse over this array okay we will traverse over this array and we have some variables here so we can see we have some variable i will write it as s and the remainder variable that we will be using to calculate the remainder at first point i is here okay i is at this one so it is 4 so value is 4 now if we will add it to sum so it will become four now if you take four modulus five so four modulus five will be actually if you try to write i will write here four what is model five will be four only so the remainder will be four so remaining will be four so it is not in the map as you can see it is not in the map so i will write the map here instead so 0 and 1 so 0 and is the value and 1 is the frequency and 4 is not there in the maps that means there is no sub array which is divisible by 5 to this point so we will add 4 here or 4 here as a key and its frequency as one because it has not occurred before so it is second now so the frequency is one only so now frequency is one now i will increment okay i will increment now you can see this uh thing nothing happened here okay so remainder people also i will tell you so i will increment now i is at this point now our sum is okay our sum is let me erase this 4 our sum is 4 at this point and 5 will be added so sum will become 9 now if you take 9 out of those 5 9 modulus 5 will be 4 again now if you see when we come to this point okay remainder is not less than 0 e this condition is actually if remainder at any point gets less than 0 so we will simply add remainder plus the value that we're dividing it so it will become positive again so remainder should not be negative as you know you this is a basic rule so here you can see this condition if remainder in map so that means the remainder 4 is in map so this is our map you can see this is our map and yes remainder value 4 is in our map so that means this 4 has occurred again so that means we added some value in between bit in between some value was added from this point to this point which was divisible by 5 and it was extracted by the modulus operation that means there is a sub array which is divisible by five so what we will do is now you can see this is in map so yes it is in map and we are maintaining our result variable so our result variable is zero now for now it is zero so now we have to add some value into it to maintain the count so it will be actually the frequency of the number of fours it has occurred so you can see it is one so that means four has occurred one time now again four has occurred so you can see so there is one sub array only between them one sub array is there as frequency of 4 is 1 so simply our result will increment by the value of so this m remainder is the value of 4 so map is this okay and remainder is 4 so its value will be 1 so our result will become 1 it will be incremented by 1. so now whatever result is one and when we are incrementing to next index we will increment uh if it is not maintained as i told you when we incremented to this point this file we added this phone into the map if it is already there in the map so we will simply increment it you can see m result increment so it will be incremented so now it will become two here okay it will become two let me it is this and right so four is four has occurred two times so i hope you are understanding so now you will get more uh clear uh example now let's see so now when our i comes to this point you can see now here we have found a sub array you can you know that we have found our sub a result is one and this is true you can see this five is the sub array that we are having it is divisible by five and when we come to this point zero so if we add this 0 into 9 it will remain 9 and our remainder will remain 4 so here our value and this maps is you can see 0 has occurred one time and 4 has occurred 2 times now if you see this 0 has this 0 as came now what will be our result so you can see this is a remainder is not less than zero so this condition will not rule but the remainder is in map so what value we have to add so it if it is in map we will simply add that value so it has occurred two times so our current result is one so one plus two will be three so at this point our result is 3 the result is 3 at this point the current value that we were having in the previous result was 1 and the frequency of the 4 if it is there so modulus remainder is there you can see this remainder is in the map so it is full so its frequency is two so two plus one will be three and now five or how we can we have three sub arrays till this point let's see so if you see carefully in this example so first sub l is this five okay this five that we were having in the result now when we added this zero we added two more sub arrays and how is that if you try to see if we added five zero okay five is zero so five by zero five plus zero will be five only so it will be still divisible by five so that means we have got one more sub array we were having one sub array as five and now we have got one more sub array that is five comma zero and now when you add okay this five form zero was added now when you see when we add the let me raise this so instead of adding five there if you see this zero so zero is also divisible by five zero modulus five will be again zero so our output is zero so that means zero is divisible by five so this will be the our next sub array so let's see so yes you can see this zero is here you can see this five we have got three sub-arrays sub-arrays sub-arrays now you can see five zero and this zero so you can see this zero so we have got three sub-arrays so that means our three sub-arrays so that means our three sub-arrays so that means our result is correct now this point our result is correct our result is three actually so that is correct so let me write also so this video is actually getting longer because i am trying to explain you clearly so let's see so obviously that till now that we have got our five comma zero you can see and then we have got our zero as a sub array now let's see now where i comes to this point this minus 2 our sum is 9 so it will become minus 2 so it will become 7 so now sum is 7 and our remainder is 7 modulus 5 which will be 2 as you saw in this approach you can see in this example it was 2 so our remainder is 2 5 divided by okay so let's see so who is not in the map so when you come here so okay we have calculated the remainder is not less than zero nothing will happen now if we will check if remainder is in map so it is not in map so that means mary is no sub array which is divisible by five till this point so okay we have uh there is only five sub arrays so now we will add when we go to next index before going to next index we are adding this value you can see this value so two will be created okay two will be created and it has occurred one time so its value will be one two second one time so that is what it is so now when i increments to this point it is minus three so now if you see minus three uh seven minus e so it will be again becoming four so when you get four so okay four modulus five will be four only so our remainder is 4 so now if you see this 4 has occurred 4 has already occurred in the map so force value is at this point is 2 you can see it is 2 so now sorry i forgot something like yeah here we incl we didn't increment our value here so force value actually is three till this point it is three let me erase this because you know it at this point it was four okay at this point also modulus and nine out of the five was four only so again nine uh here nine more to five was four only so four has occurred three times so the map value in this map is four only so let's see so now when we come to this point so this four has occurred in the map so that means there is a sub array like here it was four now again here it is four so that means there is a sub array which is divisible by five and which has been extracted by the five models operation modulus five operation so that means our value will be again incremented so current value is three current result is three till this point so four is four value is in this map is three so three plus three will become six so that means our result will be in change so our result has become six now we have found six sub arrays till this point let me do this we have found six sub arrays till this point who are divisible by five and let's see who which are those sub arrays and this point till this point we have found no sub array okay till this point we have found no sub array because this sum was nine and nine minus two was okay seven which is not divisible when you subtract this 3 from this 7 so we get 4 so that means there is some sub array so let's see so you can see here the sub array will be actually this once a variable will be this 0 minus 2 and minus 3 so it will be actually minus 5 so minus 5 modulus five is zero again so it is divisible so that means we have got one sub array at this point and now if we don't include the zero we simply include this minus two and minus three so again there is sub array which is divisible you can see so this is how we are finding the sub arrays so till this point we have found more sub errors so let's see in this also so we can see this five zero minus two and minus c so we have found this sub array okay you can see the i have told about these sub arrays first is zero okay then zero plus uh this zero plus let me erase this again i will write them up here so let's see so we have found more than three sub errors as you know we have added three to this current value for three and we have added map value three again so the sub hey value now new sub array is actually 0 comma minus 2 comma minus 3 as its sum is divisible by 5 and now the another one is minus 2 and minus 3 it is also divisible by 3 and the next will be minus five if you add minus five oh sorry five okay then zero then minus two and then minus three so if you add them so again result will be zero the models will be zero so that means it is divisible so we have found six sub arrest and now you can see and the result is two so it is two or six so that means it is correct so now when i comes to this point it's one so one will be added to this four so it will become five and five modulus five will be zero so that means five is not occurred here yeah five has not occurred here but if you see the modulus 5 so modulus 5 we are checking so it is 0 so 5 0 is here so yes 0 is here so that is why we stored this 0 so if our whole sub sum of whole sub array is 0 so we will simply use this value so it is one so one will be incremented in this one because zero is in the map that we are maintaining so six plus one will be seven so that means we have found the seven sub arrays so the next value these are the six sub arrays and the next sub array will be the whole array four five zero minus one and minus three and one so the time complexity for this solution will be actually simply o of n so as you know we were using of n square in this solution neighbor approach but here we have optimized the time complexity of n by using o of n space also so this is a bit optimal solution than previous solution so let's see the code also for this solution i hope you got the solution and how we are using the remainder operation and the hash map okay so let's see so first you can see i have initialized a map then i have initialized some variables some result and then size of the l so then i've added the zero and one value to the map that means zero remainder and its frequency one and then we will traverse over the array and we will keep adding the every element to the sum variable that is using our prefix sum so this is actually prefix sum and we know we don't have to use the sum actually we have to use the remainder so we will calculate the remainder some modulus k is the value that we are given and we will check if at any point meter gets less than zero if you simply we will simply add k or the value that we are using to divide to the remainder this is the basic approach so actually if you see it this is the main algorithm so we will check if this value that remainder has already occurred so if it is not there if it is not equal and actually you can see m dot find is not equal to n so if in c plus if it is not equal to n so that means the value exists so if it is not equal to n that means value has existed so that means here if four was coming let me erase this all so here if four mod four was coming okay if here four has came and again four modulus has came so that means four was there in the map four value for one was there and again four has come that means there was some value in which uh which it didn't contribute to the sum so it got extracted by the modulus 5 operation so that means there is a sub array which is getting extracted so simply we will add that value that frequency at that point to the result so at this point okay the frequency will be 2 at the if you see if we see the starting point is here okay when we are at this point our map contains four and two value so when we see four is already occurred our result is okay one so we will simply add this two to one so that means we have got three sub arrays and how is that you can see five and then you can see five and zero and then zero so these are the series are better so this is what we are doing and at every point we will increment our value or we will add the value if it is not there in the map that we are maintaining and we will return the result at the end so let's submit the solution so i hope you got the solution if you have any doubt you can comment down below and i will surely ask your i will answer your doubt so let's hope for the best so you got to understand this so thank you for watching guys do let me know if you like this video and do a subscribe channel and like this video for more such videos thank you for watching
|
Subarray Sums Divisible by K
|
reorder-data-in-log-files
|
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104`
| null |
Array,String,Sorting
|
Easy
| null |
454 |
Ajay has been robbed, so today we are with aapke hain kaun question and the name of the question is for sometime list court question number four, emphasis is 1 medium sized question. Well, if I use it regularly then maybe it is not at the top but Chief, you will learn a lot of things in this question, if you understand it well, then a survey sample question, Akunth Adviser, this question has a little strength, Fragnet, happiness, only patience reads the question well, this given point, teachers, these four The interior is fine and friends, this is a little useful for us too, when it is about the shop, let us underline it a little and the length of the off plant and caring teaser is 'Hey in danger'. A letter written The number of 000 is the commell of is 'Hey in danger'. A letter written The number of 000 is the commell of is 'Hey in danger'. A letter written The number of 000 is the commell of Tycoon Mukesh Kumar Saubhagya Hai Idea number one index Is there any index about this What is that about this Is there any Akshay and Ad book about this Ko injection for pregnant you Just make such a temple on every quarter around these quarters. Follow these two properties. Now he will do these two properties. Just look carefully that your icon which is matching with Jack Ma's should be connected to the gang. End Size And the short and secret important question is the latest expert of those four, that the numbers entered in their respective addresses are a summation of all of them, that summation should be forced. Okay, as an example on one hand, if we talk about these four, oh my. Thoughts on Pass Tuesday Edison 1234 What to do now What should I do to get the number of stumps and output from it Whose number Gaurav So what is a couple One is successful Jio's MyJio is more than 160 in 100 index - Suggestion is 101 tax more than 160 in 100 index - Suggestion is 101 tax more than 160 in 100 index - Suggestion is 101 tax on minus here This is put on One Love Hai and Fast Remix, so if you take these four oaths, then how much am I getting by swearing on all four? If I am getting zero, then one is taken on quarter and the other is on quarter. 1510 test from here - from vest. 2.3 1510 test from here - from vest. 2.3 1510 test from here - from vest. 2.3 I have only taken part - I have only taken part - I have only taken part - 90 lakh test from the university - We will 90 lakh test from the university - We will 90 lakh test from the university - We will add the upcoming square from here and this same drama Q. What is the gift of adding all four, I get only zero, okay so some quarters in the purse. The point to be made is that if you sum all four of them, two, what do you get Reebok, four, you have the same size by clicking on the cricket players' first flower, cricket players' first flower, cricket players' first flower, mine is yours, even then we will put four cloves and four spoons. We will do it but friend, it will be very dirty that if no one advances in a question by sharing four cloves with someone then Noida Puja then brute force post is the same, it is ok but if we try to falsify this question a little in this way. Follow the property of the review so if you don't say this is plus B plus C plus B if it is giving you zero then okay you friend create problems, one thing I want you to notice and that thing is that these four problems are not found in any two Take out the time of ' time of ' time of ' Hey brother, what should be bar tasty plus b a must be equal to - of c plus d the print and you can write anything, okay one, we can make this question, second question what can we make second question with It may be something like this - A question with It may be something like this - A question with It may be something like this - A Plus C Request - Fennel Bean Placid On Tomorrow Cricket Panjiri Question I am understanding that A Plus Seats Nickel Two Minus B Plus B Cube These four are indicating all four prosperity so they are here There is some kind of intuition coming from me that if I could do something like this, if I pick up drs all around and I can do something like this, then care is the sum of these two and the negative of these two wires. I am getting the feeling that there is a thread there whose number is being changed. What should I say in the edit? By listening, I am picking up both these addresses, let's create a current account, both the addresses, and the husband will make all the appearances, then it will be fine if I take the oath. Have solved one minus two then the descent one foot how to now had started 1 that monsoon that what how to - 2 how to - 2 how to - 2 that what should I do I will make all the fairs of those that can be possible both addresses to mines that yours are like that - Vande's this will that yours are like that - Vande's this will that yours are like that - Vande's this will give zero, this will also give hero and this is closed. Okay, so these four Bellcoms are possible from these two addresses, now what will I do, now I will search them in this, am I able to create a tree which is negative of them? Even if we are A minus one, I have changed the color of the black color paint. Who is it? Which one is hydraulic and which one can you show? Okay, so I have made these two wires, will it remain in the correct kilos? Will it make it? Mix these two after making relationship - 110 003 Dh Now the day of these two is common S - 150 Dh Now the day of these two is common S - 150 Dh Now the day of these two is common S - 150 Miles - 54 Miles - 54 Miles - 54 So what is minus one plus two test one ok under Bluetooth plus0 test 2 and two plus two Front four, now what do you have, everything is there, you have something that you have till now, we have to see that when the time of address comes, these two are the remaining, then the time of address is taken, so what I have to see is that minus one and this plus one. You think both of them together will make you zero and there is another love when this one and this one - I don't feel like both are rich and will make me one - I don't feel like both are rich and will make me one - I don't feel like both are rich and will make me correct, so what do I have to do, is any indication coming from me, friend, I could have made a map. Okay, now I am yours, I got homosexuality on the value of yours here and the value that was done on here. So I if you I am a cup map something tata sumo and in that map something na distraction I will swear that I will first gesture I will leave it, okay, then I will delete both these wires and see if the negative sum of these two is already included in the map. If it is already included in the map, then it means that both of these banks were making syrup together, if it is so clear. So let's fold it to make the above effective, so I told first of all and I have to leave the understanding of these two addresses, so what can I do, I can make a fast map like this and frustration and If he is doing credit in any plus then he can make an unwanted map. Okay, so this has become my sky as to what to do to make it in Mukesh Ambani House. Now after coming so far, I have to make all the possible time of these two wires. Possible spoon their pregnancy like minus one like if I tell you like it was time to reduce these two - don't time to reduce these two - don't time to reduce these two - don't 20 and one so I will be on my Play Store my show that - it's ready I spoon once that - it's ready I spoon once that - it's ready I spoon once is zero Ki incarnation is this zero came twice and is on 113 one is a moment notice spoon and will end evening frequency hokar audit ki to for yaad rakhna point is his profile assistant no-1 his profile assistant no-1 his profile assistant no-1 phone number one don't like this bow according to taste Head to Studio The Day Number Break Length Chinese Present Financial Crisis Union Workers Tube Number One Five Plus Two Take Every Possible I Can Get One or Two I Can Get Me In This Time I Can Do and Want It So It Can Be That if I am already in juice and in ours then please I have to plus one right then I will use a pin world coffee here so that cigarette and deposit in your show that if there is a holiday then I will also get its value if it is not already This is the viewer's roy and whatever is there, delete it. Okay, this is the fact. If we print this map, okay, then we can remove this meat. We can print things in less time. Okay, let's return it in the case now - Who return it in the case now - Who return it in the case now - Who is there? I will make you the sea front. I will print it for you. What will you make of our experiment? Make a slow motor statement. Thank you. For regular, ready type. Oh, I am my I will stand number one dot. Length but from age, names of friends are school name, phone number name, do it acomment, in this world, the years are ok, the robber's name is not typed. Papa, I told you - mind, how much is the minimum, okay, told you - mind, how much is the minimum, okay, told you - mind, how much is the minimum, okay, what is the frequency of zero, what is the frequency of 102 online twice, how many times is it online, that is a big one, okay, so come on friend, I have become you, now what do I have to do now? If I want a counter then how the end account is 20 and I will do this with solid intentions. I have to plan my waist in Indore. Its time by playing the play store. Alia, I dare to try this. Is there anyone from Indore head whose negative map is already there? I am mixed till means those four legs together are making number so pay attention I again address favorite so I respect to paint i20 price list in these number of free trade as second so my work be what ok part plus Plus and for 1000 this lab name sport dot loop inch plus okay so now this is so much to see among ourselves is it in my map if you support time this thanks for medical store name of that Anand strike slums trouble come A plus norms for 1615 me so much I want to see that brother why my account Jag my account please request you's fair I want to see the fun I am you for tat and that is the team point that I want to go to the pot chapter default and see what friend if this negative of you is present then that is from me Top evening frequency to meet should be present I come Place should be found Front If he is not present then I will definitely meet Experiment Is it not the same Is it important to look at it carefully I am in a taxi I am not doing much I am just I am seeing that if I am in my circle, then I have got someone here, complete and support me, I have got sub-money here, I have got sub-money here, I have got sub-money here, then type its negative minus one, Cardiff test one to explain it through the media. That I am Wonderla here okay but this is also so I am in the forest like the map is there - 110 I am in the forest like the map is there - 110 I am in the forest like the map is there - 110 016 that when we support it then the country okay you got it now what will you see negative one of this dynasty will do this is to close Would be for - 951 is to close Would be for - 951 is to close Would be for - 951 tips to do minus one should e map inside refer my is drama if is it is making a for belt hair what use setting on how to fix to if he then his friend's meaning should if he is not So if she is looking for me, then this is our Edwina Mountbatten, she has returned to the account, so typing is acceptable, no work is required, extra laddu is compiled and commented, kids are working but there is a very institute e approach, entry, I have told this many times in the cross. Test if your map is something like this after reducing the first two addresses, this is just what I want to see, now when I talk about hydrating the second address far away, like if there is a forest to excite on the other side, then this Vansh's Negative Petis - Mark is then this Vansh's Negative Petis - Mark is then this Vansh's Negative Petis - Mark is embedded in the body. Yes, there is tightening. If I add one and minus one, let's go till 500. This is the approach to this whole question and this thing is approaching and why are you approaching, so do that. Because when what is an addition, like A plus B plus C plus that if it is giving you zero, then man, if I do it like this, A plus C plus B plus D, this will also be this zero, this is called comedy property. Crack Edition is this formatted ok so many of the questions here will not come to the children, what brother, in the beginning, just keep the first two addresses and the remaining two friends, this is why I was like this, if there is any 21 aspect in this, if I wanted, then I would take this address. Could have first spent the time of both of them and then later checked the negative of both of them. Am I my present that Bigg Boss edition of this comedy, this work's sleep in the afternoon, its Shankar, later the negative of the remaining two legs, that map. You can find it in Ok ok if you understand then this is question ok if there is any trick then it is above free to PNB in friend and comment white to give free to PNB in friend and comment white to give free to PNB in friend and comment white to give up like that this injury challenge your friends to do it is question and help in group were bye
|
4Sum II
|
4sum-ii
|
Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that:
* `0 <= i, j, k, l < n`
* `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0`
**Example 1:**
**Input:** nums1 = \[1,2\], nums2 = \[-2,-1\], nums3 = \[-1,2\], nums4 = \[0,2\]
**Output:** 2
**Explanation:**
The two tuples are:
1. (0, 0, 0, 1) -> nums1\[0\] + nums2\[0\] + nums3\[0\] + nums4\[1\] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1\[1\] + nums2\[1\] + nums3\[0\] + nums4\[0\] = 2 + (-1) + (-1) + 0 = 0
**Example 2:**
**Input:** nums1 = \[0\], nums2 = \[0\], nums3 = \[0\], nums4 = \[0\]
**Output:** 1
**Constraints:**
* `n == nums1.length`
* `n == nums2.length`
* `n == nums3.length`
* `n == nums4.length`
* `1 <= n <= 200`
* `-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228`
| null |
Array,Hash Table
|
Medium
|
18
|
427 |
hi everyone in this video we are going to solve a new problem the problem name is construct quartery and the problem number is four to seven fine first of all we are going to clearly understand what this poem says after that we are going to move to the logic part and after that we are going to implement our logic is fine now guys let's see what this form says given an enclosure Matrix and the name of the Matrix in nothing would create fine and inside of this grid we can either have 0 or 1 that means there is going to be only two values either it can be zero or one now we want to represent the grid with a quadrant well let's now we have to represent our Matrix nothing but with a quadrate now what it is quadri we are going to understand this later on and after that we are going to say written the root of quad tree okay so now we have to return the root of that particular quantity fine now guys let's see what is this a quadrant so guys like a tree we have nothing but three thing right first is a value which represents whether what is the value of that particular load then left pointer then right pointer left pointer point to the left node right corner point to the right node same in this particular quadrant we have a node this is a node and there we have a value which is going to represent the value of that particular node at each leave is going to be true if that particular node is a last node Leaf node and otherwise it is going to be fast fine and after that we can say there are going to be four pointers instead of two rather than two we can say in three we have two right but here we are going to have four pointers like top left top right bottom left and bottom right so here if you can say that this uh node then it can have four right and until we have only two right so this is only the difference in quarterly we are going to have four pointer the first pointing to top left second top right and third bottom left and fourth bottom left right now guys it says that value is going to be true if the node representative of grid is one otherwise it is going to be 0 right so it says that value it can be either 0 1 only but it is going to one only when all the values in your grid are one otherwise it is going to be 0 if your all the values in your grid is going to be a zero right now guys let's see the next part of this particular problem so we because this is a bigger problem so let's understand from this particular grid now what this form says so now guys you can see that let's say I am going to say the C grid which is 4 into 4 right and I'm going to assign the value 0 inside of this grid fine so let me sign all the values are zero now I see it says that if all the values integrate are same that means that is going to be a leaf node right so remember this thing Leaf node is going to be when all the values inside of 3 or inside of this Matrix is going to be the same so Leaf node is going to be test right fine if it is a leaf node then you have to make is leaves true you are going to make a true and value is going to be nothing but the same as the value inside of grid so here if we have a 0 so it is going to be 0 but if we have uh all the values are 1 then value is going to be a 1 I hope this makes sense okay and if there is no same values inside of grid let's say here is a one right and here are so one so that means there is a note all the values are not same inside of our grid then we can say this you know to go into a leaf node so we can say easily if it's going to be a false and the value you can give anything you can give it a zero or one doesn't matter if it is not a leaf node fine at also you have to move to the top left part top right part top uh bottom left bar and bottom right part five so now how you can move to that particular part so you can see that here so it says that guys nothing but we have a get this grid and all the values are not same let's unders we can assume this thing right now so top left part is going to be this particular part as it is a square Matrix so we can say two plus what is going to be this particular part and uh top right this part bottom left this particular part now how we can divide this particular part you can see that because if this is this rows are going first of all let's take a whole grid so rows are 0 to 4 and column also zero to four right so this top left part is going to be 0 to 2 and column is going to be nothing but 0 to 2. and this particular zero we can set rows are 0 to 2 but column two to four and here rows are two to four and column are 0 2 and here rows are two to four and columns are two to four so this is how we can divide our gradient into top left top right top bottom left and bottom right path and I believe by this I told you this particular idea you can easily solve this particular Problem by without watching this we can say the video full right complete so you can solve also but if still you don't have any idea if you didn't get how we can solve this let's move to the next part so here what I can say now we are gonna say this particular example and we are going to see how this particular example has been solved by this lead code right so we have this particular grid right and this is two into two Matrix we can say right fine now what we can do we can say all the values in this grid are not same right you can see here 0 and 1 so what we can say this is not going to be Leaf node right so you can see is leaf is nothing but false okay and value they have given one you can give it 0 doesn't matter if it is no tell if node fine now guys we are going to move to the all the four parts so top left part is going to be this one bottom left to be this one and top right is going to be this one and bottom right is going to be this fine now guys top left is having all the values are same in top left that is zero so value 0 is leaf is true bottom left is also going to be we can say nothing but 0 or 1 so value is going to be one and easily if is one and we can set up so we can say all the values are same that is one so where is one and this Leaf is true and bottom right also value is 0 and easily phase two and it was an easy problem we can see it is example so let's move to the next example which gonna kill your mind definitely if you still have any kind of doubt you can understand this particular Problem by just this particular example two right this is example two and definitely you will have a better idea once you complete this particular example so let's see what this example says so here we have this particular example right so we can say all the values are not same this is one this is zero right we can see this all the values are not same so easily if it's going to be fast you can focus over here this is far is leaf is zero and well you can give one or zero that doesn't matter if it is a leaf node right now guys it's going to divide into top left and bottom left so we can say top left is this and top right is this particular path and bottom left is this particular part and bottom right this particular part right now guys you can see this is top left right top left you can see all the values are same that is one so they give is refused to annual usual we are not going to proceed further because this is going to be Leaf node but if it is not in inside this you can see top right you can see that all the values are not same this is zero and one so we can say it is not going to be Leaf node it is going to uh it easily if it's going to be fast right and value is going to be anything if they give one you can give it 0 as well and bottom left easily if you can see bottom left this part and you can see all the values are one so easily if it's going to be true and value is going to be 1. and bottom right you can see easily if it's one that means it is a true right if it is you can see that uh easily is well because all the values inside of this bottom right part are zero right all the values are same so easily feasible and value is going to be the zero because all the values whatever the value inside of your guild right now guys we are going to explode for the top right part because here is leaf is not true we can say right it is a false so because the values are not same inside of it right so now we are going to say it is also going to divide it into four parts so top right part I am going to divide into four part that is nothing but first part is going to be this one and the first part means that is top left this is bottom left this is top right this is bottom line fine now you can see all the values he said if your top left top right bottom left bottom right are same right you can see here we have all zeros all one so it is also going to be all the nodes also going to be Leaf node right so now guys I believe that by this you will have a better idea and you must understood this particular problem what this form says how we are going to solve this particular problem right so now let's move to the logic part how we are going to proceed with our uh we can simply quoting part so we are going to say we are going to implement one function which is going to be function which is going to tell us that all the values inside of your grid are the same or not so this function is going to tell us that so let's give it a function name nothing but we can say proceed or we can say let's say all values right so all values is going to be tell us that whether we have all the values inside of grid are same all the values are same or not right so if this function is going to true then we can say this your Leaf node and we are gonna nothing proceed further but if it is going to return false so let me see if all values is nothing but Force then we can see we are going to create a node where the left node is also going to pass and left top left also going to be proceed top right also going to proceed so let me have to apply and bottom left also and bottom right also right so these all nodes are going to be proceed if this is a path right so how these are going to proceed we can see that for this particular node for this particular nodes and for all this particular node we are going to dividing our rows right so how we can say this is going to be 0 so initially if they were 0 let's say this is uh let me Define it with a clear idea so we have a function let me write here so this is a let's have a function right and here start row start column and or we can say let me start rows and rows start column and column right so this is a function if it is the function and if all the values are not same it's all function all values function it is fast then what we can do we can say that we are going to create a node right definitely we are going to create node and let's say node is nothing but let me Define a new color so let's say there is a node so we have created a node fine and here this node we are going to see nothing but I want to say this is going to be value can be anything it is a fast rate and leaf node is going to be a fast now this no total flat we can say top left no doubt so let me add note to top right no total bottom same right so this is we are going to divide top left but we are going to pass we are going to say start row is going to be same we are going to start from this particular part photo of left but end rows is going to be changes by start row plus the half of n rows minus r divided by 2. see Focus over this particular grid right so here initially what we have you can see that we have nothing but 0 to 8 right we have our row is also going to be 0 to 8 and column also going to be 0 to 8 right and index is if we talk about index is 0 to 7 right this should be my grade right so it is going to be 0 to 4 and 0 to 4 right so I can pass here start row plus star 2 is 0 and start column is row is going to be nothing but it starts row plus half eight minus 0 divided by 2 right so start row plus half of this right so this is half we can calculate by just dividing and rho minus four right eight minus 0 divided by 2 right so I can say plus half I hope this makes sense and same with the we can say column start column comma start column plus half so this is all we are going to do for top left top right bottom left hand bottom for bottom left we are going to change that column same we are going to do with the bottom left and bottom right so we are going to dividing our grade into four parts if that particular node is not a leaf node right so now let's see with the coding part how we can do this particular part if you still you have any kind of dot you can write in a comment section I am always there to help you now let's see the implementation part and let's try to understand from there and definitely will have a better idea if you still have any kind of doubt by the coding part so first of all I'm going to do with the Python programming language so let's move to with the python so here first of all I've told you that we are going to create a function that function let's say Define so we are going to see all values right all values it is going to take nothing but we can say self argument then create then start row and end row start column and column five and here we can say the value is going to be initially is going to grade of statue and start column fine and we are going to Traverse 4i in range of start row and row 14 range of start column and column fine and here I can say if grid of I definite grade I and J is not equal to electron at J is not equal to my value that means they are we don't have the same value inside of our grid we can see later first right so we can directly say it to false but if the values are going to same the infinitely it's not going to come in that particular condition so we can see written two right and then we can say all the values are same but I hope this much makes sense right now if it doesn't make sense we are going to call a function define Soul which is going to have start rows and row start column and column right here I can see if we can say nothing but what we can say if this self taught all values are same that met all values are same if it is true right start row and row start column and of course if it is true that means we can say that it is going to believe naught so we can see return node and we can pass the value which is on that particular value right great start row and start color and we can say nothing but two Leaf node is two but if it is not the case then we can say we are going to create a node definitely we're going to create a node the value can give anything so let's say I give one and here again pass a pulse is leaf is false and we are going to explore from top left and let me write it talk right no dot top right and we are going to explore photo bottom left fine and bottom right so we are going to explore for these particular thing so we can say nothing but first of all I'm going to calculate the half so half is nothing but going to be start and rows minus start row divided by 2. fine now what I can say note total flat also going to call this functions all and for this start row plus half and let me write here and we can say start column okay and start column plus up right and for this particular right part what we can say start row is going to be same start row plus half but end start column plus half comma n column same for bottom left you can say soul and here I can say start row plus half commas end rows and start column comma start column plus r and here for bottom line we can say start row plus half let me add plus half and let half and end rows and here so start column plus half and here we can say let me get half and here end column right so once we have done this we are going to say later node so we after that we are going to call this function written sold and here we can say star 2 is going to be 0 and rho is going to be grid length of grade then zero length of grid right one now let's try to run this code and see whether this code is working or not foreign because I haven't passed my grade rights I have to pass a grade as well like pass it create fine now let me run this code and see whether we are getting any more error or not so let me see that you can see over the test case are passed so let's try to submit this code and see whether we got any error or Not by submitting the code and I believe I should not get right so you can see that my test or we can say my problem solution got accepted right so okay now let's move to the description part and let's see in the language to C plus fine now in this C plus where is the code okay so much implementation for C plus fine let me give some value first of all here okay and here guys first uh for what I'm going to do I'm going to create one function right so let me write here one function that is going to be a boon and it is going to be all values right and it is also going to take vector or let me copy it from here only so by to write we need to write Christmas part right bye start column and end column right fine once we have done this we are going to say into value is nothing but we can see nothing but grid o start row and start following fine now we are going to say 4 into I is equal to g i is equal to start rule right and I less then start called end code and I can see I plus right and after that 4 in J is equal to nothing but we can say start column and J is less than n column and J plus and if value I have told you that if value if grid of I and J is not equal to our value that means this is not discrete does not have same value so we can say later for but if it is the case then it improve fine and let me see whether we have done an area in this so no we haven't done right now we are going to create one more function that is nothing but let me Define here I can say this function also going to be node and here this function is the name I'm going to give sold and this has nothing it's going to have nothing with that vector and that in the start row and start called end rows in start column in N column fine and once we are done these things we are going to say if that all values of grade start roast and rows start column and column is true it is true so what we can say if it is true that mean what we can say nothing but we can let me go there we can say we are going to make this our this node is leaf node so I can say return new node that is nothing but going to be Leaf node so the value is going to be great of start row start and start column and what we are going to say the easily if node is going to be true right easily float is going to be 2 and test that's all we are not going to proceed for the top left top right bottom left and bottom but if it not the case then what we are going to do we are going to create a node so we are going to create our node so that node is going to be nothing but node let me write here node first of all no and Y8 node is going to be new node and here we are going to say grid can be anything and this state is going to fast easily if it's false and after that we are going to press it for left part node left part left we can see talk left file so this is going to be solved as we have already seen that it is going to take a half thing right so let me Define f in half which is going to be and row minus start row let me write here and bracket and row minus start row okay n divided by 2 right so here I can say it is going to be start row comma start row plus and here end and we can say start column comma start column plus half right this is going to be top left part same let me copy for all this part so it is going to be uh top left right okay so what we are going to change this into a bright part we are going to say start row and startup service is going to same but end column is it is going to different times so start column plus the half is going to be comma and columns so we have changes the column we have move our column part ahead right now for bottom left so what is going to be doing bottom left ahead with the rows and let me attach the N rows and column is going to be same right so we can see start column comma start column plus half fine and what is going to be talk right we can say bottom right part so let it roll right so what is going to change this with right part we can say start row and start it is definitely going to change is so we have a head with the row as well as column part right so it is going to be n rows and start column plus half comma and column Plus I hope this much makes sense once we have done this thing we are going to return our note fine so once we are dating with node let's call this particular function so I'm going to say written Soul we're going to pass grade start row is going to be 0 and the end row is going to be grid dot size definite size and again 0 and again grid dot size let me run this code to the code and let me see my test case are passing or load so no we have got an error that is nothing but int is equal to start Row in what is its error okay so okay I have used a comma I have to use a colon right semicolon fine okay tell me whether we have any more error we have a half air right so it says that we have to post start row start column okay so we are using uh okay so now we don't pass this particular as in Python we have to pass we don't need to pass but here we have to pass grid right so I'm going to pass create my fine and here we have to pass create okay and here also we have to pass our grade right fine now let's try to run this code and I believe I should not have any error right and my test case are passed right so let's try to submit this code and it also gets submitted successfully fine now it keeps motivating me so now let me do with a Java programming language fine so now this with this Java what we are going to do first of all we are going to create a function first of all let's make the screen little in between so I'm going to create one function that is nothing but public all values let me get the Boolean all values pi and this is going to take first of all create so in let me create in the start Row in the start column and enter not Circle and rows in the start columns in end column right pi and this is not going to create this if what we need to okay so let's make it grid only right fine now what I'm going to say into value is nothing but going to be grid of start row start column right fine now what we can see we are going to say for enter is equal to 0 I less than grid I should be less than n row right and I plus and here I can say for in J is equal to nothing but start column and J less n column and J plus right and here we can see if grid of I and J is going to be equal to which is equal to or because if it is not equal to value that means the other values are not same right so we can see return first but if it is not the case we come out from this Loop that means all the values are same we can see written two right fine once we have done this we are going to create one more function that is nothing but going to be a source right public sort function and this is also going to return a node so node and this function is also going to have the same value so let me copy all this value right foreign so I copied all this value I paste it over here and here I'm going to say if this all values here code values if all values of this particular things we can say grade and start row so let me write all this again so start row start call and rows start column and column so if all these are true if this is getting me true that means this Leaf node right so I can say this is nothing but a leaf node so I can say return node and here what I can pass you get a node so let me write new node and here I'm going to pass nothing but we can see the value is going to grid of so we can see start row and start column and we can say here nothing but true right so we can see 2 easily phase 2. but if we note a leaf node then what we can say we are going to create a node definitely so we can say no it is going to be nothing but node of we can say 1 and we can say fast Leaf node is not true right and after that we can say in half is going to be n row minus end column and divide it by 2 right or we can say start by start column both are going to be same right if you will write this thing or that one last particular thing so which have right e r minus c both are going to work same right but for my satisfaction I write I doubt testing right now what I can say uh I can say I have to explore for left part so node dot left part so top left okay and it is going to solve here I'm going to pass grid and start row is going to be same and Android is going to change by start row plus half and start column is going to say start column plus half 5. so I'm going to copy this thing four times and here the second time I'm going to explore the top bottom top right sorry fine here start row and start plus half is going to same and end start column is going to change if I start column plus half and end column fine and now I am going to do with Autumn left and here what I can say grid start row and here start row is going to be changes so it's going to be you can say shifting so start row plus half comma start end row and start column comma start coming plus half right so now guys what I can say now the last part is connecting with bottom right so bottom right and this is going to be great start row start plus up that means I'm going to shift right row as well as column both so it's going to be start row plus half comma and row and start column comma half start column plus half comma and column right now we can create another load now let's try to run this code and see whether it's working final node I haven't called this first of all it's going to give me an error as well right and it is also giving error here as well so we are going to see it later on first of all let me see right so here what I can say I am going to call this particular function solve so we can say gray we can say nothing row is nothing but 0 and create dots length or we can say size as well right so here I am going to say length and here we can say 0 okay dot length fine once we add in this variable update on this particular things and here I am going to see nothing but start run startup column because I have done something error here in cannot convert it into a Boolean over here so what I have done nothing but node okay so let me see the data type of these things right so they see nothing but it says that okay so what I am going to do I'm going to do this thing so let me make it nothing but grade of rho and zeros right so it is giving a node is not a symbol so what they have done so they have done something node right so they have something integer so I am just saying that SC I am passing something else over here so I have to find out something let me see what so there are two errors right first is in cannot convert it to a Boolean so I'm saying the new node grid of SRC and SC right so this is nothing but it should be either one or zero right so let me see first of all the data type so there's one data type with this particular thing right I am using this particular data and there this stored value so this value is going to be a Boolean value right so either I have to pass one or two right so I can say here if my Boolean value is going to be we can say initiative right 5 if our grid of Sr and SC is equal to 1 is equal to 0 right so then I can say my value is going to be nothing but false right and I can pass here value so first problem is solved right the second problem I am having is uh again same this node so I have to use a new file and here again I don't pass one I have to pass something so I have passed it let's say false right now let's try to run this code okay stagger flow means something is missing over a start row and row start column and column so all the values fine start row Android start column and color fine so what is missing over here start Rules start row plus half start row starter plus half and start brokes off and row startups of Android okay start column plus half everything is fine why it is seeing the static of flow something is quite something is missing right so if I say it is a true if I do this thing let me see whether it's working final node so same thing I'm again getting is that is grid start row and row start column and column so something is missing over here in this function and I is equal to start row and end rows and I plus J is less than start column and column J plus so it is fine right and here it is also fine if it is 2 that means we are going to create a new node right fine so this is also true now guys there is a missing or something we can say here like start column and start column right that is the particular error we are having so we can say n rows and rows minus start rows right now it should give me node error right so let's try to run this code and hopefully if I go to uh if I got a separate thing now definitely it's gonna be yeah you can see that both the tasks are passed and I believe now you understood this problem and definitely it was I will definitely want to get an error Java is definitely a programming language four of my kind of person right so if you still have any let us first of all submit this thing right let me see whether we are getting any error in submit part of nodes so hopefully we do not get any error in submit part and if you still have any kind of doubt you can ask in the comment section and I know it was a really tough part for me as well but definitely we have solved all this uh this political problem is Java C plus programming language and if you still have any kind of doubt Connection in the comment section and if you learned something new in this video Don't you can subscribe my channel and also like my particular video so meet you in the next video
|
Construct Quad Tree
|
construct-quad-tree
|
Given a `n * n` matrix `grid` of `0's` and `1's` only. We want to represent `grid` with a Quad-Tree.
Return _the root of the Quad-Tree representing_ `grid`.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
* `val`: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the `val` to True or False when `isLeaf` is False, and both are accepted in the answer.
* `isLeaf`: True if the node is a leaf node on the tree or False if the node has four children.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
We can construct a Quad-Tree from a two-dimensional area using the following steps:
1. If the current grid has the same value (i.e all `1's` or all `0's`) set `isLeaf` True and set `val` to the value of the grid and set the four children to Null and stop.
2. If the current grid has different values, set `isLeaf` to False and set `val` to any value and divide the current grid into four sub-grids as shown in the photo.
3. Recurse for each of the children with the proper sub-grid.
If you want to know more about the Quad-Tree, you can refer to the [wiki](https://en.wikipedia.org/wiki/Quadtree).
**Quad-Tree format:**
You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where `null` signifies a path terminator where no node exists below.
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list `[isLeaf, val]`.
If the value of `isLeaf` or `val` is True we represent it as **1** in the list `[isLeaf, val]` and if the value of `isLeaf` or `val` is False we represent it as **0**.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** \[\[0,1\],\[1,0\],\[1,1\],\[1,1\],\[1,0\]\]
**Explanation:** The explanation of this example is shown below:
Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.
**Example 2:**
**Input:** grid = \[\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\]\]
**Output:** \[\[0,1\],\[1,1\],\[0,1\],\[1,1\],\[1,0\],null,null,null,null,\[1,0\],\[1,0\],\[1,1\],\[1,1\]\]
**Explanation:** All values in the grid are not the same. We divide the grid into four sub-grids.
The topLeft, bottomLeft and bottomRight each has the same value.
The topRight have different values so we divide it into 4 sub-grids where each has the same value.
Explanation is shown in the photo below:
**Constraints:**
* `n == grid.length == grid[i].length`
* `n == 2x` where `0 <= x <= 6`
| null | null |
Medium
| null |
1,975 |
Loot Hello and Welcome Back to Way Tunnel Vision English Video Scientist Now Half Hour 50 Numbers Maximum Matrix 125 subscribe The Channel Please Click on the link for detail view Quantum In Sold It's Very Difficult To Approve Like Subscribe 232 Miles 302 201 9 4 Madam Positive And Which Can Address Inside - - 5 Possibly Can Improve Its First - - 5 Possibly Can Improve Its First - - 5 Possibly Can Improve Its First List Element In This Will Be Possible To More Which Candle Any Number Of Verses In This Case Was Not Post Pond And Can Select First Positive A And tell me tomorrow morning Sacrifice Will Have Even Number Of For Number One Number Positive And Like This Jai Hind Is Case Behave And Nikli Is - - This Jai Hind Is Case Behave And Nikli Is - - This Jai Hind Is Case Behave And Nikli Is - - Verb - Verb - Verb - Water Can Do We Can Make Sure Ho e -magazine Positive -magazine Positive -magazine Positive Notice - Notice - Notice - 1929 Scientific Pyun - Do The Number Off How To Give Positive Hanumangarh Now Just A The Word Basically What They Are Doing Wrong Number Half Inch All The Best Of The Best All Subscribe Positive So I'm Multiplying - Magh Month Positive So I'm Multiplying - Magh Month Positive So I'm Multiplying - Magh Month After Snow And Find The Number of the One Channel Subscribe to One Time for Discussion Quite Late in This World and the Click on the link to subscribe our Channel subscribe and subscribe
|
Maximum Matrix Sum
|
minimum-distance-to-the-target-element
|
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105`
|
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
|
Array
|
Easy
| null |
1,722 |
hey what's up guys this is june so this time uh 1722 minimize hamming distance after swap operations um so you're given like two integer arrays source and target and they have the same length and you're also given like an array of a lot swaps so the swaps has like this two indices which means that you can swap those two indices right and you can also like swap uh those two indices uh as many times as you want and then it asks you to return the minimum hamming this distance uh of the source and targets after performing any amount of swaps operations on the source and the timing distance is like the basically how many letters are different on each of the index so some examples right so for example the one number uh example number one here so you can swap index zero one and then two three that's why you know after swaps so the best you can get is two one three uh two one four three and the hamming distance for this one it's going to be 1 because 2 1 4 they're all the same but the 5 and 3 are they're different right and then here another example right so for this one there's no allowed swap so which means that you know and they are the answer is two right so basically there are two different like letters uh numbers and so the number three the freak the example three here so this one is zero so the reason being is that you know the uh actually this example three is the most important one because so as you guys can as you can see right so we have we can swap from zero four this blah so which means that it literally we can swap any index freely so why is that because since those four uh swaps basically connect each of the index together right so this basically this one give us like a hint right oh by the way here are some like constraints right and actually the example three here give us some hints so the hint is that you know as we can freely we can swap those index indices you know we can rearrange to any of the combinations as long as those three those indices are connected together right so which means that it's a union find solution right so and basically that's the solution will be uh so basically this is what i mean let's see let's say we have uh five one and two there's like only this is the three elements let's see the allow swaps is what is the uh from zero to one and then from one to two let's say we have this a lot swaps and here are like the arrays here so you if we do a union find right basically with those two edges so zero one and two those are in that indices right so those three indices will be will belong to the to one group so which means that as given like this uh this group here we can just freely rearrange the numbers here basically this one can be it can be a within any sequence it could be one four two one five one two five two one or one five two it doesn't really matter because they are connected to each other and since we can do the swaps any number of times basically we can just freely rearrange the uh the other here okay so yeah and that's gonna be our first step so which means that we're gonna use this like a lot swaps to create like a union find uh groups right and within one group and the second step is that let's say we have a group here so the group one we have group one the index in the group one let's say zero two and five right if we have this group so it means that any uh we can freely uh rearrange the letters in the 0 2 and 5. let's assume let's assuming the letters on the sorry the numbers right so the numbers on 0 to 5 is um 5 uh 1 and two right that's the source right how about target and then with this group we can just we can now greedily write right we greedily calculate uh what's going to be the minimum hamming distance right for this group how are we going to do it so let's say we have like uh s uh for this uh three indices we have five 1 2 and with the t here right so let's see the t the number is what it's uh let's say 1 3 and 5. so if that's the case right so and what's going to be the hamming hammering distance for this group i think it's not that hard to see right the hamming distance for this after some swaps right is what is one because we can always rearrange this the source to try to match the to the target as many as much as possible in this case so we're going to rearrange the source to what 2 to 1 2 and 5. right so after this swaps the only timing distance for this one is one so and how are we going to calculate get the one here right so we can um i think one way of doing this is we can have like a counter and we can have a count well we have a count for each of the numbers for both the s and t so every time when we have like s i won't have a number from s we're going to increase the count for this number so in this case we have five right so the count of five will be one and every time when we have like another we have like a number from the t here we're going to decrease the count of the same numbers right so that in this case you know in the end what we have here so what we have is we have count uh because the one and one five of the five they will be cancelled out so we have a count in the end we have count uh one equals to zero five is also zero right and then we have 2 equals to 1 3 equals to my to minus 1. that's going to be the final result right and so what's going to be our answer so the answer is that is the total of the uh it's the total of the uh the numbers that has the count greater than one right actually the minus one it also works but we're gonna just use the one here okay so yeah i think that's basically the uh the intuition for this problem you know and in the end we just which we just need to loop through all the groups right and then we count the hammer distance group by group and then we summarize the distance together to be our final answer cool so let's start coding here so first let's try let's fit do the uh the union find template right so we have a parent list of range of n right so for the union find you know since we have done this many times so i'll just uh quickly implement this one right parents hacks and then we have parents dot x equals to find parents dot x and then we just need to return the parent x and then we have a find web unit union x and y r 1 equals to find x and r 2 is equal to find y and if r1 is not equal to r2 right so we just do apparent r2 equals to r1 so here i'm skipping the uh the ranking logic so to actually to be to make this one real really one operation we should have like the introduce like a ranking uh array for each of the roots here so here based on the rankings here we either assign the r r2 to r1 was assigned to r1 to r2 but i just to make the code simple i'm skipping that part okay and then first you know we're gonna union to the units right in allow a lot of swaps okay we have groups uh find sorry not we do a union we do union uh a and b okay so after this one we're gonna try to group right group the uh group those indices right synthesis and the indices will be uh we do a groups because the default of dictionary.list because the default of dictionary.list because the default of dictionary.list right so that's going to be the groups and for i it goes to number in enumerate list okay and then the key is what the keys is the root right so basically the key is to find i right so to find the i will have the root and then the values will be a list of the indices for this group which is going to be the current i okay so now we can write group in the indices right by root right so now we can calculate final answer right so and for is in indices so because here i'm just using underscore because all we need is indices at the moment right in groups dot items right so that's the python way of looping through the dictionary and so like i said for each of the group i'm going to have like a dictionary to be that to count the frequency right of each numbers okay so it's going to be default dictionary dot int right and for i in indices so for count the source right so the source i right so the source eyes we increase it by one and for target i we decrease by one so we're doing this try trying to cancel out the uh the numbers that we can we don't have to swap oh sorry that's uh to cancel out the hammering distance right because we can always rearrange those uh those like the sequence try to match those two numbers together right and then in the end anything that's left on this count in this count array uh dictionary will be the hammer distance we need but keep in mind that we could end up like both the positive number and negative numbers and we just need to use one of them right some of the uh we have account for c in count dot values right and then if the c is greater than zero right that's how we uh count the at the timing the hamming distance and then in the end we simply return the answer um source yeah sorry should be source right submit okay and yeah so for the time complexity right so here we have a like uh for loop that's all of n here's another like for loop right of n and here's the same thing right the uh here's also of o of n because here we're looking through the groups and then for each of the groups we look through the indices so in total it's still the uh the o of n yup um yeah i guess that's pretty much right it is this one um what can i say i mean you seem to have uh have you just need to realize that you know since we can swap the uh the indices you know any number of times as long as they are they're connected together right we can always like try to find a best arrangement right and then once you have realized the unifying solutions right then you just need to find a way how can you greedily calculate the timing distance right so it so here what we're doing is that you know basically we're saying that if you see one unified group here um will for those data for the same number that appears in both the source and target and those numbers we are the ones that we can cancel each other out right and the ones that remaining will be the hamming distance because those are the numbers we cannot rearrange to match it to match each other right and then in the end that's it uh cool i think i'll stop here thank you for watching this video guys stay tuned see you guys soon bye
|
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
|
796 |
Hey gas welcome back tu de video so we are going to discuss in this video crying string is fine and is a very popular question and is a very good question and I would say it is not easy but it is medium level of question it is fine and Basically we will see how we will do this and friend you will see all over YouTube that I am not talking about anyone nor am I targeting anyone, no one is explaining the proper solution to this question, okay and today you will see that this The question is not that simple, okay, I will do it with basic implementation and I hope you guys liked my approach and liked the video. Okay, so let's see what the question is, if this string S can be made after a few steps, okay. So let's see how we shift, now what is said about shift in that, Un shift on consists of moving d left most character of Aage tu d round tu the right most position, ok moving left most tu the right most something. I am understanding something, I am on the left, okay, suppose this is, I have some numbers, okay, now I have to remove this number from here and bring it here, so something like this It is said that whoever does this less then we will do it okay and you catch the cash like this, okay these are the catches, in the question he himself has said Consist of moving left From the From the From the position, he will Let's see how long will I do it, why will I make two first? First of all, why will I put it in the van? Why will I put it in the van? Q2: Okay, it is mine. Q1 and it is mine. Q2 Well, now why will I put it in the van? Why will I put it in the van? Q2: Okay, it is mine. Q1 and it is mine. Q2 Well, now why will I put it in the van? Why will I put it in the van? Q2: Okay, it is mine. Q1 and it is mine. Q2 Well, now why will I put it in the van? So it's mine. Q1 What will it become A B C Di Aur Aayi This has become my Q1 I will make Q2 So what will I become C D A B What will I do now What will I do Now what will I do I will not do anything Ok I have also done the same Kali in this I will extract one character each from this and I will insert one character at the back, after how many steps it is formed, then I will take a variable which is my k tu dot size ok, what is the size of q2 one two three four punch so I will initialize it with punch, ok or 5 - 1 ok or 5 - 1 ok or 5 - 1 2 3 4, ok 5 - 1, what will happen 5 - 1, what will happen, 5 - 1, what will happen 5 - 1, what will happen, 5 - 1, what will happen 5 - 1, what will happen, see, the camera will be four, why will it be four, see, I will initialize its gold dot size with -1. initialize its gold dot size with -1. initialize its gold dot size with -1. Okay, understand what is the size of the round, is it punch? No, I will initialize it with one, okay, what will I initialize with one, okay, now what will I do, from this, I will pick the first character and pop it. And I will insult it at the back, okay ABC, this is what happened when my K was for, now I will enter the K in the degree and will perform the same operation again, now how much of my K is done, it is three, now I will put the di behind hataunga from here. So, what has become A B C di? Now try to speak with me, ok, it will be more clear than that. Now what will I do, from here A to hataunga and if I put A at the back, then what will become of this will become A B C. D A Okay, our string A is done Our string is what we needed A is done Okay A is done Look A B C D A And what was the goal of my CD Now okay so how many steps have we done In two steps String came and my round string went. Okay, I hope this question is clear to you. Look at this question. There is another perspective to look at this question. There is a shortcut. I am telling you how you will check whether there is any string rotation. Is it in me or not? Okay, you have seen the Rakhi like this, watch it right. The video may be long but this question will be clear to you and it will be cleared very well. It is important for many interviews. Look, this is the Rakhi given. Write the circular. I have written A B C D I in facial then write this in circular fashion C D I A B Okay, now it is in circular wave Now check this is a string in circular wave, I have made this string. He said, the string which is a string is making this string in a circular shape. Look, what do I need, A B C, what is my goal, CD, this also, what will I check, CD, okay, then I gave it, then I came to A, then B, look, I am getting the string in the circular way, it is okay and I am not getting that thing broken, so Han Bhai, this round string is in rotation or this is the S string, it is in rotation. That round shape of S is fine, I said it upside down, this is the S string, it is in rotation, now take the next example, it has the words A B C Di A B C I D, it is fine, take it in circular fashion. A B C Di Look, it went from A to B, it's okay, I went from A to B, it's okay, then from B to C, it's okay, then from B to A ca n't, look, it can't come back to A, so this is your string, the round one. What do you call the new one, this one is not in your circular fashion, which string's S string, then we can tell in the shortcut whether any string is in rotation or not, but all these are shortcut formulas, okay, which is the real implementation. Is that your implementation? Okay, now let's take one more example. Okay, I am not going to believe like this. Okay, I will not explain this question to you guys. Brother, I am going to sit quietly. Okay, look, a new one. Let's take an example. Okay, let's take a new example. B C G I F M. This is the string. This is my string. Make. Let's take a new example and I say, I want to check if F MBCG is in its rotation. So with the shortcut you can If you find it, you will feel that it is in rotation, so now look at its implementation, what is the implementation, brother, what is the implementation. Cut this from here, insert it here. Okay, if you understand, then you are. You will be able to find out after three steps, it will come in its rotation. Okay, try solving this example yourself and if not then ask in the comment section and the rest I don't think, I have explained this implementation with so much love. I will go to A. Okay, so first of all let's solve the lead's version. Then I have my own version which was asked to me in the interview. We will solve that version. Okay, so what will I do, I won't do anything. First of all, let's take two. I will take what type of character to do there is no additional code then what will I do why will I put s then put goal ok I will put s string in q1 why will I put goal string then i < you should gather work upon your basic Okay, do the basic well and come back okay q1 Okay similarly I can copy paste it and write for the lyrics for this people Okay brother so I hope you understand the video Okay okay what will I do now What will I do? Okay, what will I do? First of all, I took the first element of YouTube dot friend, then what did I do from there, removed it again, even after so many things, if it is not returning true, then return false. Okay, then the code. Let's see, this is a very basic code, friend, and I hope you have understood it, okay, this is not rocket science, look, it is okay for you guys, so I hope you understand, it is okay to run this example of bcgf yourself. After 3 rotations or after three rotations, this will be our string F MB CG A. Okay, I mean, what am I saying, you will do it to F MBCG, it will go to A in three rotations. Student, okay, so look, I am here. I understand, I picked a character from q2, popped it, then pushed it again, why do I push, then how does it happen, push from the back, okay, why, I just had the same concept, I did it. Checked the condition, after that what did I return? False otherwise I will return True. If both K is equal to mine, then K is also equal. This is also a very good question. Make a very good question to me. Why whenever I give mine? Why am I giving Rakhi, it is okay when I have two, why am I giving Rakhi? Listen carefully when Merraco is giving two, why am I giving Rakhi, they are equal only then, why am I feeling well, when their number of elements are equal, okay, the number of elements is equal. So there is a base condition in this, you can call the interview if it is not of my size and goal then it is not in the rotation. Okay, so let's see what is my version is this, my version is that you Return through and return false done, ok brother, no problem, just give me the number of rotation and print it. Ok, print the number of rotation and give me the meaning, like ABC is ABCD and CD is A. Now, this is your rotation. Now just print it and give it to me and whether it is in rotation or not, then print True and False and give it to me. Okay, so what will we do with this? We will copy and paste this code. And we will run it on the compiler and see, okay, such questions are asked to you in the interview and you people say that brother, you should get these questions done on the lead code, otherwise screening will not do anything to the children, it is okay, if you do then it will help in the long term. You will get less, okay then how will we do this, see, this is just a basic formality because now I will define string and goal in that function. Okay, good call brother, why do we call by reference? We call by reference so that we can Whatever change I do in the function, it should be reflected in my original string. Ok, question yourself while coding, only then you will get benefit and no benefit will not be available. Ok, Internet, I took that string, I took it Lee now the CD is okay pick it up from here I am a b c di i and my string ball is this train is round my string hole is mine what is the string roll is mine and will pass it wide ok because forget if If I mistake retain type, it will give the answer in one and zero. What do I need in the output? Its output should be true and common. You mean after how many number of rotations, this happened after rotation and true because that happened and rotation became possible. So true and in how many rotations did you happen and if rotation is not happening then false and what will I print zero ok now what will I do I will not do anything if this is happening if it is possible that it is happening to me then I will make C out and I will give one line space, this little indentation goes to part A and what will I do after that, I will do it after that, okay, after this I will make C out, my cake is fine and L is fine, this is just It's a small thing, okay, how many rotations are happening, that must be the coming store, right, and instead of return falls, I will give a condition team here, I will give a lovely condition team if, okay, what will I put, I will put so this is this given code. We would have selected the language properly. C+Plus If it should If it should If it should not come then it should not come. False should not come. Okay, sorry, okay, right now the output is wrong. What is the problem right now? Okay, I have given this condition here. It was inside it that is why it was not running and if the peacock becomes important then the return will become true and it will break the condition. If it breaks the condition then what will happen. What will happen if both of my loops become equal then that condition. A is breaking outside the loop, it is ok and it will print outside, C out, it will print mine, then after that it will check one more condition, if q1 and q2 are not equal, if not equal, then it will print C out, false. Okay, here the break will come and this one which is in this condition, what will it come out of the loop, so friend, I was asked this in the interview, okay, and in the interview, he asks such questions, okay, he did a little twist, what did he do? He just got it printed from you and got these True False printed, so I understood this video and liked it, okay, its time complexity will be of N and space complexity, because why am I doing it, so I hope this video, I understood and this problem is a very good problem, it's okay to practice yourself three to four times and like the video, it's okay to like it and share it, we will meet in our next video, till then keep reading. all de very
|
Rotate String
|
reaching-points
|
Given two strings `s` and `goal`, return `true` _if and only if_ `s` _can become_ `goal` _after some number of **shifts** on_ `s`.
A **shift** on `s` consists of moving the leftmost character of `s` to the rightmost position.
* For example, if `s = "abcde "`, then it will be `"bcdea "` after one shift.
**Example 1:**
**Input:** s = "abcde", goal = "cdeab"
**Output:** true
**Example 2:**
**Input:** s = "abcde", goal = "abced"
**Output:** false
**Constraints:**
* `1 <= s.length, goal.length <= 100`
* `s` and `goal` consist of lowercase English letters.
| null |
Math
|
Hard
| null |
1,961 |
all right so let's talk about the check if string is a prefix of array so give me the string s and then string array and basically you want to and is equal to the sh so basically you can create stream Builder and then append every single stream and just make sure that this the pattern the order is a prefix of the shess so yeah so let's start it Builder s Builder and for or Traverse the stream array and then I just say p the word into the stream Builder so if s.2 string is equal to the Str X I so if s.2 string is equal to the Str X I so if s.2 string is equal to the Str X I can say oh this is a true and then if not I need to compare with the prefix right so it's the index also word if this is if this does not equal to negative one which is you know is a prefix right but if this is netive one then it's not FL it so it's not the correct word for the shes right and yeah so if this is false you know just come false and at the end if you finish and then you cannot find anything and then I mean if they not match you return false so yep oh sorry all right so uh time and space this space for the word you're going to app every single word into here so it's going to be all of w for the space for the time this is all of w this is all of s right you want to compare and so worst case all of W Times s OB this all right so if you a question of comment and I'll see you later bye
|
Check If String Is a Prefix of Array
|
maximum-ice-cream-bars
|
Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefix string** of_ `words`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** s = "iloveleetcode ", words = \[ "i ", "love ", "leetcode ", "apples "\]
**Output:** true
**Explanation:**
s can be made by concatenating "i ", "love ", and "leetcode " together.
**Example 2:**
**Input:** s = "iloveleetcode ", words = \[ "apples ", "i ", "love ", "leetcode "\]
**Output:** false
**Explanation:**
It is impossible to make s using a prefix of arr.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 20`
* `1 <= s.length <= 1000`
* `words[i]` and `s` consist of only lowercase English letters.
|
It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first.
|
Array,Greedy,Sorting
|
Medium
| null |
588 |
okay so a lead code practice question uh in this video there are two goals the first goal is to see how to solve this problem so you're going to find the solution and do some coding work and the second goal is to see how we should behave in a real interview so let's get started so remember in our interview the first step is always try to understand the question uh if there is anything unclear please bring out the question to the interviewer and at the same time think about some match cases so let's take a look at the question the design in memory file system so design an in-memory file system to so design an in-memory file system to so design an in-memory file system to simulate the following functions ls given the path in string format if it is a file path return the list that only contains this file's name if it's a directory pass return the list of the file and the directory names in this directory your output should be in lexicographic order make dir uh given a directory pass that doesn't exist you should make a new directory according to the past so if the middle directory in the past does not exist you should create them as well this function has void return type and add content to the path to the file given a fail pass and the file content in the string format if the file does not exist you need to create a file containing given content if the file already exists you need to append the given content to the original content you need to append the given content okay so this function has a void return type read content from the file given the file return the content in the string format so uh see this example okay so i see some notes so i can assume that all the files are or directory pass are absolutely passed which begin with the forward slash and do not end with forward slash except that the pass is just false all right so you can assume that all the operations will be passed valid parameters and the users will not attempt to retrieve file content or list directory or a file that does not exist okay and i can assume that all the directory names and file names only contain lowercase letters and same name would not exist in the same directory okay so i think there might be some ash cases but i think the notes covered most of my concern about the ash cases for example what if there is already a file there but we are going to create a directory uh which has the same path as a file so what would what we do so something like that i think it's just going to do nothing for example so i think regarding this part um we are mostly in good shape about this uh problem so let's see the next part which is about finding solution so for this one the question is mostly focusing on the data structure uh design as long as we have a good enough data structure then i think those of the operations are just coding level for us to do so say for this one it remembers me a data structure called try so try appears in interview questions pretty often but not that often so try is uh for a certain note you have a bunch of them the children's uh and each children can be like um each and the number of the children's can be more than two so it's essentially not a banner tree but like a general tree and each of the children each of the branch essentially contains like uh some string to indicate what the branch it is so that's essentially the truth what the try is so for example for this one if you have the abc and the abcd so for a it has a child which is b and b has a child which is c so something like that and we also need to mark the tree node to see if it is a file and if it is file uh the file content we will need to store the file content as well so for the try the ls is going to depend on the past of the lens of the pass so if there are let's say there are un uh subdirectories then the runtime is going to be yeah it's it really depends so i would say this one it depends on the number of the subdirectories let's say there are many subdirectories and then under the inside direction under the corresponding there are three there uh m items to be listed so it is n plus m and for make dir this is just uh let's say unsub directories this is just the olefn and for add content uh again this is just the olefn because uh we just need to find the corresponding item and append the kind of content to the three node and the read content is also going to be olefin also all the ends represent the number of the subdirectories in the past so having said that let's start to do some coding work to show you how to solve this problem in the using the try solution so uh for find so the next part is about coding for coding we care about the code practice the readability and of course um and of course don't be too slow about coding so first of all we need to define a let's say file node so the file node um first of all we will have the hashmap which contains the string to the corresponding file node so this would be the children i say it's children another thing is we need a boring to indicate whether it is a file and the last one is uh we need to see uh we need to store the file contents as well let's say this is a file content yep and let's give it a constructor so let's say file node with the or we may not really need to do that um maybe just give it uh is file uh as a parameter so file content i think it's just fine so this dot is file so for the files and for the class we are going to define uh the members let's say we have the member as um let's say we have the member as private file node as root so in the constructor you have root as new file node this is so it is not a file for sure so uh so which one should we start let's say for the let's just do this one which is easier to make the our stuff so uh first of all uh we will need to split the this display the file here uh the directory using the forward slash so string um sub dlr is equal to the rrs as uh test dot sublight uh using the um forward slash so if you use the forward slash um so it means we have um we have the first one within the sub dr is going to be empty because we have the path starting with the forward slash so let's say for this one we are going to say okay i is equal to zero sorry one is smaller than sub the ar is the lens plus i so the reason we start from index is because the first step dr is going to be empty so let's see um we will have the file node as file node starting from root so if the file node dot um uh children that contains the uh let's say the sub here let's say string of the rs equals drs i so this is if it contains the sub dir then uh we just need to go to the corresponding node so file node is going to be file um node dot children dot get uh sub dir and then we just continue otherwise it means there's no corresponding sub directory there uh then we are going to create um a something so we are going to hey say okay file node new node is equal to new uh file node this says initialize false and we will say all right so file node dot children output uh the d sub dir and the corresponding node which is new node then we are going to have file node as new node okay so this one i think we should also have children new hash map then finally we just uh we don't need to return anything let's check this piece of code so we just split it and the first one is going to be empty so we start from the index s1 we have the final starting as root so if the corresponding node has a child which is sub dir then you're just going to go to the corresponding branch otherwise we need to have the new node and then we put it into the children and then we go to the new node okay so that should be pretty much it and let's see the i read the content from file so what if there's no search file so given a file return the content in string format do they say anything that all so you can assume that all persons will pass while the parameters either won't attempt to retrieve file contents or list a directory or file that doesn't exist so it means that for sure that the file exists here so here to implement this api what we do is we have file node as node starting from the root and uh okay so string um so vars is equal to pass dot split using the forward slash and then um similarly we are going to start from is one and start smaller than sub as lens uh plus i uh this is an array so um node will be equal to uh know the data children dot scatter which is the sub dir so the sub dir is defined as uh sub drs i so you go to corresponding subdirectory and then finally you just need to return node.file content yep so that should be it um so the children that's up here are yes i think it should be that should be it so i say add content so if the file does not exist we will need to create that file containing given content so uh let's see if it doesn't exist we need to do it um all right so let's also children set this dot file content uh i see called you empty stuff let's do this so um we need to say okay so string again we have some directories as fail pass so it is fail pass dot split does void with the for slash and file node starting from the root so again we start from index is equal to one i smaller sub the rs.less i smaller sub the rs.less i smaller sub the rs.less plus i so um string server dlr is equal to sub drs i so thing here is um if the file node already contains a children that has the sub-diar as the name then you're the sub-diar as the name then you're the sub-diar as the name then you're just going to have file node is if we're just going to go through the corresponding branch dot gets up dr so otherwise we will need to um create the corresponding node so we will say file node new node is equal to new file node so here we need to care about is file so to mark it to make sure to tell whether it is a directory or a file name so here we will say new file node this is eco so if i is equal to sub dlr dot once minus 1 which is the last one then it is true otherwise it is just something false so file node children dot put um dot put the server dir dot uh and then sorry the new node and then file node is equal to the new node so essentially we should have uh so this is file node okay so the name should be uh file node so file node is equal equals new node okay this one is also file okay so node is fine for here because this is the file node it's root node children and the new node okay sure and then after the for loop we should be uh in a node we should be already at the node so we have a filenode dot content.append filenode dot content.append filenode dot content.append data or just plus equal to the content so that's this api for the ls um it is so it is um it is still similar things so we are going to do similar things like this you're going to say so we are going to do some interesting things like this so ls we don't need to care about uh the creation because it's for sure the path exists so file node is um okay so we just go to the corresponding directory so let's take a look at this one if ls is a slash then uh yes let's see so given the path of the string if it is a file pass return the list that only contains this file's name so if it is a directory pass then return the lists of uh the direct of the file and direction names in this directory so your output and directory should in should be in lexicographical other um sure so let's say if um if the file node uh by the way we need to create the return stuff so this is a file and there is as new linked list so if the file node it dot is file then me it means that file and directory we're just going to add uh the pass and then we're just going to return it otherwise uh it is a directory so if it is a directory then we need to see all of its children so let's say so let's see for ls okay i think i understand it so it is something like um so if it is empty then it is empty so we are going to go through all of his children so string um this is uh um children child to go through file uh let's say this is file no dot children dot key set so all the keys um and then we are going to have the file and the dlrs.adder the file and the dlrs.adder the file and the dlrs.adder pass plus forward slash plus the child and then finally you just return the file and the directory so um i think mostly should be good let's uh do some testing for testing usually you could just go through a simple example explain how this piece of code is going to work and at the same time fixing the bug but considering we have limited time for this video let's just depend on this uh platform to help us fix all the bugs so if okay it is contains key this one should be also contains key uh let's do another compile so sub dr.lens dr.lens dr.lens line 81 uh sub dlrs dollars all right so this is the wrong answer because we add another forward slash here uh yeah so that's essentially we add another forward slash so i would say if it is only a forward slash then okay so i think i understand what it is so if um so how to say that so if um the pass so if pass dot uh last so let's say the car at pass dot lens minus one is equal to the forward slash then we just go we are going to do pass plus the children otherwise we will need to add an extra forward slash for it yeah let's give it another shot it's wrong again so it says that um output is so okay so let's file ls then make the rrsa add content ls so we are uh so the pass is empty so when we list ls currently gets a or okay so it doesn't us doesn't want us to get the follower slash added to it so it will be just uh something like we just foul plus uh children um or is it just children i so it is your output should be in lexical other okay so return list that only contains this file's name if it is the directory turn list of file and directory names in this directory okay so it seems like oh okay so it seems like it just asks us to get the children we need to uh and also i think we need to do collections the swords based on the file and they are before we return it okay so now it's good let's do a submission for it okay it's wrong answer let's see why so we have none on z9 so this one it gets the so let's uh let's see so it is calling the last second one which is ls so we ls this okay so it asks us to return the pass yeah that's weird so if it does okay so that's a misunderstanding about what we should return for the ls stuff um so it is this one so i think it's something like this it passed the equals the forward slash then you're just going to add the child of the child otherwise it asks us to it will ask us to get the children right past plus the children the past plus the follower slash plus the child let's run this again so let's run star again let's see why so it says make the rls make dr at content so this is make there this ls uh ls make dr z ls content so this is the content oh so actually uh if it is a content then we need to uh if it is file because it is file then we need to add the pass so this is ls this is lsc um so actually it is a file though so if it is a file which oh okay so i think i understand it so if it's a file then we just need to add a added uh so should we so it is the file uh we just need to have the loss of the ir actually so this file let's see how to do it uh it's just a addis der less right minus one so let's run again so it's getting us the so ls uh so lsc we are getting this ls this we are getting okay so it's just to add all the children so it is essentially something like this okay now it's good let's do another summation for it okay so it's mostly the bug is mostly about the misunderstanding about what we should return from the allies but other than that i think the algorithm should be the algorithm and data structure should be workable so that's it for uh this coding question and the corresponding solution if you like this video please help subscribe to this channel i'll see you next time thanks for watching
|
Design In-Memory File System
|
design-in-memory-file-system
|
Design a data structure that simulates an in-memory file system.
Implement the FileSystem class:
* `FileSystem()` Initializes the object of the system.
* `List ls(String path)`
* If `path` is a file path, returns a list that only contains this file's name.
* If `path` is a directory path, returns the list of file and directory names **in this directory**.
The answer should in **lexicographic order**.
* `void mkdir(String path)` Makes a new directory according to the given `path`. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well.
* `void addContentToFile(String filePath, String content)`
* If `filePath` does not exist, creates that file containing given `content`.
* If `filePath` already exists, appends the given `content` to original content.
* `String readContentFromFile(String filePath)` Returns the content in the file at `filePath`.
**Example 1:**
**Input**
\[ "FileSystem ", "ls ", "mkdir ", "addContentToFile ", "ls ", "readContentFromFile "\]
\[\[\], \[ "/ "\], \[ "/a/b/c "\], \[ "/a/b/c/d ", "hello "\], \[ "/ "\], \[ "/a/b/c/d "\]\]
**Output**
\[null, \[\], null, null, \[ "a "\], "hello "\]
**Explanation**
FileSystem fileSystem = new FileSystem();
fileSystem.ls( "/ "); // return \[\]
fileSystem.mkdir( "/a/b/c ");
fileSystem.addContentToFile( "/a/b/c/d ", "hello ");
fileSystem.ls( "/ "); // return \[ "a "\]
fileSystem.readContentFromFile( "/a/b/c/d "); // return "hello "
**Constraints:**
* `1 <= path.length, filePath.length <= 100`
* `path` and `filePath` are absolute paths which begin with `'/'` and do not end with `'/'` except that the path is just `"/ "`.
* You can assume that all directory names and file names only contain lowercase letters, and the same names will not exist in the same directory.
* You can assume that all operations will be passed valid parameters, and users will not attempt to retrieve file content or list a directory or file that does not exist.
* `1 <= content.length <= 50`
* At most `300` calls will be made to `ls`, `mkdir`, `addContentToFile`, and `readContentFromFile`.
| null |
Hash Table,String,Design,Trie
|
Hard
|
146,460,635
|
1,078 |
all right ten seven area currents just after a big wham given words first and second consider occurrence oh that's a greedy solution I mean that I would be surprised maybe that's why is easy if I try to do too much trying to be right but still greedy you shouldn't or you can't do big I mean that would make the difficulty make sense but I don't think you could do better than linear way still because you have to read every number right did my not gonna to pass type thing but also nice to see you again shrinking monkey 100 it's been a little while yeah welcome back I read this problem again I'm trying to get my speed up today that's why I'm trying to work on Yeezys and try to do them as fast as I can but cool yeah I came down with like some allergy food typing but I just could not get off to bed I was like trying to get up there better I mean I'll try to be back this coming week Sunday I mean I'm here now but definitely just one of those weeks I think it's the first time I missed a weekend like 3-4 months so hopefully weekend like 3-4 months so hopefully weekend like 3-4 months so hopefully that's not a regular thing anyway okay I'm trying to this one I keep on thinking maybe I'm I did not do the contest this week I was kind that's it's really hard to do in the sense that I could touch Saturday at 10 p.m. and like could touch Saturday at 10 p.m. and like could touch Saturday at 10 p.m. and like you know that's crime hanging out with friends time sometimes but I did actually do it I did a virtual contest I recorded it by the instrument because the last couple of times I screamed it I wasn't talking to anyone so it wasn't it was not a very interactive stream but I'll posted at some point maybe I'll stream it and then we'll watch it together kind of see where I made mistakes or whatever but about put it on YouTube in any case I mean it's not a big deal it's kind of weird because like it's not real bit but I do want to you know do more of it to at least like you know to show off a little bit or whatever that's it but like you know just to see if I rank up to anymore because I did one I did two to one two weeks ago now finish I mean I finished all the problems but I was like 490 or for something so that's you know not so hot but in this virtual contest I did okay oh yeah but I'll try look at my schedule but I try to do it just coming week but we'll see okay cool I only did this I said like do done anyway 1078 occurring to sound too big we're given birth first and second consider occurrences in some text of the form for a second day we're second comes after immediately after first and third comes in media and a second for each occurrence I'd do it to the answer and return the answer of the actual word turn that an input turn okay that's why I wasn't no use maybe I don't know way you returned the numbers after to first okay good girl and if it's tuna we mmm why is this not I know okay that's right mmm this doesn't seem like a hard form just try to figure I mean it's a season and the other one which maybe it's a easier solution but I am just trying to figure out what's the cream way to do it by thematically I think sometimes I especially for these string poems I feel like I think of like my mice see like see had way I just go first character by character which is unnecessary very pythonic I guess I'm just creating like expect yes as we and speaking of dad I heard three-point-eight just come out which I three-point-eight just come out which I three-point-eight just come out which I don't think we I mean it's we but it's fine at 3.8 where supposedly the fine at 3.8 where supposedly the fine at 3.8 where supposedly the syntax for regular expressions are cleaner because you could do which my car where you could do stuff like in line wearable assignment and stuff like that well okay so what's the expression it's just gonna be lowercase that is okay yeah I just have need to compile it cuz I'm when you're doing it yeah yes my pythons a boy I guess that's fine better then you take back X yes yeah okay find you right but sometimes when you have a hammer okay actually I try to sometimes overthink things a little bit because I definitely did a similar form the other day and I definitely spread further yeah in which there may be some tricky things with first and second being the same word you that's to me I was just maybe we have to know type oversight they were mostly there hopefully I have to try one where the cases are the same there's no - later I feel like I'm there's no - later I feel like I'm there's no - later I feel like I'm French or something we didn't look at the end yeah oh yeah it's just a waste simple state machine in that case if you expected hmm it's time to expect it I guess so that's it I'm annoying then okay I mean I think if this was on the contest I would have a dit just Chris I'm cuz they won't give me to expect every is only annoying good okay fine and just on your thousand countess maybe I'll just do something even dumber than just state machine you think I checked her we're getting slightly better at a witch by cut a slightly better at fighting stuff while waiting my timer society better making sure I check my stuff just definitely I was terrible at some point yeah I know i double-checked some stuff yeah I know i double-checked some stuff yeah I know i double-checked some stuff I guess you have to anyway if that's gonna be the case yeah okay well okay not sure I feel about it but that's fine Kevin where nothing is the answer yeah eight minutes on this one this should be less than eight minutes yeah okay I mean I know slow but that's why I didn't worry maybe you could still use a state machine but I end up not because there's only thousand Cal guys so yeah so there's something to be said about keep it simple stupid and which I try to do a little offensive regs and actually with records I would have gotten it wrong anyway because I think it would have consumed it instead I mean you could have made me do something tricky but I would have done what I did initially with the state machine so actually I've been patented by geeks but a good expression okay well thanks yeah otherwise this is a straight forward for my but again I need to keep it to still with some simple stupid or stupid simple ideas anyway and it functions in every language pretty much except for SEOs I mean so definitely shift on it this way but so yeah thanks for the heads up and I would keep it in mind but uh okay yeah this is a very straightforward well out of you it's you in an interview but you should practice enough so that you could be prepared for it dismay but I've been an easy side when but I mean almost only a little bit on the easy side but there are things that people can ask you about optimization which you know but just at the end of days like a five nine code so I don't know all right
|
Occurrences After Bigram
|
remove-outermost-parentheses
|
Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`.
Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`.
**Example 1:**
**Input:** text = "alice is a good girl she is a good student", first = "a", second = "good"
**Output:** \["girl","student"\]
**Example 2:**
**Input:** text = "we will we will rock you", first = "we", second = "will"
**Output:** \["we","rock"\]
**Constraints:**
* `1 <= text.length <= 1000`
* `text` consists of lowercase English letters and spaces.
* All the words in `text` a separated by **a single space**.
* `1 <= first.length, second.length <= 10`
* `first` and `second` consist of lowercase English letters.
|
Can you find the primitive decomposition? The number of ( and ) characters must be equal.
|
String,Stack
|
Easy
| null |
84 |
hey guys how's everything going I'm Jay sir this has been a long time since I last uploaded my videos there's a huge yeah every door the whole world is about the coronavirus and hope you're doing well please stay at home and stay healthy hope this coronavirus will be gone soon and yeah this is a very good time for a system and some algorithm problem today let's take a look at number 84 largest rectangle in histogram it's labeled as hard we're given n non-negative integers hard we're given n non-negative integers hard we're given n non-negative integers representing the histograms bar height where the width of each bar is one like this is 1 find the area of largest rectangle in this is red okay so as the example said the largest one would be this one yeah there might be many rectangles like Cadiz is 2 this is 1 maybe there's a 2 here and there's just 1 2 3 4 6 like that face right so the largest money established 5 here if there's a 7 there will be 15 hmm so well this I think for these kind of problems there always be alike tricky version but Before we jump into that one in the real Wow whiteboard test let's start with a brute-force a solution the yeah the brute-force a solution the yeah the brute-force a solution the yeah the solution the basic solution for this way this is pretty simple we find all the rectangles and compare the size right okay so this first one I labeled as brute force one a final rectangle so it will be n oh and square to find it and we need to calculate the area right and for that we need to get the minimum say we get so we need to tack we need to calculate the rectangle generated by 2 and a 5 we need to find a minimum not highly which is 1 so this one so this will cost an extra linear time so it's actually Big O in cubic it's pretty slow let's take at that we look at the result so okay for its it's pretty straightforward let's just jump into the code it's this is the start point of the rectangle and then let J equals J plus 1 I plus 1 sorry and this should be yeah oh it's the this the part self could be a rectangle so I'll start with I J plus 1 so this is the ending point up to five rectangle and then we need to find the minimum right a minimum because I'll say it starts with Heights I so forth let k equals this time it could be I minus one okay his K word jump 2j k plus one oh I think we have a better one the time complexity will not change doesn't change but we could be faster we can use the native math which is me F main heights slice I J plus 1 so we get the minimum and yeah let's say that's the max equals 0 we find the minimum who this is the height of a possible rectangle and we calculate it with a width which is J minus I and past one right yeah this is the width this is the input okay not return max this is pretty straightforward right let's run a code hope it works hmm not a number hmm math max zero mean maybe I slice really ah my bad d oh yeah there is actually I think this should be a slight spread operator here hmm yeah I submit of course it's my fail it might just take too long time yeah time limit tayo'y problem of course let's try to improve it the first idea come to my mind is that because we were checking every possible rectangle but we were getting the minimum of comparing them each comparing them over and over again to get to the minimum right like this one they will be minimum for this the rectangle generated by two and five and also to with six and it will be compared all and all it's not a good idea right so I'm supposing that we have a better solution is that we check the ending bar of the rectangle and do it in a backward way say like we get to there's nothing we can do so it's max means to write for one leave a rectangle ending at one with check - it's ending at one with check - it's ending at one with check - it's bigger okay we get the one the minimum is 1 so we get 1 right so that 4/5 is 1 so we get 1 right so that 4/5 is 1 so we get 1 right so that 4/5 is what we're getting is that we're checking for each bar this will be linear time and then we will get the minimum right and this will be an Indian time and then nothing else so we can do it in a possible improve it's actually a good force but it will be o n square I think yeah let's do it so it will be Czech ending bar for each this will be the ending bar okay we'll start with it and go to J will be bigger than J minus one so check it backwards they say we would get a five the possibility of square ne and 5 will be v 1 v 2 right yeah so okay this is the OOP I say if it is smarter than it then for the this the bar before 1 we don't need to change check right we only identify someone smaller than 1 right if it's bigger I'll say how to say if the previous one is bigger than five it's six then it's the same as five right because it's six the maximum will be four to five if it's five it's too far right so it doesn't matter it's big then bigger than it we've only carried the smaller one we will get it so the general purpose is find the slope downwards I'm not sure I make it as clear let's put it the ending at number six the bar of 6 we find five okay it's more than six so this is a possible solution and then we go again if it's again six it is a matter anymore it doesn't matter anymore we count it as five so it will be 3/5 so we count it as five so it will be 3/5 so we count it as five so it will be 3/5 so the key point is that keep the minimum number which is a smaller than current bar right so we say we keep the minimum oh the result is max okay I say smaller equals PI I if Heights J is bigger than smaller then it is smaller right I mean if it is like two is bigger than smaller one then it's smaller if it's zero then we can break so if Heights J equals zero we can break and if it's bigger than it then it is smaller so we updated max masks equals math max it is a smaller to keeping that keep that and keep that in mind which is smaller times I minus J it will plus 1 okay if it's smaller than it now smaller its itself right smaller equals I'd J and we won't do it again so we can improve this part so it's smaller equals math mean smaller height J but not this high J must not bigger it's must not bigger than way made it's not much oh yeah it's right so hmm this should work actually we can make it more concise yeah so we find a new bar to the left if we keep track of the smaller one so it will go down and then we calculate the square the size of the square and update to the max yeah this should work let's say the actually this one is n linear and this only one to comparison so I think it's good so it's improved at complexity let's run a code hmm it's a Heights is modified Heights ah there's a typo here not a number Oh zero I forgot to initialize the max submit this is where King okay it's work it's working but it's only faster than 11% of the all the solutions it's trying 11% of the all the solutions it's trying 11% of the all the solutions it's trying to prove that and generally I think there will be a tricky improvement which leads to one pass which is linear let's try to find out so we've doing the improved but forest solution well keeping track of the like we work we notice one characteristic of this problem that if there's a six and there's a five after it like is six here 5 here then this six doesn't mean anything right because we only find the smaller one keeping the down slope so if that's the case maybe we could do at the beginning not in the backward way but for these four we can't keep already keep track of the upward slope and then do the calculations right so let's say the first if we find a two right and then this two might be the possible solution so we recalculate the size it's max - okay and then we made this one we max - okay and then we made this one we max - okay and then we made this one we make this one this too is meaningless because it's becoming meaningless right because if the square contains both 2 and 1 this one will be the minimum so these two could be crashed into one so these two one actually is the same as one right so this is the character most important characteristic of this problem so yes transform this graph in into a new one okay so the first one it was egg is two and then we made one so will become 1 of course we're crashing down this a bar we will compare it with the final result 1 right and then we get 5 and then 6 and now we get to 4 to the 6 is minuteness so it must be crushed cut down to 5 right the previous 5 is bigger than 2 so we crash it and do we it will become 5 2 still this 5 2 5 is bigger than 2 we need to crash again so 2 and then we finally we get 3 so problem becomes very simple we keep how to say we keep only the key points key bar meaningful bars and remove the meaningless part and the graph finally becomes concise as 1 2 3 well this at last what it's this opera so we'll cut it down crush it and the 12 again to right and then we crash or to 1 and then finally we can tackle it all take it all and for this one 1 two 2 three 3 1 like say 1 2 3 this could be simply fired into an index and the value right this is generally means at the index of 1 0 we have 1 and from this from 0 all will be default one and then we find at two index 2 here we got a 2 and then at index 1 2 3 4 5 6 which is 5 we have three right so we don't need actually to keep track of the array we only need to calculate the size of the square so we only want to know the width which the width could be direct could be derived from the index right to five so the width would be two five will be for the size would it be height and the previous one right so - height and the previous one right so - height and the previous one right so - okay so that's cool so it starts so the final try maximum okay now we need to keep track up the my key points so we'll be two-dimensional array so let T we'll be two-dimensional array so let T we'll be two-dimensional array so let T points okay so we'll out remove this part the key points will be something like index and height right yeah so when we are traversing through the urate we find something bigger than it bigger than the key points at the top of these point and key points we push to the new point right for how we handle the mean initial one we can check by index or we initialize the empty a point which is something like that the bar here I will call it the index will be minus 1 and the value will be 0 because adding this point what do no harm right yeah it because the height is 0 it doesn't change you the maximum right the final result so ok lack I equals 0 I smarter than hide I plus opposed so what we do we will try to we'll find a new point we will do what if it is bigger we will push it right if it is smaller we need to crash it down and anyway if it is big what we do we crashing crush the bar down we need to compare the topmost number to this one if it is we will crush it down and down until the topmost point the bar will be smaller than it so actually it doesn't matter which is speaker than it or not so I was summarized into a separate function called crash it's crushing crush it down ah maybe I mean maybe I make mistake but just you keep using a crush I hide sigh which means I will crush the key points because we're having a new point which is at index I with the heights of hits I heights i right okay crush I'll be hand to the crush I tight if it's a bigger will insert a new point if it's a smaller we need to remove the point right until it's finding the best position and the finally we insert it so the new point will be tensed new point will be I said it afford to index and height right this is a new point and according to our observations while the top of the key points are a it's bigger than it we would need to crush it down right key points keep point then if it's the same yeah it's okay the same we could do the same so it's bigger or equal to height crush top right most I say right most key point if it is not smaller okay how we'd crush it quite simple because the point is array of index the high when we remove it we move the possibility of this graph this part starting the square starting from this bar to the index right let's say we made a two-week rush across six to five made a two-week rush across six to five made a two-week rush across six to five so we move the possibility of this five at the square from six to two yeah it's simple so max will be math max the top oh wait a minute we need to compare it so okay yeah I'll say constant key top equals key point first I will pop it either way I will pop it hmm no I will I don't need to pop it if it is bigger so this is the top if this is the truth if not I'll say key points push your point okay if it's smarter yeah Wow we could crush we crush it so we pop this will be top z1 this is the height times index - top z1 this is the height times index - top z1 this is the height times index - top zero we don't +1 because we only remove zero we don't +1 because we only remove zero we don't +1 because we only remove the bar here not containing this - right the bar here not containing this - right the bar here not containing this - right we were moving at six so we do this while loop again and again now we change the five six to five now we have double five right when we move it means the index of the new point was will move - we'll move here right no we will continue crush until the while loop is down so we will finally met the point here we find one right which means the while loop who will not continue so at that time we knew point updated to zero the course the that where is it top is here point mmm where is it wait a minute six we calculate it and now we have five we calculate the size yeah I think oh my I'm a mistake I can safely update it because if it's smaller we crushing down the six I can safely move the index right insert say it will be moved to - yeah definitely be moved to - yeah definitely be moved to - yeah definitely index no new point I will at least be baby here because it's yeah it's what a minute so point index will be top zero and when everything is down I'm playing this new point will be here and we can just insert it and because this is also inserted so what just say key points push Newport hmm so at the end all the bars are how to say a formatted or reduced into a beautiful upward slope and what we do at last yeah of course just as the beginning just as where we what we do at the beginning we assert an empty point right we can just insert a new point which is the eye height will be zero so we're wheezing inserting 0 or the graph all the bars will be crushed down right yeah cool it's run the code one of our defined points while key points mm-hmm okay let's see mm-hmm okay let's see mm-hmm okay let's see it's crush key points in dig site zero to 120 1 and 2 5 will be zero one okay - to 120 1 and 2 5 will be zero one okay - to 120 1 and 2 5 will be zero one okay - five okay three six it's right and then we have four - okay we'll have to - yeah we have four - okay we'll have to - yeah we have four - okay we'll have to - yeah five three yeah and then two five three yeah it's right five six mm-hmm yeah and the key points named - and the key points named - and the key points named - one it's weird I don't know what he says cannot read properly one of undefined what does it mean maybe there is a typo something but I don't know oh okay finally we get five three the top is our three zero-one mm-hmm it's just there's a zero-one mm-hmm it's just there's a zero-one mm-hmm it's just there's a strange thing ah my bad yeah at last we push this point this is not good right okay so we find a new point if it's bigger than it and then we crush I think problem comes here mm-hmm I think problem comes here mm-hmm I think problem comes here mm-hmm two points and nice one yes bigger than the we crush if not we push key point this index height we're on the code okay first one we crush this we just step oh yeah we push it so and then we find Z is it on one push it finally we you say zero one yeah I've been to 502 - yeah and then we got five been to 502 - yeah and then we got five been to 502 - yeah and then we got five three versus six zero and it's three key point means okay three is bigger than zero we pop it and then two bigger than zero a puppet one we get on it puppet then zero we're gonna name puppet ah God we pop through pop all so if my bad maybe we pop too much if key points I say then it's bigger than one and yeah it should be here we pop it and see if there is anything to pop right but for this case we would say be good one we pop hmm yeah to keep the entry element yeah we submit oh nice now we're faster than say 75% of the we're faster than say 75% of the we're faster than say 75% of the Oddie submissions this will be the we take a look there will be a 1/4 loop here so it's Ninian will be a 1/4 loop here so it's Ninian will be a 1/4 loop here so it's Ninian time and then for each crash method we have a food while loop it's seems like there will be big-oh and square but there will be big-oh and square but there will be big-oh and square but actually it is there is a there's a trick here you see for each the key points we generated like 4 0 4 for this graph we will generate something like 1 0 2 1 right and then update it to 0 1 and 2 5 to 6 and update it to 2 to 5 you see for each bar like 4 to 5 it will be checked for how many times for this 6 it will be checked for once because it's bigger and then it will not be checked again for next time it will be checked it will be removal of itself right how can I interpret this let's say for if you get a 2 if it's bigger than 5 they will be just it will be just to be insert a new one so it will not be checked again if something is bigger than it if it's smaller then it will be a removal right even its same as 5 they will be removed and replaced a new key point which is sister happen to b5 itself and the original bar is too right yeah this file the 505 is five will be removed which means it would basically check for each bar you will check at most twice one is to insert a new bar or it will be removed right if something like there's a how to say five and then seven this fight will be checked once and then we say like a six if I will be not be checked it will first be checked with seven and then what happened with seven say well bill B will be removed and then five to be checking again and six is kept and then if we get four Cesc will be removed and then five will be removed and it will be only for there so for each bar is at for each bar at it they will be stopped at one check if it is it's big like sex it will be only one check with five or four - it will be - several five or four - it will be - several five or four - it will be - several checks but after each check each bar will disappear so it's not me it's not linear time for n I have to make us robust proof of this assumption I don't know but I suppose that it will be in time some constant like three or two or three I don't know so it's linear cleans our result is much faster than a previous solution mmm how can I prove it bigger if it's bigger then nothing is checked after smaller it will remove check once yeah so check once or remove one right chick one add one yeah I know so if it's bigger they will at one bar right here it's bigger a new bar if big higher say if a new bar is taller there will be a new bar there if it's smaller they will be mu at least one so for each bar it will add one and or remove one bar but it will insert itself a hair there so you were at zero or zero so for all the bars they will be adding at most for the as for the worst case they will add their bar for themselves right so each bar what like some 1 2 3 4 5 6 7 compare ones and add one bar right for that' cases there add one bar right for that' cases there add one bar right for that' cases there will be removing some bars by 1 compare right so 1 compare plus 1 bar or remove 1 bar at least so at for the worst cases at all the bars and the only bars will be remove at the last crush here so one bar to add 1 bar or remove one bar that will be linear time total so it will be linear plus linear so it's still linear time yeah that's the general proof without the formula mathematically ok so after this problem hope it helps the sorry this video may take a little long time because we started with the brute force solution and try to improve that and finally God's this I don't know if it's concise or not but it's indeed faster than the previous two solutions and the key point of this problem is that we find some characteristics of the problem that the most important part if a smaller if shorter bar is to the right it makes the Calabar to the left meaningless so we can improve their graph how to say make it concise and make it easier to calculate and because we need to keep track of the size we only need to memorize the index which is the first elements of the point so we can derived with directly without looping through if we keep track other than a key point like this we will have something like 0 1 a 1 0 like a ray like a 1 2 3 something like this right we need to not afford to check how many 2's are there right so actually this abstraction helped us improve the solution by reducing an extra for loop right yeah so that's the end for this video hope it helps ya see next time bye take care
|
Largest Rectangle in Histogram
|
largest-rectangle-in-histogram
|
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104`
| null |
Array,Stack,Monotonic Stack
|
Hard
|
85,1918
|
68 |
given an array of strings words and a width Max width format the text such that each line is exactly Max with characters and is fully left and right Justified you should pack your words in a greedy approach that is pack as many words as you can in each line add Extra Spaces when necessary so that each line has exactly Max with characters extra spaces between words should be distributed as evenly as possible if the number of spaces on a line does not divide evenly between words the empty slots to the left will be assigned more spaces on the slots on the right for the last line of text it should be left Justified and no extra space is inserted between words and note that a word is defined as a character sequence consisting of non-space characters only non-space characters only non-space characters only each word's length is guaranteed to be greater than zero and not exceed Max width and the input array words contains at least one word so let's go over a few examples now so we have the words this is an example of text justification and our outputs is are the same words but just formatted uh various series of lines and it looks here that our first job is to partition the words to into lines first line second line third line job one partition words into lines ja2 now that we know from this index to that Index this is n corresponds to one line next few words example of text corresponds to the second line and justification corresponds to the third line how do we actually format the line so format language including the spaces so the first job perhaps maybe slightly less complicated than the second so first we can just try growing a line we initially have the line equal to this and its length is equal to four and we just try to add on spaces and words until we exceed Max width so since we have to have a space in each word between each word and the minimum number of spaces is one we take the greedy approach and just use the minimum number of spaces and uh trying to add on the next word which is and we find the length increases to seven which is still less than Max width which is okay let me try to add on and we increase the length to 10. that's okay it's still then we try to add on example and we increase the length to 18 which is above Max width so we cannot use this we must use it on the next line so now we know that the first three words are first slide so next and we continue it for you know example in place of this as for the second line the same process to find to create the line um so this is the first part of the logic our plan to attack this problem the second is actually given the Line This is or any line like such as example of text Max width equals 16 we need to format properly formatted string that represents the line including the spaces so here this is perhaps more complicated section of solving this problem but we can refer back to the problem statement for this one so let's define a few variables uh since Max with since MacBook is 16 there must be the width is Con uh the contributions with our the space width plus the word width equals should be equal to Max width and a word with is the sum of the non-space characters in non-space characters in non-space characters in the lines such as here it would be eight so space width should be eight as well to add up to 16. so we have three words we would you know this is something called a fence posts problem I guess samples the issue it's sort of related to a minor it's sort of related to off by one errors but if you have three words there are there will be obviously it will be two space two you know uh White space areas between the words so to find out how much white space we should have between each word we should divide well we should divide space width by a number of spaces which is the length of the line how many words are in the line number of words in line minus one and the problem is that it might not be evenly divisible and so we would have Extra Spaces would be the remainder of this number of words we just do number of spaces and if you recall the problem statements uh is a uh if there isn't an even number if this isn't if we have Extra Spaces we would need to add it add the Extra Spaces to the uh to the earlier the left or the uh yeah that's not a word but the spaces that are the Spade white space areas that are on the left so in so we have the line this is uh let's build the string this so we start with uh we so we have an equal let's say we have an equal white space uh in between each word which is just an empty strip empty white space this is python it is sort of python notation but just the space character repeated n number of times so here we would have the word count is the space with is eight number of spaces is equal to two so here it divides evenly so we should just have four characters in between it so our final result equals this Plus space plus is Plus makes a little light space area and now for the second line we just finished the first line so I had a small divider here and our result let's define it up front and later gather the proper ingredients so the result should be since we know the line is example of text the result should be some formatting of those characters some arrangements those the number of spaces foreign they might not be equal because the uh it might not evenly divide well we'll see so we find that the word we so we remember the recall that Max with the line should be equal to width of the spaces plus the width of the words and here the width of the words is seven plus six equals uh 13 and so the space width should be three but you know notice that we have three words and number of spaces is three words minus one is two here is two and you know uh three is not evenly divided by two so we will we must have sp1 and SP2 must be of different widths so we start with a baseline width of uh we start with a baseline width of three which is that number of space width divided by number of spaces this does not consider the remainder so this is times one since three divided by 2 is equal to 1.5 into three divided by 2 is equal to 1.5 into three divided by 2 is equal to 1.5 into the division gets rid of the decimal part and we end up with one so it's just one space and the remainder space Extra Spaces equals space width which is three number of spaces equals two which is equal to one so we must distribute these Extra Spaces among each space so we start with example and we start with the Baseline number of spaces we check if there is an any extra space where there is we consume that extra space so it becomes zero uh then we add the Baseline spaces what we check Extra Spaces is zero we don't need to add any extra spaces and the result is an example of text foreign so the last line we have different rules for formatting from the other lines so let's say we add another word here we can let's say we have another word here and if there were more words afterwards like an extremely long word uh we would have something like this but since it's the last line we should just have one space between each word and have everything right padded as for the problem statements so now let's start coding I think it may be helpful to implement certain methods after we invocate them so invoke them so let's just do a high level sketch right now so obviously we would need a vector to hold the result the lines for like we would need to respect why and the end will return lines and you want to decide how we want to go about uh with the partition so each iteration of this Loop should correspond to one partition and since a contiguous we can have two indices that represents the first word in the partition the last sort of the partition and at the end of the loop we would update the partition so L would be on plus one two for the start of the next slide you know so while we while L is less words size we do a needful uh we find well we first would need to generate the partition we would need to find the proper index R would be which is called find right past the appropriate parameters words x width now we do have the partition now we would just need to format things so something in line is equal to formats LR these represent our partition words x width and I think that's all for the top level functionality uh this is the first step I mentioned this is the second step I mentioned so let's Implement find right now find right string Vector of string words and Max with and let's think about how we want to implement this uh we perhaps we don't actually need to build any we don't have to manipulate any strings here we can just deal with the lengths so we can have the initial length to be um well we know that at you know at the very least the word at l is will be included uh the word at L will be included like the partition uh might just have one word so would be words L that size and we also want to have an index that we iterate using uh L plus one and while idx is less than words not the size okay and uh so size is the line with so far plus one first space when we're adding new word we need to add a space plus uh word starts idx dot size less than Max with plus that are equal to Max with we would want to add the word at idx to the partition so size we would want to increment size by plus words idx sine and we can't forget to increment idx itself we can just do a PostScript increment here that's okay and the result is well uh well it's not idx actually because idx number one it might end up on Words that size and as I said it's inclusive and uh what this condition fails uh there are already enough words in the line so the last word that was added at x minus one is actually the inclusive right endpoint so you would want to return this instead of idx and this is the first part second more challenging part is actually formatting the line all that you know our vector string words into x width and let's well one case we would need to consider if there is just one single word IE if L is equal to R we would just want to return that word itself perhaps if it's like justification here it's a long word but you know it's not longer than Max width we will want to pad some spaces on the right so we could Define a function that does just that give them a string word and then it matched with we would just want to pad some number of spaces on the right to make it equal make the word select equal to maximum and let's be lazy and just Implement that later and then return pad right or stats L you know R would work too uh Max width now comes more challenging parts so uh so for each word in the partition we would want well we need to build we need to start with a line obviously an empty string we would want to append the word to the line to that we would want to uh append some number of spaces let's just call it set for now except would be well as I said before this language we have a Constructor so string let's say three and a this will just get a string here you know this string so we need some number spaces uh which should be well it should be you know as we recall uh space width plus word with is equal to um Max width should be equal to Max width so we would have space with divided by number of spaces the number of spaces equals to well there are R minus L plus one we you know we can't forget about the first element uh but since they're in n words like three words or two spaces so we just minus subtract one and so their number their R minus L spaces space and we also need a variable to keep track of any Extra Spaces we need to distribute remainder is equal to well the remainder from this division here and we actually would need to use this uh use this very use this remainder variable so uh so if remainder is greater than zero we would want to in here to append an extra space otherwise just an empty space and we can't forget we need to change the variable itself so we post decrement it's that should work and we return and this we also need to get these variables here space width we actually to calculate that or path somehow pass it in but we can wait until later strength space and number spacing on space and also yes if it's the last line like we'll recall that um bright padded plus single space between each word plus right pattern so for here we can actually change the parameters set and use the same code here it looks like at least so we can add an indicator those last and last how would we know if it's the last well we've add the partition LR is contiguous so R would be at final words the final index of the final word so here's a flag and we would just want a single space here and we would not want to distribute any extra spaces so and zero that looks to me and also here uh we unless it's right padding we don't want to append any extra spaces you know for the last word in the partition so we just exclude R and in and add the words separately and we actually need to go back and Implement finding the word with uh since uh we are we're actually iterating through the words here we can somehow get the data from this function instead of iterating through the words again and I think it may be cleaner just to have it here but you know I put I don't uh I'm a bad habit of mine is making things uh more complicated than it need to be so I'll get it obtained from find right let's I guess to save an iteration through the words and let's see wait and let's check the constraints it's usually a good idea to check the constraints you know the words are not too long so it really doesn't matter here but let's just get the word let's just pass somehow find a way to pass the word length from this function to here we start by uh we're with by adding a parameter word with and space with equals Max with minus word with um and here equals we will understand word with uh it's the you know I mean because the first word is are the line starts out as the first word and here let's on variable w and represents a word with it's about size let's keep the increments in size one plus W and a word with plus equals w and we can actually return a tube with like a instead of like some sort of custom object so foreign with here we would need to pass in episode I also forgot to declare the variables and let's say work with and uh to I guess unpack the variables we would use something called time uh and she had order is uh V index r and word with now we can pass it in um also we need to implement add right but before that if the line I assume the line might also need extra padding at the end even if there are words in it such as uh this one acknowledgment we have extra spaces at the end uh we need to pad right here so line next with and this is relatively simple so we would do word plus some number of spaces and so max width minus or dark side length what it I think both are okay this should pad it to Max width or length plus Mac with minus word length is equals to Max width and so let's try running the code oh uh hope that everything goes well looks like it was sort of slows um all right okay let's try to submit it looks like it's a okay solution uh so thank you for watching this horrible first video and I hope this helps you in some way or manner to get a better job okay thank you and have a great night
|
Text Justification
|
text-justification
|
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth`
| null |
Array,String,Simulation
|
Hard
|
1714,2260
|
1,360 |
yeahyeah Hi everyone, I'm a programmer. Today I will introduce to you the problem of the number of days between two dates in the year. We will have the details of the problem as follows. Write a question. The program to calculate the number of days between two dates in the year according to this is the flash format Thu has the date month year then the two dates are said to be a string type and their format will be is to start with a four-digit year value followed by a four-digit year value followed by a four-digit year value followed by a dash and a two-digit month value followed by dash and a two-digit month value followed by dash and a two-digit month value followed by a dash followed by this value and two digits. We go into example one in example one We have the first date which is 2019 June the 29th on the second date which is the wrong house 2019 month 6 and the thirtieth day so we see that the distance between the two dates is 1A, this is the same year, the same month, and one day is the 29th, the 30th, so the actors must be one day apart. Then, through the example of Monday, we can see that the day is 2020, three months. 1 day 15, some Mondays are 2019, December 31, then we see that Monday is the last day of 2019. Day 1 means we have passed the new year 2020 for 15 days in January. So, it turns out that the distance between these two days is 15. So, we will think a little about the algorithm for solving these problems, then we can see the simplest solution we will have to handle. All on this date string tree so we can get the 5-month values and the date by 5-month values and the date by 5-month values and the date by closing it with this minus sign. After that, we will have to check a number of different cases. For example, in the case of example 1, we have the same 25 and two identical months. We just need to subtract these two values and take the subtract these two values and take the subtract these two values and take the absolute value, then we will get the difference in date. In example 2, we have a more difficult example, that is, if a day has a different year, a different month, on a different drinking day , we can have a , we can have a , we can have a way that we calculate the value of the day with the Old Year. So how many days is the distance from the last day of the old year? How many days is the day in the new year compared to the first day of January of the new year? Then we will add the two. Put this value together to know how many days the total distance is, those are just a number of conditions, we also check some more conditions, leading to that if we proceed to install Well, our program is quite long and takes a bit of time, so I will introduce it and also introduce to you a wait function so we can have a function to handle time in the language. Golden language so we can quickly install and also learn something new, this function will help us convert this date into an hour and Let's start adding and subtracting on the hour tree. So the idea is like this. Now I will proceed with the installation so you can see, I will declare a format parameter, which means the format of this hour, we will use. Just pass it something with a format, that is, a type and a format, then it will understand that it's going to be 5 months and a day, and then we 'll use a call function 'll use a call function 'll use a call function in that box. For the Cola reference object, we pass in the first parameter which is the format parameter, then the second parameter we pass in the date value which we have as the date and has the same format as the parameter or machine we specified. If we want to let it convert this date into ours, we will keep this value equal to Ms. error but in this case we don't check where they become so the dash is okay. Similarly, I will declare a piece of T2 and then call the function. You specialize in format references like A and Dead 2 after we have converted these two dates into two. Now we will calculate the return result for this problem, we will calculate as follows. If I forgot that I have not declared the result variables, then My result variable will first be zero after I calculate it, I will return the result variable em and then my result will be calculated as follows when we will take à T2 I will have the because this is a hour object, so we will have a very simple method - Let's take T2 and subtract t one, - Let's take T2 and subtract t one, - Let's take T2 and subtract t one, then we take its hour value and divide it into a day. So how many hours do we need to return to the day, right? We have to divide the total number of these different hours by 24 hours to get to the day, but remember, it's due to that. I'm familiar with this method, so you know it will return the value of the accent mark and the punctuation mark, or two Apple lanes, so I have to divide it by 20.0 A, it returns the have to divide it by 20.0 A, it returns the have to divide it by 20.0 A, it returns the exact value and then add one more. When we subtract this, we have to take the absolute value because we don't know who is T1 - T2 we don't know who is T1 - T2 we don't know who is T1 - T2 and we don't know which value is the larger value. So we subtract sometimes. If it makes a sound then just kill someone and use the cool ABS function already. This is what I introduced to all the methods in the West. The method is known and then I use the transfer of the story to control it. This Fast closure becomes a print variable and I return it because when I request this topic to return to you and my family, it cannot return it as 1.1 days. my family, it cannot return it as 1.1 days. my family, it cannot return it as 1.1 days. So I have installed it and tried to run it. example 1A Yes, you see that I have returned the correct request. Example one returns one and I hope the program's tea is also one. Now let's try to collapse Mit to solve the other examples. Okay. You can see that I have easily succeeded in all other examples, but for this problem, I cannot analyze the complexity of the algorithm because I do not know who is inside this penalty tunnel. I'm just wondering how complex it is and I do n't know how many variables it has to store, so for this video, I won't analyze the complexity of the algorithm and its complexity. The complexity of storage space Thank you all for watching the video here. If you find it interesting, please give me a like and subscribe to the channel. If you have any questions or have a better solution, please let me know. If you want to comment on the video, you can post it in the comments section below. Thank you all for watching. Goodbye and see you again. Yes, yes.
|
Number of Days Between Two Dates
|
maximum-length-of-a-concatenated-string-with-unique-characters
|
Write a program to count the number of days between two dates.
The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples.
**Example 1:**
**Input:** date1 = "2019-06-29", date2 = "2019-06-30"
**Output:** 1
**Example 2:**
**Input:** date1 = "2020-01-15", date2 = "2019-12-31"
**Output:** 15
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`.
|
You can try all combinations and keep mask of characters you have. You can use DP.
|
Array,String,Backtracking,Bit Manipulation
|
Medium
| null |
117 |
hi everyone so today we are here with a new problem this is a lead code uh medium problem which is populating next right pointer in each node two so the way we are going to solve this problem is first we understand the approach sorry the problem and then we see two approach to solve it stay tuned and let's see what is the problem first so the problem is basically populate each so basically we are given a binary tree okay and that boundary tree uh contains you know node are there and each node uh have value left right and next there are three pointers with each node okay and there is one value with this node so what we have to do is populate each next pointer to point to its next right node right so each one contains the next pointer and that next pointer should represents the right node okay if there is no right node the next pointer should be set to null as simple as that what it means let's understand this by this case so as you know this is a binary tree this binary tree have left right this to have four and five as left right these three don't have left but it contains right now for this node if you see at its right there is no node so for this the next pointer is pointing to the null right for this two there is three as a right node so its next is pointing to this 3 and for this 3 there is no right node so it is null 4 5 for 4 this is 5 as right 4 5 7 is the right 4 7 there is no right such that it is null and we have to do this very great now how we can do this okay you can pause the video and think about it how we can do it like these things okay now let's complete problem solution so as you know what we are doing at each level whatever the nodes we have we are just make their nodes next to its right node whatever it is okay so like this is the level one this is the level two this is the level three for this level you can see there is only one node that's why it's next not pointing to anything but there are two nodes so the first node is pointing to the second node and if you see the first node pointing to second and second one is pointing to the third one so we basically use the level order traversal how we are going to use it let's see this by taking this example it is very simple so what we do initially we will take a queue right and we will take this one and uh put it in our queue now uh one thing you have to understand let's suppose you are at level one when you are at level one you always try to make connection between uh the level two and when you are level two you always try to make connection between the level three okay so whenever you are at some level you always try to make an action in its below level now let's see how we will do this so let's suppose we are at uh we are pushing the uh current node to this point so what we will do we will take what is the size of this queue this is one and as you know at each level whatever the first node for each level that is the first node which start make connections for the rest of the nodes right for the first node there is no connection uh between the first node like for two you know there is no such node uh which is connected with this for node four there is no such node which is connected with this right so what we do we will take a node and this node is what we take it out from the queue so it is one right now what we do is we basically check if this node have left and right so you can see that one has left two and right as three so we will push two and we will push three now we will uh we will start we will make a for loop for the rest of the elements at the level one but you can see there is only one element one node in the level one which is we already take it out and that's why we are not able to iterate for the next of the road just wait let's see for the next role you can understand more clearly okay now we will again go to the queue and we will check this size so now the size is what the size is 2 so we will write 2 and the node is whatever the uh first element present in the queue which is 2 so we will take it out which is 2 and 42 left and right should be pushed which is 4 and which is 5. now one is already used the size is two and one node is already used so there is only one node left which is three so what i do is i basically remove this node which is three and what i do i will make this two is pointing to this three how we can write like node dot next is equal to this current what it actually do it actually make two dot next so this two dot next is actually three is current right and after this we will check if uh this current contains left no if it contains right yes seven so we will push seven into it great and after that we will also update the current sorry not current node is equal to the uh node dot next right so node is two and two down x is three so normal node is pointing to the three okay but you know there is only uh one element uh two element in the level two so uh this iteration stops okay we will work for the next iteration now for the next iteration what we do the same thing we will take this size now the size of q is what three okay and for the first node of this level we will take it out as node okay so we will write four and now what are the rest of the elements are two so what we do we will make a current and the current is whatever we pop it out from the queue which is five now we will do what we will do node dot next is equal to the current so node is four and four are next equal to the five and is there any left and right for this current no four is a leaf node so we don't push anything in this stack after this what we do we basically update our node is equal to the node dot next right so node.x is the node dot next right so node.x is the node dot next right so node.x is five so my node is pointing to the five and again i pop from the thing and it is seven now what we do no dot next what is node is five dot next is current which is seven so five is pointing to the seventh and we will also update this so now my node is seven and you can see my whole array my whole queue is empty and there is no other element here so we don't push into the queue and at the end there is uh like every node next pointer is populating with its right node so i hope you get this how we basically solve it using q but here the uh space extra space we are using we go off and whatever the number of nodes present in this binary tree all these are pushed inside this queue and that's how we are going to solve it this is the approach one okay and this is very good approach to solve it now how we can solve it using without q okay so the second approach is with the help of pointers so we are using pointers to solve it but how for that you have to understand little bit how we basically solve the previous problem okay and then we can understand from those let's see let me rub it great okay now you can see what we are doing inside the queue let's suppose we are at this mode so we basically store all the level two things in our queue and this the first node of each level we use as an initializer okay and whatever the next node we are getting in this level we just make connections to solve it we are using some pointers okay and let me write the pointer name and then we will tell you what we are going to be going to do with this so the first pointer we take is previous which is initially none the next pointer we take is current which is also none right so uh it is like this uh sorry not current we basically take a head i will tell you everything just a minute and there is one no more node which is the current which is initially root okay now this previous what this previous is doing so this previous is basically the pointer so let's suppose we are at the level two so what we do is we basically at we basically are at this level and for this first node of level two we use the previous pointer which points to this okay and let's suppose at any point of time okay let me know let's suppose for this level two if my previous this thing is none it means we are at the first node of this cabin okay uh we will understand the whole thing but this previous is just a pointer for all these node in each level this head is basically tells us for each level what is the first node so this head is pointing to the first node of each level and this current is telling us in which root in which node we are in and which node we are iterating okay so initially my current is root so root is what one okay so what i do is let me take a different color so what i do is i'm at this node and we will make a loop until my current is none okay so what we do is uh we are at the root node right we will check if my current left is there you can see that for this current there is a left node right then we check is my previous is none yes it is not so if previous is not it means that this is the first node off of a level okay so if it is the first node of a level what we have to do we simply initialize this previous with two now my previous is pointing to this two right and my head is pointing to this two why because if it is the first node of this level so it means this is the head for this level that's why we are updating our head now we will check if my current right is there yes my current right node is there and we also check is my previous is not no and that's how we come to know that my previous is initialized with the node right in that case when my previous is not none what we do we will make a connection between previous equal to current dot right so current is one and its right element is three so what we do we will do previous dot next is equal to the current dot right and this is the first pointer first next pointer we create and after this we will update our previous with the three right so we will update it with three now you can see after this if uh whatever my current it is one and i will check is there any other node in this level so we are at level one initially right so we will check is there any other node in the level one that we can iterate and you can see there is no other node here right so in that case what i do i basically update my current with head so my head is pointing to the two so now we are at level two and when we update our current we also update our previous with none and head with none now we are at this and my current is two so i will check that to have left node yes it contains left node and when it have left node we will check previous so previous is none it means it is the first node of this level yes it is so we will update it with four right after that we will check this current contains any uh right yes it contains the right node also so in that case my previous is not null and we also get our header okay that is the important thing now you can see that our previous is not null so what we do previous dot next equal to current dot right so this four is connected with this five and also we update our previous with five great now you can see this current is two and this two dot next so two dot next is three so we are updating our current by three so now we are at this position so you can see three don't have any left and event so we will do anything but these three have right element so this three contains the right node and the previous is not equal to none in that case what we will do we will basically make connection with five in seven this thing and after this we also update our previous with seven now we will see the three dot next which is none there is nothing in the next so our current is none now we will update our current with the end so what is the end that is four right and uh this previous is none and this add is none now you can see these four don't have any left right node so what we do we simply uh check its next element which is five so there is no a node it is a neat float so we go to the seven it is also a leaf then we update our current with overhead so which is none so whenever current is done this loop start stops right and this whole connection is completed right and that's how we are going to solve this problem more optimally without using any extra space any extra cube now let's see the code how we are going to solve it is very easy as i explained you so this is the base case if the root is done we have to return otherwise there are two nodes head previous and current right so what we will do until our current is not none we will go through this so what we will check if our current have left value and in that case if my previous is not initialized right if it is not initialized i it means this is the first node so we make our head as current dot left and also update our previous got it and we will check if it contains the right node and my previous is not initialized we will do the same step we just initialize it and if previous is not none it means it is already initialized then we will populate its next pointer with the right one and also update our currently current dot next right and let's suppose this is the code for each level and when one level completes we will make our current with equal to head and previous is again initialized with none and then again we will do the same process for the next level and we will do until all level is traversed and hence at the end of the day we will returning group so let me submit it and uh yes it gets submitted and uh i hope you like this problem and uh if you like this please like share comment and you can tell me how i can improve uh these things thank you
|
Populating Next Right Pointers in Each Node II
|
populating-next-right-pointers-in-each-node-ii
|
Given a binary tree
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** \[1,#,2,3,#,4,5,7,#\]
**Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 6000]`.
* `-100 <= Node.val <= 100`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116
|
242 |
even to strengths s1 and s2 write a function to determine if s2 is an anagram of s1 so what is anagram two strings are said to be ni grams of each other if it contains the same characters only the order of character in both these string is different for example if you see the example 1 s1 and s2 both contains the same character only the order of character in both this string is different so s2 is an anagram of s1 let's see the second example in second example if you see s2 is not an anagram of s1 as both the string can contain different characters so if you see H is present in string s2 but it's not present in s1 similarly C is present two times in s - but it's not present in two times in s - but it's not present in two times in s - but it's not present in and so on it's only occur once in S word and if you see another character e which is not present in s1 so as in this example as - is not an anagram of s1 so example as - is not an anagram of s1 so example as - is not an anagram of s1 so for this question you may assume the string contains only lowercase alphabets so before solving this problem let's think for a moment what's your approach to solve this problem first approach is to sort both the strings and compare if both the strings is equal then it's anagram otherwise it's not an anagram so if you recall the anagram property - if you recall the anagram property - if you recall the anagram property - stringer said to be anagram if it contains the same character only the order of character is different so our first example was car and our AC so if we sort this string then it is AC and if I sort this string then it is AC R if we compare them then both the string is equal so it's an anagram so the time complexity of this approaches oh and login so this is the easiest approach to check whether two strings is anagram or not so can you think let's think for a better solution can we reduce the time complexity further this is our second approach and in second approach how we are checking whether two strengths are anagram of each other or not let's see so here I have declared an array of array which has size of 26 why 26 has alphabet contains 26 letters so we need that much size and then I am traversing a string and here what I'm doing is I'm using the ASCII code so we know teske code of a is 97 similarly as the code of B is 98 and it goes up to Z which has s key code of 122 so to accommodate them in a indices of 0 to 25 we need to subtract it with the ASCII code of a so let's see so the first character in a string 1 is C so the S key code of C is 99 and the S key pod of a is 97 so here we get 2 so we need to put the value in this indices in indices to so here we are incrementing the count so the count is 1 now and if you see the first so let's move to next line and the first character of the string 2 is our and the s-capepod of our is 114 and if we s-capepod of our is 114 and if we s-capepod of our is 114 and if we subtract them with the S key code of a then it is 17 so somewhere let's say this is our and this is 17 and here we need to decrement its value so minus one is put here the next character is a the S key code of a is 97 and we need to subtract them with the S key code of a which is 97 so we get index 0 so at index 0 we need to increment a value which is 1 and let's move to this line and here this second character in a string 2 is a so we need to decrement the value at and this is 0 so now it's 0 the last character in a string 1 is R so the so we need to go at this index and increment its value so the value is 0 now and the last character in a string 2 is C we need to go at this index and decrement its value so it's 0 now so this is how this method works and after we came out of this loop then in this so in this code we are traversing an array and we are checking if any index has value any nYSSA's has value which is not equal to 0 then it's not an anagram so if you see in this array all the indices has value equal to 0 so we return true so it's an anagram so the time complexity of this approaches oh and which is better than the first approach so this is how this method works and that's it for this video tutorial and for more such programming tutorial you can subscribe our youtube channel or you can visit our website which is HTTP colon slash every right calm thanks for watching this video
|
Valid Anagram
|
valid-anagram
|
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "anagram", t = "nagaram"
**Output:** true
**Example 2:**
**Input:** s = "rat", t = "car"
**Output:** false
**Constraints:**
* `1 <= s.length, t.length <= 5 * 104`
* `s` and `t` consist of lowercase English letters.
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
| null |
Hash Table,String,Sorting
|
Easy
|
49,266,438
|
1,356 |
hey guys today we're going to sell leak on number 1356 sort integers by the number of one bits so we're given an array r and we have to sort it by the number of one digits in their binary representation and if they have the same amount of ones in their binary presentation then we need to sort them in ascending order and yeah just return the sorted array so the first part of this problem is actually doing the framework of this problem so telling our function that we're going to have to sort an array based on the number of ones and then we're going to have to do a function that given a number spits out the number of ones in that number right so first of all the first part we want to have a sorting which takes the two candidates and so you know how when you want to just sort them ascendingly you just do a minus b well in this case we want to sort them based on the binary presentation on the amount of ones in their binary presentation so instead we're going to take the amount of ones in the first number and subtract the amount of nums in the second number and you can look into how the certain callback works if you want to understand why you need to do this to have an ascending ordering and then if this is zero meaning that they have the same amount of one bits then we want to sort them ascendingly so we just do or meaning that if this is zero then this gets evaluated right and then we just pass in the common like this is how you would usually do the sorting if you just wanted a ascending sort right so now all that's left is to implement the num bytes the num bits function which is going to have to calculate how many ones we have in the binary representation and so to do that we're going to create a new function here and we're going to implement this recursively so what we're going to do is we're going to take the first bit like the least signifying bit of the current number so the way to do that is like this so this is just taking the first bit the least signifying bit out of our number and then what we do is we add to this the number of bits in all of the remaining bits so how do we discard the first bit we just shift the number to the right like this right so we shift our number to the right and then we call our function again and you can see that this is a recursive function so we're going to have to put a base case somewhere and we could do something like if number is zero then return zero and that would be a valid base case but instead we can take advantage of the recursive nature here and instead write a dynamic programming approach for this function so you see that we have overlapping sub problems because you're going to often times call this numbers function on a number that you've already called it on so we only want to do the calculation once and because remember that taking the number of one bits in a number takes o of log of that number so we only want to do it once and all of the other times we just want to return a memoized result see that's what we're going to do we're going to build a memo which also has our base case inside of it right and then what we do is we just check if the current parameter is in the memo and if it is returned of that memo else we just assign to the memo the return expression so yeah we just check if the num key is in the memo so it's the result is not undefined and if it is then we return memo of num and else we return the same expression but before returning it we just assign it to the memo of the proper key right so yeah in these three simple steps we've built the dynamic programming approach and so that also gives us the base case automatically so yeah i'm going to show you that this works and that's it for me today thank you for watching and bye
|
Sort Integers by The Number of 1 Bits
|
minimum-number-of-moves-to-make-palindrome
|
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order.
Return _the array after sorting it_.
**Example 1:**
**Input:** arr = \[0,1,2,3,4,5,6,7,8\]
**Output:** \[0,1,2,4,8,3,5,6,7\]
**Explantion:** \[0\] is the only integer with 0 bits.
\[1,2,4,8\] all have 1 bit.
\[3,5,6\] have 2 bits.
\[7\] has 3 bits.
The sorted array by bits is \[0,1,2,4,8,3,5,6,7\]
**Example 2:**
**Input:** arr = \[1024,512,256,128,64,32,16,8,4,2,1\]
**Output:** \[1,2,4,8,16,32,64,128,256,512,1024\]
**Explantion:** All integers have 1 bit in the binary representation, you should just sort them in ascending order.
**Constraints:**
* `1 <= arr.length <= 500`
* `0 <= arr[i] <= 104`
|
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
|
Two Pointers,String,Greedy,Binary Indexed Tree
|
Hard
|
1437
|
1,568 |
hello earthlings welcome yet again to see predict in this video we are going to see the third problem from today's lead code weekly contest 204 and it is called minimum number of days to disconnect island yeah we have a we have been given a grid we have one the one uh if we have a one in particular one in any particular cell it represents there is a land there and if there is zero in any cell it represent that it contains water cell it is water basically so if we have connected if we have a group of connected ones horizontally and vertically that is we are not considering the diagonally adjacent ones then a group of horizontally and vertically connected ones is termed as one island and we need to do some processing so that such that we do not have one island after our uh after what whatever we need to do so yes so if we see here it has only one island the we have four ones connected with each other so if we delete these two diagonal ones then there is no these ones are not connected as we only care about the horizontal order or vertically connectivity and if you see this example if we delete this one right here then it will disconnect this the whole island and we will have two islands okay and if you see here we need to delete these two ones in the middle if you are able to see at this one and this one if we delete these two then we will be having two islands and in this case we do not need to delete any land cell as still before the given input grid itself contains more than one island okay so let's see what we can do to solve this problem now uh as i just wanted to complete this problem or submit this problem during my contest i came up with a brute force approach by brute force well if you see here the maximum length of rows and columns of grid is 30 so let's say number of rows are m and number of rows the columns are n then m into n is just 900 which is let's say it is equivalent to 1000 so i came up with the solution whose time complexity is square whole square of mn so it will it is less than 10 to the power 6 so yes in future when we come up with more efficient solution we will surely either share it in the description box or come up with a new video so just for just to submit this problem during the contest i came up with this solution let's see this now so for this first of all i created my own defect function which starts with anyone and it visits all the ones of one particular or one particular uh island you know it kind of marks them and i can call that this dfs function on any one or any one of that of my island suppose i have a island this right here so if i call my dfs function on any of these ones after my after the complete execution of my dfs function i'll be sure that i marked all these ones so in one dfs calls so in a way if i do any then after this one i'm only doing my dfs function on any one which is unmarked after that so in a way one dfs function marks the ones of one island so the number of dfs function i would be making would be equal to number of islands in my grid as in one of my dfs function call it will visit all the ones of one island so if i am doing m number of dfs function calls then it also means there are m islands in my grid okay now the first thing i would be doing first of all without doing anything i'll try to i'll be finding the number of islands which are present in the grid the input grid itself so if the number of islands initially is greater than 1 then i do not need to do anything i will simply return 0 because it is even at this point it is disconnected i do not need to disconnect it any further okay now and again after that if i see i am also and also during my dfs function call i am also counting the number of ones in my grid so if i see the number of ones is equal to one here there is only one island no if i have reached to this point it means i'm only i'm having only one island okay so i'm done with this part even for if island equal if i'll number of elements is equal to zero i'll simply return zero at this grid is disconnected so at this point we can only care about not care about we have come to the situation or uh scenario where we are having only one island in our grid okay so i see the number of ones i'm also counting the number of ones in my grid if i see the number of ones is equal to one then i delete i need to delete it and then i'll reduce my number of islands to zero then the answer would be one if the number of ones is equal to two then it only means the islands are connected the ones are connected in this way or in this way so in this case i need to delete both of them because even if i did one i one cell from here it is still one island and it is not disconnected so in this case the answer would be two now this is for one case and i have covered one another case suppose if m is equal to one or n equal to one that is if we are having one row or one column then i'm seeing if uh yep if i'm having more than two ones if i mean more than one two ones and there is one row one column then it can only be like this then i just need to one i just need to delete one cell in between uh if i accept the end points i just need to delete one cell it can be any cell except the end points of this row or column then i would be uh sure would be assured that be having more than one island so in this case the answer would be one now let's proceed further now this one thing i have another i have i observed during the contest is the answer in this case can only be 0 1 or two if you see even if the cells are connected in this way we just need to delete these two cells then it will kill this it will get disconnected and if the cells are connected in this way then we just need to delete this cell either we would be having this case and also there is one another case which was there in the example as well this one right here if we are having two bridges you can say these ones are similar to bridges which we have in graphs then we need to delete these two ones yeah you can come up with any other example you will see that answer can only be any one of these three values okay so there can be multiple examples as well at this point i think i won't be able to come up with a proof but if you come up with examples yeah this would be the case yeah even let's see one another case if i'm having yep if i'm having this array yeah this grid then what i can do i can simply delete this cell i can just delete this cell right here i'll show i will be sure that it is having more than one islands now i use this information okay i used this information to proceed further yep so let's see what i did as i have explained earlier my dfs function runs once for one particular island that is so number of dfs functions calls is equal to number of islands then what i am doing what i did was for each of the cell which is having value is equal to one so i traverse the whole grid which takes uh m into m time i tell the whole grid and i saw that if it is one then i changed change its value to 0 and then i performed my dfs function on the whole grid and i checked the number of islands i would be having if i delete this one i saw if at this point i was having number of islands greater than one then it also means if i delete this one then it will do the trick for this question then the answer would be one and i will i would be doing this for all the ones present in my grid and suppose if i'm not able to get number of islands more than uh one still the number of island islands it is one then i will repay i will again uh change it change this cell's value to one from zero like initially i change its value from one to zero i checked whether after deleting this cell after building this land would i be having more than one island if i see that i'm having more than one island i sim i will simply return one as the answer but if i see still the number of islands uh is one this then i will change its value back to one again and then i move on to other cells i would be doing this for all the ones and if at any one i see the number of element elements in the more than one i return one and if at the end i have traversed my whole grid and i'm not able to find any such one it means then my answer would be 2 because for after deleting any such one i'm not able to disconnect the graph or disconnect the islands then it means i must delete two land cells to disconnect my grid okay so that this is uh that was my approach the time complexity of this approach would be m into n whole square as i am traversing the whole grid it takes it has m into n elements and my dfs function call takes time m into n at max so if i multiply this it would be m into n whole square of m into n as the value of m and r is less than equal to 30 this will work as far as the submission is concerned let's see the code now yep first i have taken this uh visited array it simply tells me whether i've visited that particular cell or not this is the number of islands i would be having after my dfs call this is the number of ones in my grid and m n r m and n are the rows and columns so initially i have marked it as false all this lands as i have not visited them and i found out the number of islands in my grid for each of the ones which is which has not been visited yet i called my dfs function and as i've explained it earlier it means this one dfs function call represents one whole island so i'm crazy incrementing the island uh variable and also if grid is equal to one i'm also counting once which i will be using later if i see the number of islands in the grid initially is not equal to 1 i can simply return 0 even if it was uh if even it was 0 then the answer would be 0 and if it is it was greater than 1 the answer would be 0 in that case as well then i see if number of rows are is one or number of columns is one or we are having number of ones less than equal to two then the answer is if we are having two ones at this point we are sure that number of islands is equal to one okay so i we are only thinking taking care of this case now because we have covered all the other cases above now if number of ones is equal to two then is no way we can delete one cell and we are we would be able to disconnect the uh the islands the answer would be two in that case otherwise the answer is one and now the second thing which i was explaining earlier for each of the grid cell if it is one i am deleting it first of all i am the storing its index now i am changing its value to zero it is equivalent to deleting that lens cell and then i m marked all my grid cells are unvisited and islands at zero i initially i did island zero and then i found out they found out the number of islands i would be having if i delete this particular land cell and at this point if i see yep i was able to disconnect the islands as islands is uh islands is equal to two then i simply return one here okay and after that if i see that still the number of islands yep i think it should be greater than 1 as i think even after if i delete one particular land cell can i have more than two islands if i am deleting one particular cell yeah i suppose we can have that scenario let's see the example here suppose we are deleting this particular cell and uh yep the island is something like this so if i delete this then at the end we would be having three islands yep so our it should be island islands greater than one and we return one here as we are able to disconnect the islands otherwise we see that the islands is still one then we change its value back to one and i move we move on with other land cells we see we check the other land cells and even if after all this checking of all the ones present in our grid we see we are not able to disconnect the graph we simply return 2 as 2 is the maximum answer we can have in this case okay yep i like this problem and as told in initially when we come up with the a better approach and an efficient one we'll surely share it with you guys either in the description box or we'll come up it will come up with a new video so i hope you liked the video and please do subscribe to our channel as around 85 percent of our viewers are not subscribed to our channel so yeah take care and sayonara
|
Minimum Number of Days to Disconnect Island
|
pseudo-palindromic-paths-in-a-binary-tree
|
You are given an `m x n` binary grid `grid` where `1` represents land and `0` represents water. An **island** is a maximal **4-directionally** (horizontal or vertical) connected group of `1`'s.
The grid is said to be **connected** if we have **exactly one island**, otherwise is said **disconnected**.
In one day, we are allowed to change **any** single land cell `(1)` into a water cell `(0)`.
Return _the minimum number of days to disconnect the grid_.
**Example 1:**
**Input:** grid = \[\[0,1,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 2
**Explanation:** We need at least 2 days to get a disconnected grid.
Change land grid\[1\]\[1\] and grid\[0\]\[2\] to water and get 2 disconnected island.
**Example 2:**
**Input:** grid = \[\[1,1\]\]
**Output:** 2
**Explanation:** Grid of full water is also disconnected (\[\[1,1\]\] -> \[\[0,0\]\]), 0 islands.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 30`
* `grid[i][j]` is either `0` or `1`.
|
Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity).
|
Bit Manipulation,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
103 |
hey everyone welcome to Tech white in this video we are going to solve problem number 103 binary treat zigzag level order traversal so given the root of a binary tree we need to return the zigzag level or the traversal of its notes values so we just need to print the nodes in alternating directions at each level now we will see the logic and the code for this problem now let's dive into the solution so here I have taken the first example from the leeco website so initially I will start printing from left to right so I will start from left to right in the first level so this is my first level so I will first print three this is my first level then in the second level I need to change my direction I need to print in the reverse order that is I need to start printing from right to left so my result would be 29 in this level so I am just printing it in reverse order now in the next level I have to change my direction I need to start printing from left to right so here I will print 15 and 7. this is my result in this level right so at each level we need to create a separate list so I need to open all the answers in the levels in a final result right now we will see how we are going to do this so at start my queue will be having the root node and I will be creating a separate list level so where we will be appending the current level values so level will be used for that then I'm going to have the final result right and I would be also having a Boolean variable where it helps to change my Direction so which way I need to append in that level and I will be having two Loops where one will be for Q and one will be for level size right and here I have taken a variable left to right to keep track of the directions which is initially will be true since I am going to start from left to right for the root so first I will pop the top element so I will pop the top element 3 will be my current node then I will check the direction here it is left to right so I need to print it from left to right so if I need to print from left to right I will directly append that in my level I will open the current node that is the pot node right then I will append the left and the right of the root in my queue that is 9 and 20. so the left and right of 3 is 9 and 20. I will open that in my queue now I will open the level list to my result here it will be 3. then I will change my direction to false because in the next level I need to Traverse from right to left then I will make my level empty now again in the next iteration I will pop the top element which is 9 and I will check the direction it is false so now since it is false since we have to print it from right to left I will append the level list to my current node so basically you are just going to have the reverse order in that level so I will show you guys when I append 20. so now it's basically it's going to be 9 in my level now I need to pop the top element which will be 20. now I will check my Direction which is right to left so I need to open it in the reverse order now what I will do is I will take the current value and I will append the current level list so already there is 9 in My Level list so I'm going to append it like this will be my new level so basically you are going to have 20 command line right then I am going to append the left and right of 20. which will be 15 and 7. and I'm going to append this in my final result which would become 20 and 9. right basically that is the reverse order here then I will make my level empty my left to right will be true now I need to pop the top element that is 15 since the left to right is true here I need to open directly to my level then I need to append the left and right of 15 so that is none so I'm going to just pop the next element so I will pop 7 then I need to check whether it's left to right yes it is left to right the left to right is true then I'm going to append it directly to my level now since I have done with my notes I will append this to my final result where it will become 15 and 7. this will be my final result I will return this one right so the time complexity will be order of n and the space will be order of n as well now we will see the code 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 will have my edge condition that is if my root is not present then I'm going to return empty list then I'm going to create my final result so initially my Q will be having the current route and then I'm going to have my Boolean variable which is nothing but left to or right so initially I am going to print it in left to right direction it will be true at the start then I'm going to have a while loop I will run this while loop until my queue is empty then I'm going to have the level size so the level size will be the length of my Cube then I'm going to have my Lin level list I'm going to have another group where I'm going to run this Loop based on the level size there's a number of nodes present in that level that's what it means now I will pop the top element on my queue I'm just going to pop the top element then I need to check the direction so if the left to right is true then I am going to append directly to my level list right I'm going to open the node values to the level list directly if my left to right is false then it is my else case where level will be I'm going to append the existing level node values to my current node value right so basically I'm appending all the node values that I have already appended to my level list to the current no then I need to open the left and right notes of my current mode to my queue right I'm just opening the left hand right node if it is present I will be appending that to my then after finishing this particular level I will append the level list to my final result so at each and every level changes I will change my Boolean value to true and false I'm just alternating the directions so I will make left to right as true and false on each and every level we change foreign I think it's fine let's run the code as you can see pretty much efficient thank you guys for watching this video please don't forget to like And subscribe I'll see you guys in the next one cheers guys
|
Binary Tree Zigzag Level Order Traversal
|
binary-tree-zigzag-level-order-traversal
|
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[20,9\],\[15,7\]\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[\[1\]\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Breadth-First Search,Binary Tree
|
Medium
|
102
|
654 |
going to see the LOD question 654 that is the maximum binary Tre we are given the integer LS with no duplicates a maximum binary tree can be built recursively from nums using the following algorithm create a node whose value is in the maximum value in nums is a vector given to us in which all the elements are stored we have to find the maximum value stored in the vector and we have to make that value maximum value is the node of the tree so recursively we have to build the left sub tree of the s prefix to the left of the maximum value and the right s prefix to the right of the maximum value and we have to finally return the binary tree here is one of the example given over here is the nums in which the six is the largest element so we have to make six as the root node of that three and the left notes this is the S left of the root maximum value that is six so we have to make this three 2 and then one and the same for the right part as well 0 and 5 as the right part of the six is done so finally you have to return the node that six root node and that will get return so let us say the code of the question here is the code of the question first we have to check if num is not empty if num is empty then we have to return n as the answer so first we have taken a maxi variable to find the max value of the uh max value stored in the vector which we have initialized it as integer mean then we have to iterate hold the nor size and we have to check each time if numi greater than Maxi we have to update the Maxi value to numi and we have to store that index as well so that we canate to um uh push all the left uh subar and the right subar in the left and right Vector that we have taken respectively so here is the left vector and here is the right Vector we have to iterate the left till index I and uh we have to push this is the left part and the same we have to do index I +1 to num side and we have to index I +1 to num side and we have to index I +1 to num side and we have to push it in the right Vector then we have to initialize answer node as a new node storing the making the Maxi as the root node then we have to make the recursive call that answer left for that in which the left pass and similarly for the right Vector will be passed in the right recursive pole and the finally all the nodes will get stored in the tree and we have to return answer which is the note that we have cre created
|
Maximum Binary Tree
|
maximum-binary-tree
|
You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm:
1. Create a root node whose value is the maximum value in `nums`.
2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum value.
3. Recursively build the right subtree on the **subarray suffix** to the **right** of the maximum value.
Return _the **maximum binary tree** built from_ `nums`.
**Example 1:**
**Input:** nums = \[3,2,1,6,0,5\]
**Output:** \[6,3,5,null,2,0,null,null,1\]
**Explanation:** The recursive calls are as follow:
- The largest value in \[3,2,1,6,0,5\] is 6. Left prefix is \[3,2,1\] and right suffix is \[0,5\].
- The largest value in \[3,2,1\] is 3. Left prefix is \[\] and right suffix is \[2,1\].
- Empty array, so no child.
- The largest value in \[2,1\] is 2. Left prefix is \[\] and right suffix is \[1\].
- Empty array, so no child.
- Only one element, so child is a node with value 1.
- The largest value in \[0,5\] is 5. Left prefix is \[0\] and right suffix is \[\].
- Only one element, so child is a node with value 0.
- Empty array, so no child.
**Example 2:**
**Input:** nums = \[3,2,1\]
**Output:** \[3,null,2,null,1\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
* All integers in `nums` are **unique**.
| null |
Array,Divide and Conquer,Stack,Tree,Monotonic Stack,Binary Tree
|
Medium
|
1040
|
1,042 |
all right let's talk about the flower planting with no json so you're giving an ungarden label from one to n and then there's a red path so the path is going to be from x to y but the path is by direction or path so if you can go from x to y right you definitely can go from y to x all right so all the garden has more three path so this is not important so you want to choose a flower type for each garden so for any two garden connecting by the pack right so uh the flower can be one two three and four right it did it doesn't matter you have to pick one and you have to return the array where the answer i is a type of flower painting and the garden so uh let me just quickly explain what happened so you have what three garden right and in the past it's gonna be one two three one right and um so the answer could be what one two three could be one two four one four two three two one and so on right so uh there are four type of flowers you can pick but you don't want the comfort right so imagine you pick a color one for golden two so this could be about two this could be three or this could be four right so i mean two one three two one four right or this is i mean you can also do like this right four one three two one three i mean you can definitely choose a different type of flower you want and then you return but it has to be unique right so uh let me call this get rid of this and let's try another example so uh this one is easier one two or one two three two four right so they are not connecting together right so definitely pick any color you want right but not the same color right so okay this is too easy so how about this abolish you have four golden one to two okay two to three okay three two four okay four to one two three two to four okay this is pretty much a limited flower type you can choose so for example if you pick color one for the golden one right you cannot pick color one for here cannot pick color one right so this has to be a something else see probably not four just two for example two and you cannot pick color two here because this connects right so definitely this is the only uh only type of the flower you can choose and again you can pick uh you can definitely do like this right four or four over here one over here right but it has to be what um unique right so how do you actually do this i'm going to redraw the diagram again and quickly explain so i need to build a proof based on the map so i have a map i have to put an integer for the key set for the value so i will just i'll just record what's my path for the map so one it goes from two it also goes from what twos and three right and for the bottom two it goes from one and three right goes from a golden three you go from two and one right so i will traverse every other garden based on my current garden and this is going to be what this is gonna be my uh hashmap right then i will have to let me change another color then i will have to traverse this current map based on my return value so if you notice the number of the earn is going to be the length of the answer i mean the return value right so i will have to create a result array in the array right so this is going to be my in array the return type and for every single traversal for what i equal to 0 to i less than right i will have to create a taller array just based on the current index current gallon right so for current garden uh index i would have a individual color rate and this color array would just represent what uh the value for this uh hashmap right so i will set the value to 2 and 3 for the garden one in the color array to 1 so if i can just go over here so this is my color array and this is uh index from zero one two three and four right so the size of five be honest because you can have one uh from one two three four right four different color but give you extra space just to easier to type for sure and then what i would say well i would say for golden one i would say the two and three to be true right so i mean troop to be wine i mean uh based on this right and then i will traverse again i'll traverse again for the uh for the resort to set the color into my result so i have to see the color right if the color rate is not equal to one so which means what possible of this possible this right and this doesn't count because i'm not using this but i would like to put the extra space on it so i would just assign this and this i mean just either one of them right but i would traverse from biggest to the smallest uh just in case i am out of uh space right so i would say okay so i will traverse from uh this is gonna be my c equal to four to c uh equal to one something like this all right so this is gonna be going to be my solution so i'm gonna stop coding and follow along so that's map integer i set integer right map equal to new hashmap and i need to be clear my headset in my hashtag right math output at i equal to new hash set right so after i declare i will have to try traverse the path in the path right and i will say a equal to pass at zero and then b to have it one right but the index doesn't starting from what doesn't starting from zero right it's starting from one right if you notice the patch is always starting from one so i'm gonna subtract one right here all right now i can actually build a uh put the connection together right so i would get what i will get the get a garden a and add the adder connection at b get the garden b and commissioner a and this is going to be my graph so i will fill the graph based on uh this code and then i will have to create a return value return window right so i will try very do i listen and i plus right and for every single garden i will create a color array new size of what five right and then i will have to traverse the possible number you connect in the graph so this is going to be my one and this is from the i right so uh again this is like uh find out what are the garden connect to the current garden right so i would say what i would say the color ray and the garden no you know the one right so this is i need to set a color right and what garden right definitely at least garden right so i would say that equal to one so which means there is a garden connecting with my current garden and now is traverse equal to 4 c whether equal to 1 c decrement and then i would just find out if my color is c does not equal to 1 which means i didn't connect with another garden i will set the number in my result value at c right just think about this i need to find out what's the current garden with another garden right will all the garden coming together and if they are coming together i would say to one all right and then i would say uh the possible value right if a color if a garden does not connect with another garden which means does not equal one right so i can set the color to be what uh to be c right so uh this is going to be my solution and let me run a code shouldn't be the problem all right let's talk about time and space this is going to be a time and this is going to be a time so all of an although p and this is going to be all of n and this is going to be all those the maximum is going to be out of p for sure that if everything is connecting together over all of c so the worst case won't be what all of n times out of p so i represent the little error right p represent what length of the path and the size is going to be what the size is going to be all of p so this is going to be pretty much the solution and i copy public paste my quick notes if you didn't understand so uh this should be what all the valentines will appear right so uh this is the solution and i will see you next time bye
|
Flower Planting With No Adjacent
|
minimum-cost-to-merge-stones
|
You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers.
All gardens have **at most 3** paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return _**any** such a choice as an array_ `answer`_, where_ `answer[i]` _is the type of flower planted in the_ `(i+1)th` _garden. The flower types are denoted_ `1`_,_ `2`_,_ `3`_, or_ `4`_. It is guaranteed an answer exists._
**Example 1:**
**Input:** n = 3, paths = \[\[1,2\],\[2,3\],\[3,1\]\]
**Output:** \[1,2,3\]
**Explanation:**
Gardens 1 and 2 have different types.
Gardens 2 and 3 have different types.
Gardens 3 and 1 have different types.
Hence, \[1,2,3\] is a valid answer. Other valid answers include \[1,2,4\], \[1,4,2\], and \[3,2,1\].
**Example 2:**
**Input:** n = 4, paths = \[\[1,2\],\[3,4\]\]
**Output:** \[1,2,1,2\]
**Example 3:**
**Input:** n = 4, paths = \[\[1,2\],\[2,3\],\[3,4\],\[4,1\],\[1,3\],\[2,4\]\]
**Output:** \[1,2,3,4\]
**Constraints:**
* `1 <= n <= 104`
* `0 <= paths.length <= 2 * 104`
* `paths[i].length == 2`
* `1 <= xi, yi <= n`
* `xi != yi`
* Every garden has **at most 3** paths coming into or leaving it.
| null |
Array,Dynamic Programming
|
Hard
|
312,1126
|
1,710 |
hello everyone welcome to learn workflow in this video we will discuss about another liquid problem that is the maximum units on a truck we will understand what this question is exactly saying and how we can approach this particular question to solve okay so before starting this video uh if make sure to subscribe this channel if you haven't already for regularly code videos so this video question is uh easy level question and uh let's read it and try to understand what this particular question is talking about it says you are assigned to put some amount of boxes onto a truck so you are you need to put some boxes onto the truck you are given a 2d array that box type so here we have box type being given to us and where box type i is the number of boxes and then like box type like uh then now like within the studio array we have another thing like the number of units per box okay so it like box types has like two stuff in it uh on each row that is the number of boxes we have uh and also the number of units per box are available to us so that's what we have over here and uh what are these two things is that like the number of boxes is basically the number of uh like number of boxes is the number of box type of i like of type i like the myth element top type it element is like the number of boxes we have of this type and number of units per box is like or of each time i what is the number of units present in each box okay so there are boxes of some types a different types and within that we have like how many uh units are there in each box we need to check that okay i mean we are given away with this element now what else we have you are also given an integer added truck size so here you have a truck size and then which is the maximum number of boxes that can be put on the truck okay so that's the maximum number of box that we can put on the truck and you can choose any box to put on the truck as long as the number of blocks does not exist struck size so uh as long as the number of boxes we have uh does not exist like uh it does not so it seems like as long as you can put a any box on like truck as long as the number of box does not exceed truck size so we cannot put something more than the truck size but we can pull we need to check how many we can do right that's why the next line is like return the maximum number or total number of units that can be put in the truck okay so uh by the reading this question we can find that it is isn't it something more or less looking like our knapsack kind of problem where we need to put some uh stuff into our sack and then see what is the maximum number of items that we can put in our stack and load our sack like the maximum wise so it's a pretty common uh what you can say a pretty common question based on like greedy algorithm so whenever you see questions like this and you find that there's like uh we need you can basically understand it's the like normal napster kind of question okay and what else are there in the boxster you can see one three uh like one being the uh like type one okay and on type one how many boxes are there three boxes are there and like number of unit per box is three okay and this is the number of boxes uh one box is there and it has three units per box then there is like two boxes there of this type and there are like two units per boxes there and the third one is like uh three boxes are there uh over here and it's like uh it is more like one units are like one unit power box out there okay so what the basic idea is we need to maximize the number of units see what we need to maximize the number of units so what is the number of units is given on this uh like this is the number of news we have over here right so what exactly we need to do first thing sort the array in descending order based on this number of unit right what will happen for that if you solve the array based on this number of valid in descending order so all the items you will find at the top will be uh like having the maximum number of units per box right so that will be the maximum number of units you will find per box and then so that means you have you are saving space and also maximizing your number of units so you just put in one box and in that place you just found you got a much more unit uh much more units of item in it right and then you keep on taking up like as much as long as the truck size is not full truck is not full you keep on adding boxes from next like a lower number of units as well and that then you can actually figure out how this is done like as an example there you have we just read this example and it says the truck size is 4 and the answer should be 8 that's what they're saying let's try to understand the expression the explanation says like one box of the first time contain three on it two box of the second type contains two in it and three blocks of the third type contain one area okay uh so you can take all the boxes of the first type and second type and one box of the third type see how is it so there it is like uh one box plus two box so that is three boxes are done and then you got one you need to take one box out of this three boxes so thus you can you take a total of four uh per truck size right so see in that case you find that there is three plus two five and one from here the districts uh you need to done no uh what i did no uh finally like that's not the six units are done but how many is the size is like one into three plus uh two you will take here to two into two and then uh like two boxes having two units each and one boxes having three units each and one boxes having one unity so that's how we come to a result of eight over here okay so that's the idea behind this like that's how this whole question and i hope i can make you understand how this question is this is pretty much similar to our uh knapsack kind of problem so the first thing we will do we will like uh sort the box types uh array like this box type array and in descending order by the number of units per box that is the number of units per box i say uh okay so this will be uh this box types of i1 more or less i1 you can say and then out of that what you will need to do like we will iterate through the box drive and at each tip we should add as many boxes as we can like until we reach the truck size okay and we should add the number of boxes added multiplied by the units per box to our answer like the that's what we are doing here like uh number of units per box and uh like we are adding the number of boxes added multiplied by the number of units per box so that's the multiplication we are doing over here okay and then uh like at the same time what it will be best to do is like we will simply uh reduce the truck size by like how many boxes we added and then uh reduce the truck size to that okay so that's the idea behind this simply reduce keep reducing the trucks and if the truck says become zero we got our answer go ahead with the answer our answer we our answer is here and we'll simply return our answer so that's the idea we've got here so let's write this exactly in terms of code and then see how exactly it works for us okay how well efficient it is so let's uh write this code awesome so we find that uh this particular question works for us this is not the uh like fastest algorithm we have but this works for us so uh faster algorithm we can go ahead with something like a backup sword or something like that let's understand what we have over here okay like as i said just now so that's what we have basically so uh whenever there is an error as the sort is used you must know that it is going for like uh n log n like n being the box types uh array like uh this box type that is length what we have so that should be n log n with the complexity and then we are going for each of the items so that's a lot like order of n is here and then there's n log n is there so n log n will be the dominant one in this time complexity now uh let's understand further so what we did we simply uh did an iris dot sort like sorted out all the box step based on the second element bring we have over here is like uh number of units per boxes okay so there's a one we did we just uh sorted the array then we took our final answer variable as zero uh we just make sure that initial is zero and then we went through each of the boxes in this box type and then what we found or we just found out like we took the current value current developing uh which one is minimal the box size is minimum uh like either our truck size is minimum or our uh box of uh zero like our current box uh like the number of boxes we have over here is minimum so whichever is minimum we are just doing like uh in this case look like uh since we had like the number of uh boxes is minimum like the number of boxes was the minimum the truck size was minimum over here like only one unit was left in the truck size so what we did exactly we multiplied it with the current like with our b of five b of i was one uh like one over one unit we have so that's how we are doing over here okay and then we reduce the truck so we keep reducing our truck size and uh then we find that if our traffic truck says anyways uh reaches to zero uh that's what we gotta answer and if anyways like we took like all the boxes everything we got like uh and still some probably some truck sizes left for us that because we cannot do anything any further right so we will return the answer like we somehow took all the elements and that's the final answer so uh most of the cases that in between this step will written as the final answer but on some cases if our answer is like going out and like we have less number of boxes than the truck size so in that case it will be a final written answer so that's more or less idea behind this question and uh this question i like is pretty easy to understand more or less uh kind of concept is there also make sure you subscribe to this channel for regular lit code videos and also if you face any uh problem related to the understanding of this question make sure you just comment below i will be happy to help you out as well so uh thank you all for watching this video hope to see you soon in my next video as well thank you you
|
Maximum Units on a Truck
|
find-servers-that-handled-most-number-of-requests
|
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106`
|
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
|
Array,Greedy,Heap (Priority Queue),Ordered Set
|
Hard
| null |
84 |
welcome to december's leco challenge today's problem is largest rectangle in histogram given n non-negative integers given n non-negative integers given n non-negative integers representing the histogram's bar height where the width of each bar is one find the area of the largest rectangle in the histogram here's some visualization here we can see the largest rectangle is going to be an area of 10 in between area arrays 2 and 3 with a height of 5 and a width of 2. so this is pretty similar to the water container problem but let's see how we might solve this now the very first approach we might do the naive approach would be to find every possible subarray and just calculate the areas for each one and this return the max we can do that in a nested for loop it wouldn't be too hard we can just get the length of heights right here uh store the max equal to zero and we'll just say four i in range of n that's starting and for j in range of i uh 2n let's just calculate the height which is going to be the what minimum between heights from i to j plus 1. and the width which is just going to be j minus i think we'll actually need to add one there yes so uh if having that we can just calculate the store the max between the max that we have so far and the height times width and we turn the max so this should totally work and it does but it is a time complexity of n to the two power n squared and obviously we want to do better than that uh this would reach a time limit exception so could we find a o of n solution somehow well okay let's think about this uh if you recall with the water container problem that solution was using two pointers and that worked because all we cared about was the outside bars like say we started at two and three all we need to store wasn't in between these two but that's not gonna work here right because with this problem we actually care about what the minimum is with like in between this array so we'd have to check the whole between two and three to find the minimum of one and then calculate that and so that wouldn't work uh that ends up becoming an n squared solution again so wouldn't be any more efficient so can we do what else can we do well what about a dp solution or greedy solution again with this problem it's kind of difficult to do that because we need to figure out what is the minimum for each subarray so even if we went with dp we would have to have like a 2d array which really doesn't work because that just ends up becoming n squared again so really all we're really left with here is some sort of sliding window technique or using a stack now how can we do that well here is the key inside say that we had an array that looks something like i don't know 10 20 30 40 with the index numbers string stored here how will we calculate the maximum area for this well if it was like an increasing order like this it would be fairly easy right we can just start at the very end and pop this off we'll say all right pop off 40 and take our index number of three and the width of this would be what four so just subtract uh four oops let's get take four minus the index number which is going to be three so this is going to be the width and this will be the minimum height right so this would be 40. next we could take off this 30 here and this would be 30 and then get 2. so this would be 60 right and same thing right here we just take 20 and pop this off here and this would be what 3 so it'd be 60 again and so on and so forth and this actually is o n and this works because if we had it all in an increasing order we don't really care about these sub arrays because like this area here we know that uh this was this is going to be greater no matter what right like 2 20 30 this will be greater in terms of i'm sorry what i mean by that is it'll be greater in that um the width is always going to be longer and if we have like so say we start with 10 the only one we need to calculate is from 10 all the way to the end here right because 10 to 30 is going to be smaller than 10 to 40. since we know that 10 is going to be the minimum we could just go to all the way to the end so that's going to be our intuition with this increasing stack if we just store our information into stack then we can just calculate the ones that really matter and everything else we could ignore so how would we start well what we'll do is uh we'll have a stack as well as the max height then we're gonna have a for loop and we will pop off from our stack in a while loop and calculate the widths and heights using the index number that pops off from this for loop here so we need to have the index number as well as whatever height that we're pulling off in the for loop once we have that then we can store our max and append to our stack here and finally just return whatever is our max right okay so hopefully this will start making sense as i coded out so we'll have an empty stack first as well as the max height or max area being zero and we're gonna have a for loop we'll say for the index number as well as the height and we can just do an enumerate with the heights and we'll have to have a while loop here and what we want to do is create our stack to be increasing right so while there is a stack and let's see well there's a stack and the last item on our stack is greater than the height that we put pop off or that we're iterating on if that's the case then we want to pop off of our increasing stack because we know it's no longer increasing so what do we do well let's see uh first we want to get the width or i know we want to get the height which is going to be equal to whatever we pop off here so we'll go to heights and we'll pop off from our stack the rightmost index now our width is going to be equal to well it depends on whether we have a stack or not if we do have a stack i should say if there is no stack then we know we want to go all the way to the end right so the width is going to be equal to the index number that we're on because it'll just span the entire width otherwise if there is still a stack left then the width is just going to be equal to i minus whatever is last on the stack and we actually need to subtract one as well to get the width correct since these are index numbers so we popped off our while loop calculated the width and height and now he wants to our max right so let's get our max here to be equal to max equals max between max and height times width and finally we want to add to our stack whatever height or i should say index number that we just calculated now one thing to note is once we have gone through our entire array we might have a stack here that's just completely just increasing and that's not enough because we still need to calculate this increasing um uh increasing stack so to do that we could write another while loop here or all we can all we need to do is actually just add a zero at the end since we know that zero will be uh the absolute minimum so we just put it to the end so that way we'll calculate every single area and that would be it we just return our max after that so let's see if this works does look like it's working let's submit that and there we go accepted so this is a sliding window technique within increasing stack sliding windows are very popular questions in interviews so it's something that i need to brush up on myself because they're very useful but they're hard to come up with on the spot so i might eventually make a series about that i should definitely solve more of these sort of problems all right that's it so thanks for watching my channel and remember do not trust me i know nothing
|
Largest Rectangle in Histogram
|
largest-rectangle-in-histogram
|
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104`
| null |
Array,Stack,Monotonic Stack
|
Hard
|
85,1918
|
111 |
welcome to this video now we're going to solve a coding interview equation minimum depth of binary tree here's the problem statement given a binary tree find its minimum depth the minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node note that a leaf is a node with no children this is the problem statement if you're given this tree as input then you have to return 2 because the minimum depth for this tree is 2 and this is the minimum depth how we can find the minimum depth of a binary tree now let me show you how we can solve this problem let's suppose that this is our given binary tree first what we're going to do is that we're going to find the minimum depth for each node in our binary tree by considering the current node is a root node this is our root node okay we're going to traverse this binary tree in dfs fashion this is our root node the left of this root node is this node now we're going to find the minimum depth for this node 2 we see that left and right node for this node 2 is null now we're going to consider these two is our root node at this point we have left equals to null and right equals to null so we'll return 0 we will return 0 for null node then we're going to return to this node left plus right plus 1 and that is 1. this is the minimum depth for this node two so the minimum depth for this node two is one then we're going to visit this node three then this node 4 then the left node null so it will return 0 then right node now it will return 0 so 0 plus 1 is 1 for this node 4 will return 1. then we'll visit this node five then left node we have now so it will return zero right node we have now it will return zero now if we consider five is our root node then the depth of this node five is one that we can calculate by using the formula left plus right plus one then we have left equals to one and right equals to 1. here we see that left is not equals to 0 also right is not equals to 0 if we see left is not equals to 0 and right is not equals to 0 now we have to find the minimum depth by considering three is our root node we clearly see that the minimum depth when we consider this three is our root node is two how can calculate that we have ellipticals to one right equals to one we see that left is not equal to zero and also right is not equals to zero if we found any of them is not equals to zero then we're going to calculate the minimum depth for the root node in this case 3 by using a formula 1 plus max of left and right so max of left and right is 1 so 1 plus 1 is 2 in the sketch this node will return 2 now we see that left is 1 and right is 2 for this root node and this is our real root node now how we can calculate the minimum depth for this root node so we're going to use a formula one plot minimum of left and right so minimum of one and two is one so one plus one is 2 for this root node we'll return 2 and this is our answer now let me show you how my solution might look like into the code i'm going to go through our pseudocode using this tree as example first i'm going to declare a function mean depth that takes the root node then we're going to check if the current root is equals to null then we'll return zero then left equals to mean depth root.left equals to mean depth root.left equals to mean depth root.left so in this case it will point to this node 2 then again recursively it's called this mean depth functions then in this case left points to null at this point this mean depth function call with null node so it will return zero then right node right that we have now so it also return zero then we're gonna check if left or right is equals to zero then we're going to return one plus left plus right in this case one plus zero is one for this node it will return one then right okay we get ellipticals to one now let's go to the right of this root node this is three then left here we have null so it will return zero then right here we have null so it will return zero plus zero is one okay using this formula then right five then left zero then left null so it will return zero then right is null so it will also return zero plus one is one using this formula then we see that left equals to one right equals to one when we have this is our root node then this code will run it will return one plus min up left and right since left and right is not equals to zero so this node three will return two one plus min of one and 1 is 1 so 1 plus 1 is 2 then this is our root node for our root node we have left equals to 1 right equals to 2 okay this left equals 2 and right equals to 2. we see that left is not equal to 0 also right is not equals to zero so this chord will not run in this case then else return one plot mean left and right so one plus minimum of one and two is one so there is 2 so this will return 2 for this given binary tree it will return 2 so 2 is our minimum depth for the given binary tree and this is my solution to this problem the solution will takes big of n time complexity or n is the number of nodes in the given binary tree it also takes big o of n space complexity for our function called stack hope this concept was clear if you have any question if you have any suggestion let us know thanks for watching this video
|
Minimum Depth of Binary Tree
|
minimum-depth-of-binary-tree
|
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
**Note:** A leaf is a node with no children.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 2
**Example 2:**
**Input:** root = \[2,null,3,null,4,null,5,null,6\]
**Output:** 5
**Constraints:**
* The number of nodes in the tree is in the range `[0, 105]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
102,104
|
531 |
students will be discussing a lead code problem 531 a lonely pixel this is a medium problem so let's get into the problem so what it says given an MX and picture consisting of a black B and white W pixels it's done the number of black lonely pixel and a black lonely pixel is a character B that located at a specific look positions where the same row and the same column doesn't have any number of black pixels so the B is a black pixel in this example and W is the white picture so what it says so if we are looking for a b as a black pixel so that should not be repeated in this row as well as in the column if it is not repeating simply we have to add the count and if we take it the first row so uh so B we have a B on the second positions right second index it's not repeating on zeroth and one similarly we have to check the column 0 and uh one so it's also not repeating because we have w on first and second position so uh in the first row count is one similarly in the second row again it's not repeating because in the left and right side is a w and the top and bottom also the W which is a white lonely pixel similarly for the third row where we have the first zeroth index which has wide pixels and similarly is on the right side we don't have any white pixel repeating and similarly as we have on the top also it's not repeating so the total count is three as they have mentioned in the output so if it is if we land it on the chart so what we are trying to do is so uh this is white pixels in our case so this is white pixel so it should not repeat in the column as well as in the row so in that case we don't have any white pixel so just we added the one as a count plus when we move to the next row right so again we found one b as a white pixel so we again will check uh on the same column so in the columns we don't have it so and the similarities in the row also we don't have any white pixel repeating so again I have added one similarly it's like I will check for the next index I found one white pixels first I will check in my columns we don't have any white pixels repeating and the same in the row also it's not repeating so again it's a one total it's a three so three is the output in our case so how we will be implementing uh in code and uh I will still try it but it's repeating on the same row as well as in the column in the row as well as in the column if you pick this one right so again it's repeating because in the first index itself repeating and similarly in the row in the column also it's repeating and if we move to the next row if we pick this one it's repeating on the same row so the count is 0 for 4 year okay so now how we will be doing it in the programming so let's dig deeper in the elbow part so what so I will text right of the size M closing right so uh let me samp it to the problem so what it says so we have I'm cross and pictures they have given right so consider uh Blake is B and white is W pixels right so we need to return the count of such black cell that are located in a row and column with no other black cells that's what I said right so it's essentially like we need to have the count of a black cell in each row and the column so okay so we have m row and column so hence like we need to array an array row counts of size m to store the count of a black cell as well as we have to maintain a column count for size n to store the count of columns so we can do this by iterating over the cells in The Matrix and for each black cell 8X and Y we will increase the count at a row count as well as a column count by one so then we can just iterate over the cell once again for each cells for X and Y we will check if the count array row count and array like column count is one then or not if it is then we will increment the count of answer by 1 and the same answer we will return as in a result and out the black pixel so uh in first row right so this is a black pixel which count is one so only if we have one black pixel in this row so simple as iron cream increase in the column section and again like I will find out the next I will check in the next row if we have any black pixel so I found one so again I have incremented it in this row also I will check one here also like we'll check we have one simple is here also like we have one so the condition is so as I said like we have to create a call array and similarly we have to create a row arrays so row arrays these like if you found any black pixel so simply it will increment by once and same for a row as well okay so after incrementing the values again we have to iterate the same Loop to check uh check those values for the pictures they have provided it and we will check like wherever we have one count for row and column simply we will increment the answer and the same answer will return it so there we have to check three conditions so what are these three conditions the first conditions we have to check a picture I and J should contain white pixel and row count of I should have one count if it is a more than one count so simply I will say we will get to know like this is repeating in somewhere on the same row so in that case we don't need to increment the result and the second can the second third condition is same for column count for J if it is 1 then we will increment the result by a plus 1 and the same result will return it okay as I said like we need to create a two arrays right to increase the count first we need to find out the uh the length how I like ah we have to iterate right I'm cross and so first we'll take a m length same fold this is her row okay and for column picture zero Dot and this is your column so next thing like we have array stores for Excel so we need to create a true row count for M length similarly is for call count and length okay so first we have to iterate and we have to store all the row and column count in a row count array and column count error so I will be iterating first for my row 0 and same for column okay and we'll check the condition if we found the white pixel then only we have to increase the count of row and column so what we are checking pictures I close J if we found B then we'll increase row count plus same for call count okay so we are done with the counting part now we have to find out the answer because we'll check row and column values like it should contain only one count if it is a more than one count so in that case we have to skip that row okay again we will iterate the same Loop so instead of writing again I'm just working the same door okay so here what we have to write a three conditions the first condition we have to check pictures J should contain B and row count should be 1 as well column count also should be one if the condition matches then we have to store the count and the same count we had written okay so as I said like in the first iterations we have to count all the values and the second iterations we have to count the answer so there are three conditions first you have to check the picture should contain White pixel and row and column count array should contain one count if it is a more than simplest you have to skip it and we have to move to the next row run this problem let's see if all the test cases are washed okay it passes all the conditions let's submit this version okay so we made one small mistake so let's connect it will start it from M to 1. okay now it's fine okay it's running fine guys if you have any doubt please comment in the comment sections and thanks for watching this video please like And subscribe my channel thank you guys bye-bye
|
Lonely Pixel I
|
lonely-pixel-i
|
Given an `m x n` `picture` consisting of black `'B'` and white `'W'` pixels, return _the number of **black** lonely pixels_.
A black lonely pixel is a character `'B'` that located at a specific position where the same row and same column don't have **any other** black pixels.
**Example 1:**
**Input:** picture = \[\[ "W ", "W ", "B "\],\[ "W ", "B ", "W "\],\[ "B ", "W ", "W "\]\]
**Output:** 3
**Explanation:** All the three 'B's are black lonely pixels.
**Example 2:**
**Input:** picture = \[\[ "B ", "B ", "B "\],\[ "B ", "B ", "W "\],\[ "B ", "B ", "B "\]\]
**Output:** 0
**Constraints:**
* `m == picture.length`
* `n == picture[i].length`
* `1 <= m, n <= 500`
* `picture[i][j]` is `'W'` or `'B'`.
| null |
Array,Hash Table,Matrix
|
Medium
|
533
|
252 |
welcome back to algojs today's question is leak code 252 meeting rooms so given an array of meeting time intervals where intervals I is equal to start I and I determine if a person could attend all meetings so here in the first example we have an output of false and the reason for that is our first interval start is zero n is equal to 30. and then the next array is 5 to 10 and the final array is 15 to 20. so these two intervals are in between 0 and 30. so there is an overlap there so this is going to return false in the second example we have 7 and 10 and 2 and 4. these are not overlapping so the answer is going to return true so this is a good introductory question to intervals with this question the first step to solving it is to sort the input array and we're going to sort it based on the first values within the array so like the second example we have 7 and 10 2 and 4 we need to sort this just to make sure that it's easier for us to navigate through this problem so with any interval question I'd like to draw out the grid so we're going to go up in fives here so 5 10 15 20 25 30 and we're going to plot each of these arrays within this grid so 0 to 30 5 to 10 and 15 to 20. as you can see we have an overlap here and we have an overlap here so the key points in question involves the current end so let's just call this array right let's call this array current we have start and end so start is equal to zero and is equal to 30 and then we have current plus one we have start and end so how can we tell if there is an overlap between current and current plus one where we take this n value of current and we compare it to the start value of current plus one if the end value of current is greater than the start value of current plus one we have an overlap in which case we can just return false for our second example the first thing to do is to sort this array so we're going to have we're going to plot this out so it's going to be and here we can clearly see that there is no overlap because this value here so current end is less than current plus 1 start so the person could attend both meetings in this example so firstly let's sort intervals based on their first value so it's going to be a at 0 minus B at zero let's create a start variable which we're going to set to zero and an end variable which we're going to set to one so these are going to be the indexes within the arrays we need to Loop through intervals so as equal to zero I is less than intervals dot length minus one so we're doing minus one because we're comparing two values and this way by minusing one from the interval.length it means that from the interval.length it means that from the interval.length it means that we won't go out of bounds if intervals I at end so if the current interval n value is greater than intervals I plus one so current plus one start we can return false else return true so whenever we reach a point where current value at end is greater than current plus one value at start we can return false if that never occurs within this for Loop we return true because we have found that there are no overlaps within this array of arrays so let's give this a run submit it and there you go
|
Meeting Rooms
|
meeting-rooms
|
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** false
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** true
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 106`
| null |
Array,Sorting
|
Easy
|
56,253
|
1,765 |
hello welcome back let's try another lyrical problem 1765 map of highest peak so this is another BFS problem actually it is a multi-source BFS multi-source BFS multi-source BFS let me explain a little bit about the example and then go to the Whiteboard to explain my uploads for solving the problem after that I will go back to the code Editor to finish the coding so for this example one so this is zero and one means water after updating the water should be white so this is from the description so yeah because one is water but for the final result the water will be set to zero and then the water will be spread to the land from the beginning this is zero these three zeros means just land so for the first step this land will be one and one but after that yeah this land is also connected to here and here but this land should be updated to the nearest land plus one that means this will be number two now let me go to the Whiteboard to explain my uploads yeah because normally for this kind of a problem first of all we need to find the source because it's a multi-source problem where is upper a multi-source problem where is upper a multi-source problem where is upper Source other source is the water what is water is the number one inside the is water grade after fighting all those Waters we need to set the water to zero because our final result for this number one should be set to zero then we're gonna use the BFS to serve while you search it we need to add it to the numbers inside the Edgewater grid because if it isn't water it means this is land and this is land it is connected to the water it will be one and for this one it is connected to the land not water it means more distance the distance is two so we will set it using this distance one plus one it is a two now let me go to the Whiteboard to explain a little bit about my uploads and then go to the code Editor to finish the codeine as you can see I will use example 2 as our example so from here this is a the input is water let me move a little bit put it in the middle so this is water so here is a zero one zero and zero so one means water and zero means a land so from the beginning we're gonna fight the sauce so this is our sauce and then we're gonna spread for directions from the sauce so first of all this one will be updated to one and here it's connected updated to one and this updated to one and also this one should be updated to one because it's connected to this Source now this is our first step we're gonna put this node inside the queue now our queue has this node and this one and we're gonna pop out and attack this one so after that because this is connected after popping out this will be updated to two and this one will also update it to two because it's connected to this one because it will pop this one first yeah but how should we added it should be easier because after all we will set the ones to zeros that means for example this is a for example this one will set to 0 first after supplying we're gonna just use this grid yeah this grid will be this 0 Plus 1. so it is one and for this grid it is just this grid it is one plus one it is a two and also for this grid this number it is a software yeah for its neighbor it is at the top this one it is one plus one it is a two finally we started gonna return this is water grid yeah as you can see it's a template money source BFS problem because there's no yeah many conditions to talk first directly uses the money Source BFS template to finish the coding now let me go to the code Editor to finish the coding so for the coding as our template it should be always be RC let me finish my template so it will be less of its water and less of is water 0 now I'm going to use a queue and visited set the queue should be empty the queue and the visited set will be an empty set I also need four directions so the directions will be inside I'll set it to 0 1 and 0 minus one so the directions doesn't matter but we need to give four directions yeah I mean the sequence doesn't matter but we need to give it a four directions it means the top bottom left and the right yeah now this variables have already defined I'm going for the first step the is to find the multi-source is to find the multi-source is to find the multi-source so for the multi-source we need to Loop so for the multi-source we need to Loop so for the multi-source we need to Loop through the flow and columns so for say increase columns just need to update the grid we need attack if it is water equals to 1 it means at this position it is water so what we should do we need to put it inside of the queue first 2. iPad RC and visited set dot add RC at the same time we need also to set the is water grid for this position is water RC for this prison to zero yeah because this is according to the description if it is 1 so what we're gonna return this prison is will be set to zero after that we're gonna use all those zeros it is the other monthly source to spread for the BFS serves while search updated is of the grid connected to the water now I will use the PFS so for BFS yoq RC should equal to two dots pop left and I need to update the directions so for Dr DC in my directions and my new low and new column should be equal to R plus Dr and C plus DC now I need a condition tag so this tag will be for though it should be bounded inside the grid and also for the column this will be more than equal to zero and less than capital c and also I need to check the row and column this Tuple should be not inside the visited set I don't need to check if this is water law and column if this number is one or zero it doesn't matter because I just need to check if it is invisible to the set yeah I can check if this though and column equal to you know for example here equal to zero yeah because I'm going to check the zero but it doesn't matter we have to also check the low and column typo Not Invisible set yeah so this is why we don't need to check that because the numbers are done important because we're going to use visited set to add update it yeah here we our template is visited set so we don't need to check the numbers inside this grid yeah the log and column is 81 0 or 1 it doesn't matter without the check if it is not inside the relative set we're gonna spread to the BFS to search for the next row and column after thirds so we need to update the Q two dot append should be our new add new column and the visited set should also be added by this new low and new column then we can update to the is water grid so what is this water grid so and column it should be updated to is water where are we coming from RNC and what Foodway plus with negative two plus one so if water are say plus one so from here is water is set to zero and zero plus one so this will be one and this will be one equals to this one so its water is one plus one it is a two so final finally we just need to return the is water grid so this is exactly in place operation and the time complexity is just m times M times n yeah of the grid let's check the numbers it's not a big number it seems it is okay now let's just run it to text if it really works or I need many any mistakes yeah so the output this is a little one zero yeah it means from some place I made a mistake yeah let me check my seti RNC q1 deleted directions face water yeah let me print it out to the Edgewater glued first to attack if there's something wrong with my with water and let me also tax the visited set so this is water this one also decided to zero I didn't set it is still 0 1 0 yes yeah so it means is water RNC should be equal to foreign yeah no I had some mistake but at least I get the right result it is zero yeah and this is a zero one for my presence so it means this one yeah we are safe now I just need to yeah take care of these mistakes why it is audible ruins it means there's something wrong about here I also did a title it should be the column c-o-l yeah because should be the column c-o-l yeah because should be the column c-o-l yeah because I used the new column let me check if there's any other typos now let me run it yeah as you can see it works now I will delete the plate and submit it to track the speed or it can pass all the testing pieces yeah normally I need to delete the print otherwise it influences the running of the speed yeah as you can see it's pretty fast it's like 17 more yeah around the 67 percent of all submissions yeah it's like three seconds yeah you tell um basically yeah you can also optimize the solution by not using the ability to set by the numbers too yeah to as a mark of the BFS but it doesn't matter I think at least for me even we use our visited set it didn't have so much influence of our speed because it's just m times n is it still okay for this recordable grid thank you for watching if you think this is helpful please like And subscribe I will upload more difficult problem like this see you next time
|
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 |
1,897 |
hey everybody this is Larry this is day 30th of the legal day challenge only two more problems for the end of the year and today we get a easy one a problem to kind of rest the end of the year on I suppose we distribute characters to make all strings equal what does that mean uh okay so you given away of string words and in one operation pick two indexes and move any character from word I to any position in word sub J all right return true you can make every string in word g code using any number of operation and force otherwise oh it's just a move it's not even like a swap okay um huh I think the uh the intuition is that you know you have n is equal to the number of words and then now each character has to appear in uh or each character has to appear as a multiple of n right I think that's the initial intuition I'm trying to figure out whether there's like any edge cases where that's not true um I think the movement thing is you know makx it so that you don't have to worry about ordering because you can just like within the same word I guess as long as you have two words but if you have one word this is trivially true anyway but you have two words then you can just move it from one to the other and back to kind of you know reordering as you like and so then in that way you can normalize it however you like I think that should be it so let's um yeah so let's do uh let's add it up right so let's say we have count is equal to collections. counter and you can actually even just do something like word and I think that will give you what you want I'm just going to return Tru uh yeah so it just kind of sums up all the things um so I think that should be good right so then now um now we are just return um or C Mod n isal z for C in I guess technically is a V for V values better but yeah but count. values or something like that and I think that should be uh that should be good hopefully unless I an edge case and looks good 1369 day streak one more day for the end of the year um this is going to be linear time constant space or Alpha space if you want to prefer that Alpha space being the size of the alphabet right which is in this case 26 probably uh unless I didn't really pay attention but it doesn't you know I is 26 52 uh 72 whatever it is you know it's still all of alpha where Alpha is the size of the alphabet uh for space and of n plus Alpha time roughly speaking I guess technically that's bounded by and as well but yeah uh that's all I have for this one let me know what you think I mean it is a easy after all so maybe uh yeah we'll get a chance to kind of just rest but yeah uh that's what I have so stay good stay healthy to get mental health I'll see yall later and take care bye-bye
|
Redistribute Characters to Make All Strings Equal
|
maximize-palindrome-length-from-subsequences
|
You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_.
**Example 1:**
**Input:** words = \[ "abc ", "aabc ", "bc "\]
**Output:** true
**Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ".
All the strings are now equal to "abc ", so return `true`.
**Example 2:**
**Input:** words = \[ "ab ", "a "\]
**Output:** false
**Explanation:** It is impossible to make all the strings equal using the operation.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters.
|
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
|
String,Dynamic Programming
|
Hard
|
516
|
81 |
Loot Guys Welcome Back to My Channel English Video We're Going to Solve Sachin Rotated Edit You Saw This Gives Statement Hair Dyes and Interior James Todd in Decreasing Order Not Necessarily with Distinct Values Before Being Order Not Necessarily with Distinct Values Before Being Order Not Necessarily with Distinct Values Before Being Passed to Your Function Name Cicero Test Unknown Poverty Index K Sadhe Resulting there is like this for example 0 4 5 6 7 might video test pilot in research and vikrampur 5604 ki jeevan di adams after the rotation and interior target damru target in namaskar first it is not in us to is problem mein kya hai ek no0 giver It is ok but it is in sorted order in increasing order but what is it in the function which is salt add life, it will come at any point even after what yaar tension and here is the example ghee add it is said that you are here You can see in the example that it is 012 4578 and what all the functions here, I am given, what is this on the five index, it has been tweeted, okay protected here or is it okay that from here four five six Seven and here 0124 then on this side okay so here also till here what is the five index it is in the increasing order itself, the point after this is also in the increasing order just here is it at some point what is it that Just giver and debit here but the point here is that whatever is the phase before and it is in increasing and whatever is after this is this increasing map, then after such rotation there will be a given and there will be a target value which will be what to do. Okay, we will have to find out whether Redmi is present or not, then let's see how to solve this problem. Okay, so what we will do here is that we have to remind the started one, in this we will do Mittu if we will return the return forms, okay. So what we will do here is 2 point Hey take ly and okay we will mouth the aloe vera juice till this less money aa Lansdowne equal to and okay now what we will do here we will first check what is the target value Vellore Is it equal? If not then equal? If not then equal? If not then first we will check that it will be equal. If I can be the target and the other, it is possible that the value of both can be equal. The value of pallu and or alka of star and pallu and or alka can be equal then in that condition. We will click the button, okay, otherwise what will we do? First of all, we will check whether the target value is high, if it is more, what will we do? Yes, we will turn Allu forward to the site because it is in increasing order. If any person is more than here, then do this to them. Will move okay if mood will do if that what will be the target value what will be the less will be my cut from right side to side mills what is this side to left side so we will do this right this whatever is art school religions will move you towards the next It is not equal, we will check whether the target Ballu is more than my end or not, then we will check today, is it less than today, yes, he will free Kamlesh Kumar, we will check the speed, it is not equal, then we will see. On this side, what is meant by Else Pale, is it more than this, is it not the target, is it less, then we will check Olive and if it is less than, we will free it from the market, freed it, then we will check whether each one is equal. Have taken and one of the two is equal is the value equal here and the health of so here what we will do we will start a so then done from here was done for the present case we see here What will we do? We will take it out and take it. Okay, I will check first. What is the total? What is the value? We will take it and it is not from either of them. We will check the film. What is the market value? Is it more than the end? Is it more like this? Alaikum, what will we do? They will start doing mukra and then will check, is it more, no, not more, then click on the art, is it less than the wound? Yes, and is less than saliva, is it not less than saliva, is it more? Light cut means, it should have been on the side here too. It is not present and here the fiber is there and the height should be between 500 and 245, then it is not here also, that chilli, if both the conditioners are not feeling then we will do return forms, it will not be anywhere, okay do it here, Mithun will pause. Otherwise, let's code how to code, keep extracting these. The word brot is under right. And my daughter's size of eight is A minus one. Some people have accepted it. Will add it here. Left with request and right first set. Will check whether any of the two is lost or not Namaskar Amilitary is equal to target and Nam is right request you to target if either of them is lost Okay and then we will check it only Is my Nam I am left CIA more The target is more, Shimla plus will do the right thing, a specific terms, this is right and right se, this kah tari w kam hai, admission cord ko hai - - hai - - hai - - MP3 ringtone, trio condition mein koi feel karna hai, department system falls on the return meter will not be up, why No voice return file will give up worship submit to whatsapp meter thank you
|
Search in Rotated Sorted Array II
|
search-in-rotated-sorted-array-ii
|
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).
Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`.
Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 0
**Output:** true
**Example 2:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 3
**Output:** false
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* `nums` is guaranteed to be rotated at some pivot.
* `-104 <= target <= 104`
**Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
| null |
Array,Binary Search
|
Medium
|
33
|
815 |
hello hi guys good morning welcome back to the new video sub Changi I hope that you guys are doing good just let me know uh in this video we're going to see the problem bus routs another lecture of our series now you will see that this has been asked most frequently by Uber Tik Tok and phone pay no matter it is the records for last 6 months and the number is quite high so this problem is very important let's quickly jump on itself we are having the roots now it just represents uh like that a bus is traveling on this route itself so I defining my routs as given for that specific bus ID or basically route ID these all stops my bus will go through so I can just indirectly say that my zero bus travels in this sequence and for short the sequence is 1 5 7 and then again one so it will just keep on traveling in this route so it will just go through these bus stops my bus ID zero it will go through these bus stops 1 five and 7 and we keep on going through these bus stops in the sequence now cool now I am just asked to return the least number of buses I must take to travel from source to Target my aim is to take the least number of buses no matter what the route is no matter how many number of bus stops are the only thing is least number of buses let's quickly see the problem St itself let how I can visualize that if I just go and look back it is 1 127 I have stops 1 2 and 7 for sure I have marked them with the same color which means same bus so for sure I can travel from 1 to two or I can just choose to travel from 1 to 7 same with the same cost because for sure as soon as I enter a bus the cost for me is if I change a bus if I don't change a bus anybody can travel so from 1 to two I can travel and also from 1 to 7 I can travel with the same cost and then ultimately you will see that from Seven you can see it's kind of a junction that on like stop number seven you can have a bus white and a bus pink so you were traveling with a white bus or you can just say a metro line having a white line a pink line so you were traveling with a white line you just entered this blue line so for sure you were entering like you just took on the starting you just took a white line then on number seven you just modified that to a pink line and for sure does the does you requireed only these two bus stops or these two Metro lines now if you just go and visualize a better example just to have that visualization so we can actually see that let's say I make this example for you guys right and for every example I have written that okay it's the bus stop uh and for that corresponding bus ID or basically the bus number I have these all bus stops with which okay this bus ID will go onto these all bus stops now if I just visualize that to a simpler problem let's say if the color would have been all same now I would have asked you let's say you are walking or basically I ask you that okay at every bus stop I will charge you now give me the shortest possible money spent or shortest possible bus stops you should go to reach the target so what you could have done is you know that every bus stop you will be charged so you know these are the bus stops for you and you know that every bus stop AR will charge me so what you could have done is you could start off with this with zero buses or zero bus stops in one as you take one bus or like as you reach to do one bus stop you know that you will be charged so you will just go and say I reached these bus stops these both the bus stops are the shortest possible distance from me for sure both are at the one distance so I can reach both of them by just giving one cost okay next I can just give I can just reach giving two cost next I can reach by giving three cost next I can reach by giving four cost it's a simple BF Fest just is saying that every bus stop I will be charged so please minimize the number of bus stops used so you could have simp simply done is simply travel at each bus stop just try to reach that bus stop as fast as possible and from that go to other bus stops as fast as possible so from here itself let's say if I erase these uh back edges from here I can just go in one cost I can go both these places in cost two I can go both these a simple BFS just to reach bus stop in cost three I can reach both these places in cost four I can reach the Final Destination which is minimum cost I would require let's say if the graph would have been big on left side still I would have reached minum cost from the right side so I would have S my answer is four even if I can go by the bigger side from the left so that is one thing that if you modify and look that get every bus stop I will be charged but here it is not the case of bus stop it is the case of bus now I am just being charged if I change a bus I can take any bus stop whatsoever so now the problem is that I have to just take a single bus now I have just removed those back edges but still you would see that those would not be required for you uh provided like you can just in the initially you will just build it up but you will see that would not be that much required for you were starting with this node one now I'm just asking you earlier in just one cost earlier in one cost you only could reach one bus stop because you know that at every bus stop you will have to encounter a cost so you know that okay in one cost I could only reach one bus stop but now I'm saying that in one cost for sure you have a bus with you can just board any bus and that bus it can go to any stops and that is your cost so I know that okay I am at a source of bun I have two options I have two boards I have two buses I can board I can choose to board a white bus or a green bus I can choose to board a white metro line or a green metro line now if I choose to board a white metro line now for sure I have used a Metro One Metro I have used but options with me are I can by using just one Metro Credit I can go to bus stop 2 bus stop 7 by just using one Metro credit because I have boarded white metro line or white bus line I can now choose to go to stop seven in just one credit because it's just I have boarded a bus I can just get down anywhere I want same way I can just choose from the one because it's actually also a green line so with this green line bus stop I can go to bus stop 4 and bus stop five with this one cost so earlier what was happening was in one cost you was you were only going to the one bus stop now with one cost you can go to all these bus stops which are in this line so you know that at point one I have two lines which is a green line and a white line and in the white line I have and when I say white line I mean the bus ID as one in the white line bus ID one is going on in the Green Line bus ID3 is going on as you saw in the example white line bid1 green line bid2 right so I know that uh my node one is having both lines which is actually bus ID of which is it's a stop one so I know that this stop one it will encounter a bus having a bus ID of zero and a bus ID of two which is bus ID of zero which is white line B two which is a green line now Arian this is not given in the input with us right because in the input I am given corresponding to a bus ID what is the bus stop I'm not given corresponding to a bus stop what all bus IDs are there or what all different lines are there or what all different colors are there that is not given cool no worries we'll actually make a reverse map for it we'll actually see but we can make a reverse map for it that for every corresponding stop give me all the possible bus lines because if I know okay I have a white line and I have a green line then I would know okay on a white line I have a Node 1 2 and 7 and that is given to the question white line which is a bus ID zero I have Node 1 2 and 7 that is in the question which is given to us so I just simply get to know if I at a stop one I have these two bus IDs with me or these two lines with me on these two lines I can travel on these points on ID Z I can travel to1 2 and 7 on line two I can travel at1 4 and 5 and for sure I should visit every point at Max one because I'm just going greedily as close to as possible right one is already visited it's my source so simply don't visit them so I can visit 274 and 5 and that to in just one cost so that's how just the only modification you have to do is rather than earlier what you could have done in simple BFS starting from this Source you know the source is zero the cost of the distance is zero so the source is one cost and distance is zero you would have gone to a another Target which is like another node uh as a node two now the cost would have increased to 0 to one now in this you would have gone from 1 to 4 uh you would have gone to four node the cost have again increased to 0 to 1 so that would have been the case but in this you don't have to worry about it you just have from this starting node you will just see that from this starting note I can just go on to all these notes which is two I can go on to S I can go on to four I can go on to five and for sure the costing cut or basically the buses changed uh from there again just I just used one bus from Source I just used one bus from here itself I just used one bus right just simply on the previous number of buses used simply add a plus one if you just quickly go and for sure if you remember to actually keep track from a specific stop Point bus stop if I can reach that particular what all lines bus lines or basically Metro lines or basically uh different color lines I can go to from these color lines I can just know the different stops I can go to in that particular one cost so with this for that only I have to make the entire map from the bus stops corresponding to their bus IDs are basically the colors of the bus so that I can just simply do and for every of those bus stops I can just keep track of it as you can see that I have I will simply travel on my bus stops okay for one the ID is corresponding zero so just simply for one map push in a vector as zero for one you will see here also a two will also pushed so with this you can actually make your entire vctor now coming back again what you could have done is simply in your queue in your que you will have your actual bus stop and also the number of buses used in the beginning Source you have never used a bus because you are actually standing here at the source initially so what you will do is you can just use one bus now which means one cost now if I use if I just use a one cost what will happen is you just you can just go to two 7 4 and 5 I simply push that in my Q 2 7 4 and 5 and for sure the cost is actually 1 simply adding a one to all of them basically I'm just using one bus and this is all the options which I can go to now again from this again I can go to which means in the next iteration of queue I just try to fetch from the front of the queue and then try that I can go whatever wh I can I just say okay it's a two from two it's a middle um I can go to seven but that is already visited so I cannot go anywhere else okay that will not be used from Seven uh I can go where oh I'll see okay I can go on one but that is also already visited so I'll just keep track of what all bus stops are visited so that is one thing that I need to keep track of bus stops visited because I should not go to the same bus stops again and again uh that is one thing now for the this node 7 I'll just go and look okay uh bro uh okay you are at node 7 corresponding bus IDs give me those corresponding bides okay this node s will give me corresponding bides as this white line and a pink line okay white line was a bus ID of zero and pink line was a bus ID of one you will see that you had already traveled the entire white line earlier right you have enti you have entire travel the bus ID zero so for sure it's of no use to travel again that bus ID zero which means for corresponding to bus ID Z what all stops I have already traveled it one way is again I will iterate on bus id0 and then I will figure out okay I have traveled one I have traveled two I have traveled three that is one thing but you see I see that for sure if I know that bus ID zero is already traveled entirely so why to check it so what I will do is I'll also keep a bus visited that okay what all bus IDs are also visited so that I should not go inside that bus ID which means if I go inside the bus ID I'll just find bus stops and for sure I have keeping tracking of the bus stop being visited or not that is good thing but it's good to actually cancel that out before itself so I'll just keep track of bus visited also that okay if the bus is visited or not if this bus you will see that this entire white line is visited so simply don't visit it one is not visited okay this is not visited so simply visited then I will visit a three and a six I'll visit a three and a six simply adding a plus one in their actual buses traveled this four you will see it's in the mid it can go to five but five or five is already visited so I cannot go anywhere so don't visit anything from this uh for five again I have two options which are actually bid2 B ID3 bus id2 is this itself bus ID3 is the blue ID now bus id2 is green which is already visited so don't visit this but ID 3 I can visit it because it's the blue ID so I can go into this and for this I have options as 8 and six again for eight I can go and visit it's not visited for six ah I cannot because six is already visited because I'm keep keeping track of the bus stops visited right so I know that bus stops are visited or not I'm also keeping track of bus IDs or basically bus visited or not so that is also sure that okay this bus is visited or not so six is not visited cool so ultimately when I will be querying for three there will be no nothing to else to add for six oh six is my target itself so my number of buses used or buses traveled are actually two which is actually in the second which is I'll just keep track of as a pair of my actual bus stop and all so which means the current stop and also the number of buses traveled so with this I can simply get my answer so you will see that the complexity is entirely number of total bus stops being used now in every bus ID I can have let's say m number of bus stops for bus IDs are 10 bus stops are5 so at Max it will be 186 so that's pretty much it which means that you will just visit all the bus stops exactly once in the total entire particular graph structure cool that was pretty much it let's quickly jump on the code let's see the code if you go and look back the code so one thing for sure what we need is uh as we saw that uh we would be needing corresponding to every bus stop ID I need what is the bus ID so I'll just keep track of a map uh saying that uh bus stop to bus ID right bus IDs so this will make me sure that I go onto all of my um routes now I should go on in the indexing base so I'll just go on to my all routes now in this all routes I know that um the bus ID is actually number the I and also the uh entire thing which is the uh bus stops are this itself which is the routes of uh routes of I now I can just do one thing I'll just go onto all of my bus stop in bus stops so now I know one thing that for this corresponding bus stop this is the bus ID which is Bid which I have marked so I can just go and copy this up and just say for this corresponding bus stop just simply go and push back a this corresponding bus ID which is I have already found right B ID now when this is done I know one thing I have entirely got my entire bus ID and stuff for every corresponding bus stop I've got the bus ID so I will just now and use a q because I know that my entire thing is based on my queue and for that queue I should keep track of what uh which is the current stop so I'll just use off a current stop and also in the queue you saw that I have to also keep off track of the bus traveled so that is one thing but you also saw that I should also make sure that I should not visit things again and again so what I will do is I'll just keep track of the bus visited and I'll also keep track of the bus stop visited so ultimately as you will see that initially you are at a source so that Source will actually just be saying okay the number of bus visited are actually zero and for sure the I just visit this particular bus stop so I just know that this particular Source uh I'll just simply visit and just say that this bus stop is visited now as usual a simple cue that while my entire thing is not empty so what I will do is firstly like as you do simple Q you just get the size uh which is Q do size and then you just simply do and say uh like V of size minus because basically you just start traving the entire Cube for this entire queue itself uh you will have a pair which is in the front uh like we'll see what this pair contains so it will be just Q do front and for sure remove the whatsoever you have inside the front now for sure uh what the first value says what is the current stop and the second value says then uh bus traveled so far the number of bus travel so far so I'll just say p do second now just have a quick check that uh um if the current stop is actually what we wanted because ultimately you like you just usually have a check now if that current stop is the target itself now if that is a target uh oh bro simply return the buses uh you have traveled so far so that simply like return that now what I can do is I can just simply iterate on all the remaining parts which is um I simply go and iterate on my remaining number of for this corresponding bus stop what all are the buses we have which means at this bus off what are the number of buses we have so I'll just go and simply say uh bro uh can you please from the bus stop to bus IDs uh can I please get the buses I have so he will just say okay bro the current stop is this so for current stop these all number of bus IDs are there I just have a check okay if the uh this be visited which means if this bus is visited already bro please bro don't go into it so if the bus is visited I can simply say a bus if this bus is visited blo simply continue uh I in no mood to actually view you now if that is not so I'll just say okay for this corresponding bus what all are the bus stops so I'll just say and go on to all the bus stops corresponding to this bus so that information is stored in my route or basically routs um array so I'll just simply go onto my this particular bus all these stops and I will just ask considering that uh that particular bus stop is not visited also so I'll just say that b stop uh visited of this part ular bus stop if that is actually also true so simply continue because you don't want it now if this is not the case vaa uh you are good and for sure if this is not so simply also visit here uh just simply saying that you don't encounter this again and again condition because you are not setting it true now here also just simply mark this condition and set this condition as true itself so that is again for sure now ultimately what you have to do is just push uh my entire thing which is the current bus stop which is this particular because as you are on this particular bus stop so you know that you are at this bus stop out of the current bus stop you have got to this bus stop and for sure the distance travel will be number of buses traveled plus one now you can simply go and keep on doing it until unless you just actually return from your answer let's quickly see if there are no typos and stuff uh oh first time there are no typos great okay Co so that's thank watching goodbye Take Care thank you so much for watching goodbye take care bye-bye
|
Bus Routes
|
champagne-tower
|
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever.
* For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever.
You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only.
Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible.
**Example 1:**
**Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6
**Output:** 2
**Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
**Example 2:**
**Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12
**Output:** -1
**Constraints:**
* `1 <= routes.length <= 500`.
* `1 <= routes[i].length <= 105`
* All the values of `routes[i]` are **unique**.
* `sum(routes[i].length) <= 105`
* `0 <= routes[i][j] < 106`
* `0 <= source, target < 106`
| null |
Dynamic Programming
|
Medium
|
1385
|
88 |
hello everybody today we're going to go through lead code problem number 88 which is merge sorted array so this says you are given two integer arrays nums one and nums two sorted in non decreasing order or increasing order I like to call it and two integers M and N representing the number of elements in nums one and nums two respectively so we're going to merge nums one and nums two into a single array sorted in non decreasing order the final sorted array should not be returned by the function but instead be sorted inside the array nums one to accommodate this nums one has a length of M plus n where the first M elements denote the elements that should be merged and the last n elements are set to zero and should be ignored nums two has a l length of M so if we look at example one m is three so means the first three numbers are relevant and then the rest zeros we're going to ignore nums 2 is 256 and is three the output merges those two lists example two nums one is one nums two is nothing so we're just going to Output the one and again M represents the amount of elements in nums one and N represents the amount of elements in nums two example three nums one is zero nums two is one so returns a one uh m is zero there are no elements in nums one the zero is only there to ensure the merge result can fit in nums one and as a follow-up exercise can you one and as a follow-up exercise can you one and as a follow-up exercise can you come up with an algorithm that runs in O big O M plus n time we sure can Le code we sure can all right let's try to do that so this is the method that lead code gives us interray nums one the amount of relevant numbers inside nums one an interray of nums 2 and N denotes the number of elements inside nums two so the first thing we need to do is get rid of those annoying zeros inside nums one we don't need to concern ourselves with those so I'm going to instantiate or create a new variable nums one copy which is going to take be a new int of size M which is the number of elements inside nums one that we care about and we're just going to Loop through those until we get assign nums one copy equal nums one until we get just the three Val well using the example one from um the exercises this will just be three and we'll get rid of the extra zeros so the next thing we need to do is assign two pointers so we need to Traverse through nums one and nums two and Compare the numbers in each and or actually I'm sorry actually we're going to Traverse nums one copy and nums two and pointer one will correspond to nums one copy and pointer two will correspond to nums one two and we'll find the smaller of the DU numbers and then we'll stuff that back into nums because leak code wants the result to be in nums one so we're just going to Loop through those two numbers so I is less than M plus n so we're taking the values that are relevant in nums one and the values in number of values in nums two okay so here is our check so basically we need to say if pointer 2 is greater than or equal to n which means if we've exhausted all the numbers in nums two so we're out of numbers in nums two or we still have values in nums one copy that are relevant and nums one copy the value at pointer one is less than nums two the value at nums 2 then we're just going to assign nums one copy the value or poter one let's just say it's zero nums one copies zero into nums one and the plus here means we're going to increment pointer one afterwards so we're not we don't want to compare this number anymore we put in Num so we want to forget about it if the Plus+ was prior to the poter one if the Plus+ was prior to the poter one if the Plus+ was prior to the poter one then we would increment point of one before we used it but that's not the case here l else so this means that we still have values in pointer or in nums 2 that means we still have numbers to go through pointer one can still have values as well but this is basically saying that the value in nums 2 uh is less than the value in nums one copy or equal if they're both equal it's going to go into the lse statement and so then we just put nums 2 the value at pointer two into num one and that is pretty much it end the method so let's go through the debugger here and see if we can't make more sense of this okay so why is it not no helps to hit the debugger button okay so as you can see nums one is one two three z0 Z and only the first three numbers are relevant nums two is 256 three numbers there so we have a new nums one copy that just has the three SP three in indices we need and we're just going to put those three values in nums one copy so now nums one copy is one two three which are the three numbers we need out of nums one and we're going to instantiate the or assign these pointers to zero so now we're going to Loop through this six times M plus n 3 + 3 is times M plus n 3 + 3 is times M plus n 3 + 3 is 6 okay first time through so now we're comparing in nums one copy the one to the two in nums two so pointer two is greater than equal and false meaning we still have numbers inside nums two and we still have values to go through inside nums one copy and nums one copy Z is less than nums 2 copy which is true so we're going to stick the value in nums one copy which is actually the one we stuck the one into nums one but you can't tell because nums one already had one in there so looks like we didn't do anything but anyway so now we're comparing we incremented pointer one so now we're comparing two to nums 2 two and it's going to go down here because these two values are equal so it's not less than in this case and so we're going to put a two into nums two I'm sorry into nums one and increment pointer two all right so now we incremented both nums one copy so now we're comparing the two to the five so this should yep there we go so it should go into this first case and add so there now we see num one has changed because this used to be three but um we added the two from um where is it yeah here nums two our nums one copy okay so now we're going through here and we're comparing the three to the five and so now we add the three into nums one so now we've actually gone through all the numbers in nums one copy so this is just going to add the remaining numbers five and six to nums one and you see there it's added 1 2 two 3 5 six and we return that and you can see up here that it is 1 122 356 which if we go back to lead code 1 22 3 5 6 is the result we should see all right while we're in lead code let's just uh run this and then submit we are amazing we're always the fastest submission and use less than 56.93 memory percent 56.93 memory percent 56.93 memory percent memory okay so finally I'm going to go through the time and space complexity so time complexity in this case is M plus n as we increase the amount of or numbers the amount of elements in nums one or nums two the execution time goes up then space complexity is O of n so same thing if we increase the values in M or n then we're going to take up more space and that is it so thank you for watching good luck in those interviews and we'll see you next time
|
Merge Sorted Array
|
merge-sorted-array
|
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
|
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
|
Array,Two Pointers,Sorting
|
Easy
|
21,1019,1028
|
80 |
so Elite code has this top interview 150 questions list I have done the first three so let's continue and see if we can go through all of them within a few months all right I've recently started to Learn Python so I'll be putting python this is a medium problem it's so similar to this except that now we're keeping each element at most twice instead of just once and we want to do it in place with a constant extra memory um okay um so I remember for uh remove duplicates from started every one we were traversing we had two pointers and we traversed the array once and that was enough to do it in place so now we just need to keep each element twice but I'm thinking that we could have one additional counter that just counts each time we have a new element we count how many times it's appeared and if it's over two we just skip to the next let's try to implement that and see if that works okay let's have a counter starting from zero we have two pointers one is pointing at which position we are at right now and the other one is pointing at so for this example one will be pointing at where we should add the next element so when we are here for instance what we'll be pointing here and the other one will be pointing there and these will skip so one pointer let's call it index um the other one let's call it precision or just use I to go through the array oh will we Traverse this oh no I forgot to start the timer uh okay it's already been four and a half minutes so we'll add that later okay let's focus I don't remember how to Traverse this it was a long time ago I did the last one um so it fits this wall so let's say we're here if it's the same as the last element and counter stays at two then we move on to the next otherwise we put that to here and then we increment the position and move to the next element as well let's see how we can start from the first one I mean the first logic that we have is if hmm otherwise because when we start they are the same they're both that's index zero and we move on to the next okay let's adjust this as we go so we move on to the next one there are at one now you move on to the next as well counter is at two and this is not the same as last you can start this at zero at one okay hmm foreign okay we started zero and contour and I starting that one okay first round they are the same and contrast the ones so we increment everything now position is at one I is two counter is to and they are different so what do we do then so these are different what do we do in this case can reset Contour to one and we move these along okay we will refactor this later okay so counters one again now I is here position is here so these are the same so the encounter becomes two I is here Precision is here okay so this is where we need to do something so it's the same and compare is to so what do we just increment to the next okay so now we have now eyes here position still here counter is due to move on to the next and now we have position here I is here it's not the same so in this case we want to move this to this position and we will do that um so they are not the same and counter is to so you want to put this one here positions this right here and then we wanna move all of them and reset counter so now positions here and we have index I pointing to this so this part eyes pointing to three so two is here we wanna counter is at one hmm so where was this case they are not the same just move along all the same okay there's this case they're not the same hmm I'm thinking that we only need this all right so if they are the same and we already have two of them though we just move on to the next one if they're not the same then we will put that in place and move along every index and reset Contour otherwise was the last case would be if they are the same but we only have one of them then we just move on to the next okay or the end okay um we will return this one that's how many elements in the end try this oh interesting hmm okay so one positions here we have I here we moved to this place okay the next one is three they are different again so what do we moved three we should move to 32 here okay I see so three is moved here and then they all increment um so the last one what happens with the last one same as position and counter was only at one so that's why it was moved so if they are the same and counter is at one this should happen as well okay let's just let's try that logic and then refactor later or cheat not sure if this is python syntax okay that's wrong if they are the same and counter is one foreign so these didn't get moved oh it's because in this case we need to increment the counter as well okay well this needs refactoring definitely so you move that and increment counter okay so that's the red logic we need to refactor this whole thing all right oh that took so much more time than expected it's okay it's gonna get better all right let's refactor this so we have this logic so for all of them we are gonna increment I foreign let's remove that oh wrong answer which is not quite sure just the right syntax but that's not the correct syntax um okay if I is the same as British or her one so here right here that's we only had one Point into that okay next one this is where it goes wrong are the same osc I see it's it was incorrect to remove that logic oh look at that I have already solved this back in February in C sharp I don't even remember that so what we need is this it's not really much refactoring though It's gotta be something better okay there's one thing I can take out the face this same element and we already have two we will continue if the same element we only have one and we will replace that and increase counter if it's not the same element we will replace and reset Contour to one otherwise we just increase the counter what is this question so this would be I mean we have same element counter one or two that we have different element I don't you think we need this case um and we will create the position okay that seems to be much better so you do not need this so we have one they are the same element counter one or counter two or they're not the same element that will replace and increase counter uh no recite reset counter and in the end we increase our partition all right I think that's compact enough oh let's look at some other Solutions this is my solution python okay that's surprisingly short if K is less than two so it's doing one update and so this is like my oh so they are not using any counter oh I see they completely skipped using encounter so they're just always looking at the last two let's see okay so for all the numbers for the first two they're just gonna stay the same okay and then for the third element 1K equals to if it's not Okay so if the third element is not the same as the first one so they're looking at the last element if it's different then we oh okay it's different we put it here hmm so like this so these two stay put and now we look at this case here if it's different we put this here next one different than zero we put it there this one is a different one nope then we'll just move on Is this different than one no moving on is two different than one yes so we put this two here so K was still here and the afterwards I suppose okay yeah increment k and then it's just different than we put it there so you want more time right oh sorry wow this is really smart I'm so impressed so smart um okay let's Implement that um so all we need is okay for all the numbers all these eyes are confusing to me so I'll just name it number if a really smart okay this video is long enough okay it will get better I'm gonna get better so uh time and space analysis so we are only traversing this input array input list once so that's so the time complexity will just be a love and linear and is the number of elements in the input and the space complexity is just constant because we're just using some pointers and we are doing this in place so linear time constant space okay I will look at some more solutions later but this video is long enough so I'll see you next time foreign
|
Remove Duplicates from Sorted Array II
|
remove-duplicates-from-sorted-array-ii
|
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements.
Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`.
Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int\[\] expectedNums = \[...\]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\]
**Output:** 5, nums = \[1,1,2,2,3,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,0,1,1,1,1,2,3,3\]
**Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\]
**Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
| null |
Array,Two Pointers
|
Medium
|
26
|
374 |
Hello friends, in today's video we are going to discuss the list of problem, gas number, higher oil, what is the problem, Egypt, you are in such a situation, that is why I and you are playing a game, what should I do, I will do it on a number which Bansi should write and enter. Someone number one Now I will tell you Who is this number Bone miss you hurt How is number 20 number diet What will you do Every if you did wrong by saying number What will I do to you Let me tell you that you have your own astrologer and number that means on my Why we it is small okay so what will you do to gas the golden number is near which has many planets in me this question will allocate you - planets in me this question will allocate you - planets in me this question will allocate you - this mixture is my virginity guest number system oil that oil or will button you in it dedicated The number is the cure from your guest number or the cleanliness must try that my number 51 is fine after making all your salt then it us what to do enter the number and dedicated if this is the problem you have the most basic HTC fold it If yes, then you always know that the numbers had become ours. Thank you. Let's read the air cleaner. This will tell you where you will deposit the cash. The answer is yes. Look at its code, then you will know that the most basic penance can be a shameless inch. We will delete the point till the festival, if it is successful then it will definitely ask, this is your answer, do it from Indore, otherwise your ID for transfer of whether this is a chapter problem for M.Ed Sangh, this is a chapter problem for M.Ed Sangh, this is a chapter problem for M.Ed Sangh, see this which is customer footpath 31st December 9 inches long If it is possible 108 times, then you will do so many Krishnas, then you have that time limit, I will give it once till the printhead, we can do it till the printhead, when you go above it, then what should you do if the time is erased, then you will have to do something else to optimize it. So if you were told that your number gets likes in the range of up to one second, then whenever you want to give a gift, then if you have patience then subscribe. How will it stay, sit and watch it, face half filled with water, you all must be knowing that - Well, if you don't you all must be knowing that - Well, if you don't you all must be knowing that - Well, if you don't know then do amazing about it and do write your thoughts in the description box - Very important urine, lots write your thoughts in the description box - Very important urine, lots write your thoughts in the description box - Very important urine, lots of good, very less problem. Turn it on in time, it is very important balance, so what do we do with the water of the house, the letter I A, as we know that hey Gave, this is which is Vansh or is equal to RK Hussain and N is what our It's 10:30 now this week N is what our It's 10:30 now this week N is what our It's 10:30 now this week go inter mit removed Android now understand to what is file so you did you five this is the question so passed but now I had established on number six so if I ask the man what is my number I am ignorant in the city, I will have to think that liter will do 110, then you will come to know that your number has increased from there, so what is the use of drinking this, if I am stuck in your ocean, then you will have to search the refinery top, don't forget this dish. Go friend, you don't have to use it in this - the advantage of this is that - the advantage of this is that - the advantage of this is that I fix it by half an inch, so now log in, get up and search, then it's okay, if half of the chilli is finished and let me tell you that it is yours. If you stay then what should you do with the oil, you send my play to Ali, I am now the entrepreneur of the valley 113 cigarette or you who are likes will be back now if you take it out in the army, this is Alpesh York Tuk, if you take it out in your 1622 Tamil Nadu will definitely come midnight, half the gas is there, now we have a question for you, if you pass it to the stomach then I am wondering what return will it give you here - you here - you here - liter - unmute so that our liter - unmute so that our liter - unmute so that our paste number is smaller than your paste number. I have seen the return result for you, if you get a return then what should we do here, forget this dish of ours that you are not in the fridge, you are one younger than here and I know you from the first letter that if you are bigger than white then I am Yagnik. Again the spot is over now how much crotch length is left Ali and Arya etc arrested according to depletion Quiet Mention makes its request and Kohli seventh okay now this one is done now if you now you middle adventure bittu kya hoga seashells is the person of 2017 Now you did six, which class six did you pass the patient, why did you get zero return this time, whereas if you got European, then the answer was on the medical store also got accused. Look, now it's your turn except Sacha Kheda, let's recharge all the strips, first, not this reference of yours. Now, are these references among these or have you tried the medium liquid again and if the one you sent is bad then leave it and get it with Edwina, after that we took out Aamir and then passed our time and got the result zero. So this is ours, if this is a plane, then I am your friend, what is your number, now what is this number, whatever you did, it is small, ours, then Namaskar, recruitment, celery, if you tummy, our page number, office number, boost, admit. I will be able to do simple things comfortably, set this light to low, it is loft, you can subscribe, okay, so click on the more button, next day, first of all, what will we do, one, we will go for the lighter balance but it goes left, start 121, this Right way we will start and enter the answer my will say enter answer is equal to zero ok now what to do boil daily wallet ok so what should we do first thing we will find out the unit of this we will write the unit like this email plus and minus llb -2 like this email plus and minus llb -2 like this email plus and minus llb -2 Okay, I will quickly add the middle two plus two subscribe video, if you subscribe then it means this is the result of this, what will you do, pass the flame medium of the gas and from there you will get some result if your if you have pimples, then you will get this. For work, do a medical store in the answer. Well, now do one. We have done the stitch with it. Now we will go to such a condition. Now we will make it if your result is laddu, zero, if less, then what will we do here Rs. Now we will mention 12, if this is the number that I have done and the number that you have done is 10, if this number of mine is smaller than the number that you have, then we will reduce our height range to this, like we used to do here. Address that you are my number six of is it for the stem cell by reducing the brightness to the house? Okay then media management is done, come if we are positive in this result house and my results from this, doing the number that you did, my page number. If it is big then you will do your admission here Lakshman will do it ok you will press your dream reference ok as you are doing yours what 5s did you do on mine and on my number is that stopping required I press the reference job muted If you go to Ad app and get the option then open it from Indore and return and subscribe to the commission, then it plays a very important role in our time job, skin, very good, very less time. Please subscribe me and many more. Subscribe this channel soon. Thank you.
|
Guess Number Higher or Lower
|
guess-number-higher-or-lower
|
We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible results:
* `-1`: Your guess is higher than the number I picked (i.e. `num > pick`).
* `1`: Your guess is lower than the number I picked (i.e. `num < pick`).
* `0`: your guess is equal to the number I picked (i.e. `num == pick`).
Return _the number that I picked_.
**Example 1:**
**Input:** n = 10, pick = 6
**Output:** 6
**Example 2:**
**Input:** n = 1, pick = 1
**Output:** 1
**Example 3:**
**Input:** n = 2, pick = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 231 - 1`
* `1 <= pick <= n`
| null |
Binary Search,Interactive
|
Easy
|
278,375,658
|
206 |
ladies and gentlemen welcome to another elad code question today is question 206 reverse linked list given the head of a singly linked list reverse the list and return the Reversed list so this question can be solved by just using pointers and how we can do it is just iterate through the nodes and as we iterate through the nodes we want to assign a previous node so we want to assign a previous node and iterate through the nodes and as we iterate the nodes we want to reassign the current nodes next to previous node so we're going to reassign the current nodes next to the previous node and iterate through the nodes and then at the end we could just return the previous node and the solution is of n o of one space o ofn because we have to iterate through all the nodes and of one space because we don't use any additional space other than pointers so we can start coding our previous node will start off as none and then we will iterate all the nodes so our current node is the head node want to reassign the current node and we will move forward with our head node and then we'll go back and reassign our current the old current next node to the previous node and then we can reassign current no we have to reassign previous yes so we have to iterate we have to move next first because if we have this line before this line it will change the next node and when we go to head. next it will be different from what we wanted to do yeah and then we just return previous node see if that works thank you for tuning in see you in the next one peace out
|
Reverse Linked List
|
reverse-linked-list
|
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[5,4,3,2,1\]
**Example 2:**
**Input:** head = \[1,2\]
**Output:** \[2,1\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is the range `[0, 5000]`.
* `-5000 <= Node.val <= 5000`
**Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
| null |
Linked List,Recursion
|
Easy
|
92,156,234,2196,2236
|
148 |
welcome to october's leco challenge today's problem is sort list given the head of a linked list we turn the list after sorting it can you sort the linked list in n log n time and o of one memory so the way i know to do that with sorting is generally quick sort but unfortunately we can't use quicksort with linked lists right and the reason for that is we're not able to jump index points easily inside of a linked list we can only move forwards so what can we do to combat that well let's start with the first approach by going to our linked list one time and appending our values into some sort of array then we can sort the array and rebuild our linked list so that would be the easiest method what we do is first have a current pointer point to the head and we'll say have a temp list we'll say while cur we will add to our temporary the current.value and then we're going the current.value and then we're going the current.value and then we're going to move our pointer to the next one so now we have our temp array with all the values in order we want to sort that and this is the part that's going to be n log n uh now all we need to do is rebuild our linked list right to do that i will have a dummy node that's going to allow us to remember the head and we'll say all right cur make it equal to dummy and we'll say for all the values inside of our temporary we will re-create our linked list we will re-create our linked list we will re-create our linked list we'll say curl.next equals the list node we'll say curl.next equals the list node we'll say curl.next equals the list node of the value and then move our current pointer to the next after that we can just return the head and we have that with our dummy node the dummy dot next is pointing to the head there so this works in times of in terms of time complexity it's n log n and but unfortunately we use o of n space as well as we have to recreate our linked list so that might not fly in fact this in a lot of ways is cheating because we're using built-in methods built-in methods built-in methods so what's another way that we can do it well what about bubble sort allows us to use constant space and we can use mobile server as a linked list right because we can move through the linked list in order and just swap values whenever we find the current node value is greater than the next one and we'll have to do it multiple times n times to be exact so this ends up becoming n squared but let's just see if we could implement this we first need to have the end because we need to know what's since we're moving the largest value to the end and then the second largest value to the second to the right of the end and so on so forth we need to know how many times we can do that so let's first figure out what n equals uh to that we'll have a current pointer and we'll just say while cur increase our end by one and move our point pointer okay so now that we know what our n is we will have to have our nested loop here and we'll have to have some iterator values to keep track of where we are how we'll have i equals 0 at the beginning and we will say while i is less than n and now we need another value for j and we'll say while j is less than n minus i and make sure that current dot next exists and i actually think we need to ensure the current here start with head every time and what we'll do is say if per that value is greater than the curve on next value we want to swap these two so that's fairly easy we just need to say current next dot value equals curve dot next stop value or not next so notice that we're not restructuring this linked list in any way we're just change swapping the values themselves uh and that's fine this would totally work um now we just increase our j like this and we increase our i down here like this after that we can just return the head and this would be constant space oh uh let's see record that value hmm if correct value card on next.value oops so it's my fault okay some typos there um there you go so this works but if i submit this it's gonna reach a time limit exception and the reason for that is unfortunately n log n time complexity so this isn't going to work either um it looked like it was about to work but nope it's not going to so what's another sorting algorithm that we know there's merge sort right we could use merge sort that is n log n time but we do need to use some extra memory to do that but i think for this solution we're just going to go with merge sort because um the way of using constant space is so complicated i don't think it's really worth me going into so let's just go with merge sort here and think about how we do that if you remember with merge sort basically we split our list here it's going to be a linked list into a left side and a right side right down the middle right so we need to get the midpoint at the midpoint and we will have to recursively call our sorting on the left side and the right side so recursive and then at the very end we will merge the two sides and return whatever the resulting list is there so we'll have to have some extra helper methods here we'll have one called finding the midpoint and this is going to pass in the head and just return the middle node as the mid node yeah the middle point but one thing to keep in mind is we also need to split our linked list as so that when we move through it will know to stop for the new left side so we also need to make sure to split this linked list and to do that we will use a method called the slow and fast pointer and slow fast pointer basically just has two points in the beginning one moves at space like at a range of just one moves up to the next while the other one moves next and as soon as that fast pointer reaches a point that it can't go to the next we take our slow pointer and get whatever is it's pointing to next that's going to be our midpoint and the algorithm works don't want to go into too much but that's just one of the methods of linked lists so let's first have a slow and fast pointer and what we'll do is say while fast dot next and the reason we need this fast on next is because we could have a null value here which is going to throw an exception and what we'll do is say all right slow just point it to slow dot next while fast point it to fast.next.next point it to fast.next.next point it to fast.next.next so once we have this loop here our midpoint is basically going to be the slow dot next and one thing to note is we need to get our slope dot next pointer now to be pointing to null this is how we split the left side and the right side so now we have like two heads uh finally just return the head or i'm sorry return the mid and our head now is broken to the left side while this midpoint is like the new head okay so now that we have that method we can say all right mid just pass the mid point passing the head and now we have our mid so now we want to pass our left and right side recursively so to do that both of these will return a left and right and what we'll do is just recursively call this sort list and we'll pass in on the left side the head and now it's remember that we've split it here so that it's going to end at the midpoint or right before the midpoint so now it's going to split like again and again while the right side we have to pass in the mid all right so now we need to have some sort of merge up merge function merge helper method and that's going to be we'll just call it merge and we will pass in the left and right and whatever gets returned here the new head is going to be the new sorted list so this is our last part we need to write our merge algorithm and this passes in what the left and right side and how does this work so to do that we will start with creating a dummy node and actually have the current pointer point to that as well and this will allow us to keep track of what's the head right all right so while there's a left and a right what we say is look if the left dot value is less than the right dot value oops less than the right dot value what do we do okay well first we need to have our current pointer.next equal to current pointer.next equal to current pointer.next equal to our left head right and then we're going to point our current to the current dot next so that we move our current pointer and we'll also have to move our left we'll say left equals left on next otherwise we will say card.next equals otherwise we will say card.next equals otherwise we will say card.next equals right on next and right equals right.next right.next right.next now once this is finished we know that we've completed one side left or the right so all we need to do is take our current on next and make it equal to either left or the right so it's left or right whatever is left if left is now null then it's gonna move to the right um if right was null then theory left should have some values left so that would be that so finally after that i think we just returned the dummy.next the same way because that's dummy.next the same way because that's dummy.next the same way because that's going to be pointing to the head in the very beginning all right so let's make sure that i got this right here just to reiterate we first find our midpoint and split the list so now we get the head recursively call that we also have to call the right side the new head here which is the midpoint and whatever gets returned the new heads we will merge them so let me make sure this works oh okay so it looks like i've messed something up here um hmm i'm guessing that we've because it calls so i guess we need some sort of base case here so say like if not head or not head dot next return uh whatever the head was passed in so i think that's why it's happening we need to have obviously it's going to keep calling if we don't even if we pass null values right so yep there we go so this does work uh my mistake let's go and try to submit that and there we go accepted all right so this i don't know um in some ways it's pretty basic in a lot of other ways though i don't think this is that easy and unfortunately i wasn't even able to do this in constant space this would be basically extra of n space but it is n log n time complexity how could we do it in constant space well they do offer the solution here if you want to take a look but it was way too much i mean this even this i thought was kind of long for a legal question to like write out so if you really want to know like go ahead and look it up but i don't think i'm gonna go into it today just don't have time so thanks for watching my channel and remember do not trust me i know nothing
|
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
|
338 |
such that for each I that I is lesser than equal to 0 greater than equal to 0 and less than equal to n answer Alpha is the number of ones in the binary representation of I so the question what they have given is because they are given an integer called let's say three and you have to written an array answer of length i n Plus 1. 3 plus 1 y 3 plus 1 because uh you need to find the number of binary ones in the binary representations eight integer from 0 to 3 so 0 to 3 means 0 1 2 3 so 3 plus 1. is the array size so we have to find how many number uh ones are present in the binary representation of all these integers and of all the integers so binary representation you know how it is 2 power 0 .1 2 power 0 10 to power one two power two this is fine so 2 power 0 means one it is two power one is two and two power two is four so if we take an integer three how do we get the binary representation of integer three uh 2 plus 1 will be three so both 2 and 1 will be one and the 4 will be 0. so this is the binary representation of three similarly for 2 if we take the middle one is two that is fine so only for that 2 we give one and all other remaining digits we give zero so this is a binary representation of two then similarly for one how do we do this one is fine by this is one and zero so there is one and if you take 4 we have this directly 4 that will give us all others are zero so these are the binary representation This Is How We Do the binary representations right now we have to check the number of funds in each binary representation so for in 0 of course it is 0 only because all are zero one two three this is 4 and this is 5. because 0 it is for one we have one uh bit containing ones then from 0 to 5. that is 0 1 2 3 4 5. in all this integral we have to find how many ones are there in the binary representation so all this we have to calculate we have to add and give written out so how do we solve this problem so initially so instead of taking all the zero count from 0 to 5 I'll take only one integer and the remaining integers are all other we can do like we will run give of course you'll give one for Loop or inside that I equal to 0 to n let's say equal to n so each number we will perform the same steps that is not a problem so I'll take now number five so n equal to 5. only for 5 we will see another will come as a so as I said here binary representation is one zero one how is it one zero one this is 2 power 0. 2 power 1 and 2 power 2. so 4 to 1 it is so 4 plus 1 5 you get hence for only four and one you give one and the remaining integer whatever is present you give zero so 1 0 1 is a minor representation of 5. now uh you know in one zero one how many ones are there two are there so initially let's say the count equal to zero we have to get count equal to 2 by the end of the procedure so how do you get this first with least significant bit whether it's one normal how do we check that is by doing and operation with one so the binary representation of one is one nothing but uh only for one we need to have the one and remaining zero so it is zero and one right so when you do an operation with one so basically it's what it is doing is it is looking at the least significant bit of the number which you are having and it's comparing with one it also has one at the least significant bit so if the number which you have taken has one in the least significantly it will of course result in one number right because one has one in the very significant bit so this will be resulted in one hence the count will get incremented count equal to one now so now for now this number is done what about the remaining one and zero we have to check for that also so one is done the remaining bits how do we take that is by doing the and operation is nothing but for no terminal operation right shift yeah that is by doing red shift right shift with symbolizes by one so right shift means nothing but if Q right shift by one that is five by two so five by two how much will you give will you keep 2.5 which is rounded off will you keep 2.5 which is rounded off will you keep 2.5 which is rounded off to 2. so now let's so now 5 is radius to two now we have done the right shift it is so what is the binary representation of two who is number four to one so only for two v e one then others are zero so for two it is 0 1 0 it is actually one zero right if a neglect the zero so one zero is nothing but this remaining digits here hence to remove the least significant bit and get the remaining which we do the and operation and to check the least signal we can pick whether it's one or not we do the and uh very sorry yeah to get the remaining bits except the least significant bit we do the right shift operation so right shift for getting the remaining bits and to check whether the least significant bit LSP is one or not for that we do the and operation with one why are now pressing with one because in one only we have the least significant bit as one all other bits are zero so that we can get to know whether the least significant bit in the given number is one or not easily by doing the end opportunity one so if it is with one because for the remaining bits we have to do one zero so one zero we have that is by two uh right here so you don't end operation with one now at this time we are checking whether this listing will be it is one or not so we are doing and authorizing it one of course this is not one because zero here present so zero and one will be zero one nine zero one two zero and one nine zero because for one who accept only the list will become zero and only the foreign zero one and you have to end with zero one so 0 1 and 0 1 now you could see zero one means only one we have got so at first one zero one was there for that we did the end operation with 190 uh now then we removed this one and to get only the remaining once it up we did the right shift operation by one then we got one zero so in that works we checked with and operation with one and with the least significant which is one or not ending clearer increase the count as per the result so after this instance we need to get only the remaining one for that whatever previous number was a two we give practice one so this is of course one way one and we will be zero and second will be in these two so after this is one negative two that is one by two of course it is so until you get the num whatever integer is that is zero you have performed this operation first you do the and You by doing the end you check the least significant bit is one or not so this one you increase the count of this one you decrease the count but the land operation results in one increase account otherwise we keep it as it is and then when once you do the and operation then you do the relationship I write shift to get the remaining bits so yeah first let's declare the array how to store another letter so in answer is equal to 0 I less than or equal to n and I plus here then initial as count equal to zero and let's say income equal to hi whatever number you have so while this number is not equal to 0 because at last until 0 you do the operation right the relationship should get one now zero so until that you have to perform the pressure so while num is not equal to zero as I said count equal to count Plus num and make one so this will divide them okay so once this is done after while look you get the account you have to store it in Array right so answer of I elect to be equal to the local stuff at last you return the answer that's it so in this case initially start with zero then you run for one so one and one will be one so that count will be incremented to one then one right shift one will be what it is one by one will be so like the Q2 for all the numbers yeah one by two that will be zero hence it will be stopped similarly for two also we start with two or two and one will be zero so count will be zero only and uh again you write it by 1 so 2 by 2 will be one and single for one and zero three also three again three by two then three by two three zero one and one by two that will be zero so four it will be 4 by 2 that will be two by two equal one and one by two it will be zero similar for 5 what we did it so we will run this I'll get it okay all right successfully submitted if you have any errors please drop it in the comment section it'll come up together with the next session and please subscribe and like the video keep running thank you
|
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
|
894 |
everyone welcome back and let's write some more neat code today so today let's solve the problem all possible full binary trees this is a pretty challenging problem for a medium because it's definitely different than a lot of tree questions you might have because it's definitely different than a lot of tree questions that you've probably already solved before we're given an integer n and our job is just to return all possible full binary trees we can make with n nodes so we actually need to build these trees now the default value for every single node we can assign is just give it a default value of zero so when we return a list each li each element in the list should be the root node of the possible tree the good thing is we can return the trees in any order that we choose so this problem it is going to mainly going to be about brute forcing this problem now you can actually optimize it and i'll show you the optimization we can do to the brute force solution in the code because i think it'll be easier but it's one of those optimizations that might not always be allowed so in a real interview i would probably check with your interviewer it depends on you know when they say return a list of trees as you can see below these are some possible trees we could create does each tree node the node of every single tree does it need to be distinct like does it need to be a brand new node like a deep copy or is it possible that we could take you know this subtree of three nodes and then place that exact same uh subtree over here to save us a little bit of time so basically creating a shallow copy right like meaning that these two trees are actually the exact same they just have a different root node suppose right so that's kind of what the optimization hinges on but i won't get into that now so right now let's focus on actually solving this problem now you do need to understand what exactly is a full binary tree they give us the definition here basically every single node in the tree either has to have exactly zero children or two children so suppose in this first example we're given n equals seven right we can see that there are five different trees that we could create with seven nodes now how can we actually do this like even just focusing on the brute force how are we gonna do this well every tree starts with a root right so we have seven nodes that we can choose on the right let's just say okay uh you know here we're gonna put our first node you know the value is always gonna be zero so now we really have n equals six nodes remaining so now the question is how are we going to brute force this right we're going to look at every single combination right so how do we even do that well we have six nodes remaining we could decide to put zero nodes on in the left sub tree right zero nodes at all and we could put all six of the remaining nodes in the right subtree and see you know how many different uh valid full trees does this lead us to right maybe it's impossible to even make a tree like this and based on the solution on the left you can see yeah it is impossible do any of these trees have a uh empty left sub tree no they do not and the reason is if you know by definition that won't be a full binary tree because every node such as this node has to either have two children you know a left and right child or has to have no left and no right child right so if we have zero nodes on the left and we have even a single node on the right then it becomes invalid so by noticing a pattern like the one i just mentioned we're trying to be smart and trying to see if maybe we can save some time and maybe we don't actually have to brute force this problem and maybe you can come up with one i don't really know a way that we can do that so unfortunately any pattern we recognize isn't really going to help us so we are still going to just have to brute force it so i would the recommendation i would give you for this problem is don't try to be smart just trying to figure out how you can solve it at all what we noticed though is to brute force so we could go through every combination so we could either have zero nodes on the left and six on the right or we could put one node on the left five nodes on the right or we could put 2 on the left 4 on the right and etc right basically every combination we could put 1 or we could put 0 through 6 nodes on the left side and then to calculate how many nodes we're going to put on the right side is basically just going to be n minus l where l is the number of nodes on the left right so this is what is going to be r which is the number of nodes on the right we're going to have to do a entire loop to actually determine that but the good thing about this solution is it's pretty recursive hopefully you can recognize that right because initially we have the problem of n equals seven right then we put one node as the root node and then we have the new problem n equals six right so then if we say okay let's put two on the left four on the right this four is a new sub problem right now we're trying to calculate how many different trees can we make a full trees can we make with four nodes and of course we're going to end up getting down to some base cases right if n equals zero then you know that's an empty tree so i guess we can just return an empty tree right we can just return null uh as the return value in this case what if we had n equals one that's also a pretty simple base case right we could just return a single node with a value of zero and you know just continuing if n equals two it's not even possible right then in that case we'd have to return null or uh you know since we're returning a list of trees if we were given two we would return an empty list because there's no possible full binary trees we can make with two nodes right if we take one node as a root node then we either have to put a node on the left or put a node on the right in both cases you know the node won't have two children and it won't have zero children so it won't be a valid tree so that's really enough for us to solve this problem one thing i will mention that you know since this is a recursive problem every time we compute the sub problem right if we computed how many trees can we make with four nodes we could cache that right we could put it in some kind of uh hashmap cache and then you know if we were recomputing that same sub problem then we could just you know have that list of trees stored for us and then we could return that instantly this will speed things up but it still won't be an efficient solution it will still be somewhat brute forcing and the real time complexity of even this caching solution is going to be 2 to the power of n now i don't completely understand how you can get to this time complexity because apparently from the leak code solution section there's quite a lot of math involved so i don't know if it would be super important to prove this is the time complexity in an interview so i won't go into detail on that okay so now let's write the code and like i mentioned we're going to be brute forcing this recursively i'm going to call it backtracking you can call it dfs or whatever you want and i'm going to put the function inside of the function just because that's how i'm used to doing it but you know you could declare this function outside if your interviewer would prefer that you can definitely do that as well now remember the two base cases we had so if n equals 0 we just want to return null now what this function is going to do is it's going to return the list of full binary trees fbts with n nodes where n is the input parameter right so if n equals 0 we can just return an empty list if n equals one we can return a list with a single node we can create a tree node uh with the constructor an empty constructor will have a default value of zero as defined up above so that's good for us now we actually want to return it don't let me forget to write that otherwise we're gonna continue with the brute force now the result remember is a list of trees so let's define that result and now let's actually build it so remember we're just brute forcing it so we're given n nodes one of the nodes is gonna be used on the root node of the tree and then we're gonna be left with n minus one nodes uh in python though if we let's say iterate through l meaning the number of nodes in the left sub tree in range n uh what this does in python is it will iterate through zero through n minus 1 nodes so this will just do what we already want it to do right it'll go through 0 through n minus 1 because one of the nodes was taken up with the root node so that's the all possible combinations we can have for the number of nodes in the left tree now to calculate how many we'll have in the right tree we can just do r equals n minus one minus of the number of nodes in the left tree right pretty simple math and now we're actually going to be running the backtracking the recursive part right so we'll have l is going to be the number of nodes in the left uh subtree so how many possibilities can we get so we're going to pass in l for backtracking right this will return all possible a list of all possible trees we can have and we want to do the same with the right so call backtrack on right this will also you know return that list of trees so we can say left trees and right trees is equal to the result of these two function calls suppose the left tree list has two trees right t1 t2 and suppose the right list has some trees as well t3 t4 uh you know and we also have a root node right so the question is how what are all possible full binary trees we can make so if we have a root node one possibility would be that the root node would have a left child of t t1 and a right child of t3 or it could have a left child of t1 and a right child of t4 or it could have a left child of t1 a right child of t3 or a left child of t2 and a right child of t4 right basically what we're doing is going through all combinations of these two lists by these two lists i mean the lists of possible trees in the left subtree and the list of possible trees on the right subtree so since we're just going through all combinations an easy way to do that is just a nested for loop on these two lists that were given so let's say t1 is all possible trees in the left sub tree and as another nested loop t2 is for the right subtree and each time we do this we're going to create a new root node right a new tree node uh the value is going to be 0 the first parameter the second one is the left subtree which is t1 and the third one is the right subtree which is t2 so we're creating a new tree a new full binary tree with n nodes right that's what this entire function was all about so now that we've created this what do we want to append it to our result variable because that's what we're ultimately going to be returning so we can create we can return this new uh full binary tree and then yes this is really the entire function this is the bulk of it and then once we're done with that we can go ahead and return that result variable and then to solve this problem we can just call our backtracking function on the input value n and then return the result of that now as you remember i did mention that we can optimize this problem a little bit with caching so let's do that let's first define our cache up above i'm just going to call it dp because it's short this dp will map an integer value n to the list of full binary trees that we can create with n nodes so you know these are two base cases another base case is going to be if n has already been computed so if n is in dp then we can return the result that was already computed and if it hasn't already been cached then we'll compute that result and then cache it at the end so we can cache it before we return just like this dp of n is going to be equal to result so once we've computed it then we will cache it so that we then next time we want to compute it we can instantly return that now a slightly more efficient way to do this we can see that these two base cases can actually just be thrown into our cache if we want to uh you know save a few lines of code so that's what i'm going to do so you know the one base case is with zero nodes we can create an empty list we don't we can't create any full binary trees and with one we can create a single uh full binary tree with just a single node so that's what we'll put in our cache right now we could even add a couple more base cases if we really want to write two is also going to return an empty list but i won't do that just because it's not really necessary in this case so with all that said let's finally run the code and make sure that it works and as you can see on the left yes it does and it is pretty efficient even though the time complexity is 2 to the power of n so i hope that this was helpful if it was please like and subscribe it supports the channel a lot consider checking out my patreon where you can further support the channel if you'd like and hopefully i'll see you pretty soon thanks for watching
|
All Possible Full Binary Trees
|
random-pick-with-blacklist
|
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tree where each node has exactly `0` or `2` children.
**Example 1:**
**Input:** n = 7
**Output:** \[\[0,0,0,null,null,0,0,null,null,0,0\],\[0,0,0,null,null,0,0,0,0\],\[0,0,0,0,0,0,0\],\[0,0,0,0,0,null,null,null,null,0,0\],\[0,0,0,0,0,null,null,0,0\]\]
**Example 2:**
**Input:** n = 3
**Output:** \[\[0,0,0\]\]
**Constraints:**
* `1 <= n <= 20`
| null |
Hash Table,Math,Binary Search,Sorting,Randomized
|
Hard
|
398,912,2107
|
56 |
huh okay let's do this hey what's up guys knee right here I didn't groaning stuff on twitch and YouTube check the description for all my information you could support me on if you sub to me on Twitch patreon whatever even just liking and subscribing or discord or whatever is awesome so I am streaming again I did this on stream earlier if you guys want to check valve for those I'm gonna try and do them a lot more but this problems called merge intervals very popular it looks like the method signature changed it used to be like a little bit different but you know I this one's this way is fine or whatever given a collection of intervals merge all overlapping intervals okay so what this is we have input like this like 1 3 to 6 you know each one of these it's a 2d array is the input and that's what we're gonna be outputting to and we're looking at the studio rate in each sub array is going to be an interval and it's going to be of size to the beginning of the interval is the first element the ending is the second element beginning first element ending second so some of these intervals overlap like 1/3 some of these intervals overlap like 1/3 some of these intervals overlap like 1/3 and 2/6 overlap because to the beginning and 2/6 overlap because to the beginning and 2/6 overlap because to the beginning of this interval is less than the ending of this interval so you could see if you were to like plot this out kind of number wise you would see ok one and then two and then three and then six in like this would be the first array you know 1 2 3 and then this would be the second array and there's a little bit or well you know what I mean like 4 5 6 or whatever this would be the second array from 2 to 6 if we're doing inclusive or whatever and this would be the first array and they little whatever we're calling a overlap that would be the overlap right there right so that's what they mean they just want you to output the overlap version you want to merge them so that you take the beginning the right here and then you take the larger of the ending values if they overlap so we put six in this case and it's a pretty simple problem you kind of just loop through and you do exactly what we just said there's no moreover it's fun there's basically two conditions you check a current interval in the next interval and if the next interval is beginning is less than the current intervals end you found an overlap like in this case and then you merge them otherwise you just keep going on your way and they don't merge so it's fine you just put them into the output or right as you go like eight ten comes after you know this comes out the beginning comes after the end so it's fine the only case is where the beginning does not come after the end of the previous one and then you merge them and it's actually we're counting equals two so it's this has to be greater than or greater than not if it's equal we still merge so that's the whole thing you just merge them the output to do this we are going to first thing we'll do is we'll just check okay if intervals dot length is less than or equal to one that means there's either zero intervals or one interval as the input and we could just return intervals because like we're not going to be merging in or any intervals that see that means that there's only one interval and the whole input or there's nothing so that's it with this return it we are not able to assume that this is sorted so that's kind of annoying you do want it sorted because in order for us to check the current in the next we want to make sure the next has a greater beginning value then the current beginner value otherwise this method of checking the beginning value towards the end against the ending value isn't gonna work if like we're putting fifteen eighteen at the front like that doesn't even make sense so we do have to sort we're going to be using a comparator to sort so we'll do a raised dot sort and we'll take in intervals that's what we're gonna be sorting and we're going to pass in the current array in the next array so you could say array of one and you could say array of two and then you can use this function and then we'll do okay we pass in we're gonna be looping through current array and next array and we'll sort based on integer compare of array of ones first element an array of two's first element and what this does is it sorts our input on the first elements so it makes it look like this right it puts the element with the smaller first beginning value first so that's really nice this sorts our entire input here you could check that if you want to actually do this properly we're not gonna be able to I would like to do this I'd like to say output array is equal to new int because we this is our input this is our output 2d array just like our input but we don't know the size of our output it's gonna be different than the input size usually so if we merge it's gonna be different and we don't know how many times we're gonna merge so to deal with that we're gonna do a list of integer a list of int arrays called output array so in a ray list because you don't need to specify the size and at the end we'll be returning like output array I don't even remember this output array dot two array so you turn it into an actual array at the end it's a list and then we turn it into an array oops and then you pass in you know output array new int of output array dot size and then I think it's like this to convert it into the 2d array at the end so that's what you do I'm not a hundred percent sure that's completely ripe that's what I remember so the strategy here is just we're gonna take reference to a current interval and how we're gonna do that is we're gonna say we're gonna start it out and we're going to say okay current interval will be equal to intervals of zero so in this case it'll be equal to 1 3 right and what we'll do is we'll put this onto our output array right away we'll say output array add current interval so we'll just add a current what we're gonna take the first interval as our current interval we're gonna add that on to our output array so output array will be equal to this at first and what we're gonna do now is we're going to loop through the intervals in the 2d array intervals and we're going to say okay current begin is going to be equal to the current interval of zero that's the beginning of our current interval current end is going to be equal to current interval of one that's going to be equal to the end of the current interval and then we're gonna say the next beginning the beginning of the next interval will be equal to intervals whatever we're looping through all of the intervals like you know like if we have this input array we're gonna loop through each interval like you know interval by interval we're gonna go boom and we're gonna say okay next begin is equal to intervals of zero next end is gonna be equal to intervals of one and what we're gonna do is we're gonna say okay if our current interval is going to be the one before the next interval so we're gonna be comparing one three against the next one like two six if our current intervals end is greater than or equal to our next begins you know what I mean if three is greater than the next beginning that means there is an overlap there and what we can do is we can update our current interval we can update our current intervals ending value which it's already in the output array so our output array has this interval in we take an interval at the beginning we put it into the output array we're just like alright this is a nerville we're putting it in the output array and now we're gonna update the end of it to become the math dot max of whatever it was the current end so three versus the MER the overlapping intervals end because we want the max of the overlap ending so we sorted it and now we know that these are overlapping and we want maximum of these ending values so we check it against the current end in the next end and we update it here and just updating it here since it's already in this array we can update it within the output array by just doing this so we say current interval was added on to output array same current interval of one changing the ending boundary to math dot max of these ending boundaries right here three and six literally changes it within the output array so we don't even have to remove or add or anything we just keep going otherwise now here's the part that is important otherwise if the intervals are not merton if we're not gonna see a merge meaning like eight ten comes after to six and that's fine they're not getting merged what we're gonna do is we're gonna say okay let's update our current interval now to interval the next interval that we're looking at so we'll update it to like eight ten or whatever and then we will add on to our output array we'll add it on to our output array in the process completely restart so we just do output dot add current interval and this will add on to our output array eight ten and in that case that's exactly what we want to go onto our output array because it's fine and if there was another merging interval like for example if this was like nine eleven we would you know it would hit this point and we would see okay we'd update it and we'd see emerge and we update it in the output array and it would up to it would check the max of ten and eleven and we would just go okay 8a we'd update it within but it's not so in the other case we just keep going and we keep creating these new intervals adding Mon the whole idea is you put an initial interval onto the output array and then you keep going and whenever you see a merge you go until you're not seeing merges anymore and while you're merging you're just changing the end you're only changing the ending value of the current interval on the output array and you could change it from the output array just by referencing the variable within the loop so that's the whole idea here let me know if you guys have any questions about that it took me a while to kind of understand this like if you could see all this friggin freaking you look at all these errors I was doing it on streem if anyone was watching like there it took a while so cannot be converted into int intervals of zero sorry intervals of you have to put I of 0 always making typos but yeah not intervals of I've zero interval dude sorry you're looking at the current interval so not intervals of zero sorry what am i doing dude intervals of zero what int current interval it's an int array dude so many errors oh my god dude I don't want to do this again I don't know if I confuse you guys but doing that okay there you go that's the solution I don't really want to do it again sorry about the typos you take the current interval and you put it onto the array you keep going as you're merging them and you change the ending value from the output array but within the loop you don't have to remove from the output array or anything it's just since we added the it as a variable we can reference that variable even while it's in the output array and change the values to the maximum ending boundary if it's not getting merged we just move on to a new interval and add it on to the array if it's not gonna merge we just keep putting them on and while we do merge we just keep changing the ending values at the end you just convert it back into the integer the hardest part was probably just the conversions from list to int and make sure they're sorted because otherwise you can't do it all thank us for watching I appreciate you guys definitely you know hit me up on I'm just trying to stream again so hit me up on there and you know appreciate you guys and let me know if you have any questions see you in the next video all right
|
Merge Intervals
|
merge-intervals
|
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104`
| null |
Array,Sorting
|
Medium
|
57,252,253,495,616,715,761,768,1028,2297,2319
|
212 |
in this problem we have to search for words in a 2d board and uh for example you are given a 2d word where each cell will have a character in it and it will be from small a to small g and you are also given a list of words so you have to find which of these words in the dictionary are present in this board so what we will do here we will create a try out of this so we have put all these words into a try and this is the try for example you can see that e a t is here then r a i n is here similarly p and both are also here so what approach we will follow is that we will start from top left corner first cell so we will start from first row take all the characters and run a dfs from there and in dfs we are allowed to move in four directions top bottom right left not diagonally so for example uh you can see that o a t h is present here so we should return that this word is present your output will be only a subset of this so what we will do we will start from here o and we will see if o is present there is a branch corresponding to in the try or not if o is not there in there is no branch then we will return we will continue to the next cell but here we see that we have a branch corresponding to o so what we will do we need to trigger four dfss first we will go to right let's say this is order one or two three four you can take any order any of these four it's within the bounds that is it's greater than equal to 0 and less than equal to n minus 1 so n minus 1 and m minus 1 in both rows and columns so here o is valid so we do a dfs from o and we had passed a string empty string so for each cell of board do a dfs from that position i j and we will start with an empty string so here dfs 0 was called and string was empty then here we saw that o is present here so what we will do we will append the current character so s now becomes this o since we found it next what we will do we will look at these neighbors so there are only two neighbors so we will call dfs and this position will be 0 1 and the string will be this s that is o and when this is dfs on this is called we see we will see if this is the current pointer if we see a is present or not a is present so we will make s equal to o a and then we will again trigger a dfs for this a so we will trigger dfs on o a and it will be zero to so we will see that oaa is not present so we will return back next neighbor let us say we took this so we will call dfs on this cell is 1 and string is again o a then we will see the current string is t so o 80 is present so we will make the string equal to o80 and every time we will also check if this is end of the word or not for example this is end of word all others are false similarly this is also an end of word so oat is present but it's not end of word so we will continue dfs from here so we will look for oata it will call dfso ata it will fail it will not find it so return then next neighbor is oath so dfs and this is 0 1 2 3 dfs of 2 1. o 80 so the current character is h so we see where th is present or not yes and this is also end of the word so we append it to the result whenever we encounter end of the word we are keeping track of a common result where we will insert it and we don't have to repeat uh it multiple times since o a t and if this is h then we have oa t h and o t h in two directions o t h and the one in yellow so we don't have to put it multiple times so we will keep a set here and we will keep inserting it and finally we will return a list out of this set so it's very simple the algorithm only thing is that you will need to implement a try as well as dfs so the idea is very simple not much of complexity in the idea so let's start coding first we will write it in c plus then java and python so first we will need a try class and in try we will make everything public so that we don't need to uh we can keep track of the current node so we want to access the children directly although this is not a good way of coding you don't need to expose the members of a class but let's do it for simplicity and here we have small letters so we can take it off length 26. then we will define the constructor default constructor and we will create the children so whenever we will insert a new character we will create a branch there otherwise it will be null and let's also define destructor although you can skip this step since we will do a lot of dynamic allocation for different nodes it's better to define a destructor to clean the memory so we have defined uh the try and its constructor now we will need to define the insert function and it will take one parameter the word which we want to insert so initially current is at root node and when we insert it we will move our pointer there so current is here this pointer let's say we want to insert a oauth into it let's say we have an empty try to begin with so we have an empty try i want to insert oath so it has 26 pointers all pointing to null so we will see the branch corresponding to is there or not it's not so we will create it and this is current is here then we move current here the node that we created then we look at next character we see if this branch a is there or not if not we will create it and move current here and when we have inserted everything t h we reached the end then we defined that current dot end of word equal to true so that way we will be inserting different words if c minus a to get the index so and finally so we have defined the try now let's define our main function so we will need to also define a dfs so let's keep a placeholder for it we will fill it so if there are no words then we don't have to search for any word irrespective of whether board is empty or not if there is no word in the dictionary we return an empty vector then try so we will insert all the words into a try in this try so we have inserted everything into the try now we don't need to worry about this words everything is in the try and we are keeping this unordered set to avoid duplication and let's call it result then for int i equal to zero i less than board dot size plus i and we also need to pass this board here so we got one parameter for our dfs and we pass it by reference then we have this result we also need to update it in the dfs and again pass it by reference and what else we need uh an empty string from where to begin so every dfs will start with an empty string and that's it finally the role of this dfs from every cell is to fill this result and finally we will create a vector of string which is the return type for this so we can create a vector from a set using this pass the begin and end iterator so include every element of this set and create a vector and finally we will return this result v and now we will implement the dfs and here we passed this inj and then this result here we are passing the result we will not be adding type here we will be adding here and next we had string s so this is the current character ij and what we will do once we scan through it so let's say we reach here o a then we can come here t and this will trigger dfs on e sometime so we will come to e and it will again trigger dfs on o so we will go in cycle so what we will do we will whatever nodes are in the stack that is we are is in the process of dfs we will mark them as some other character let's say dollar so that when we come to e we will not take this path since this o is already in the stack or that will be denoted by some character let's say dollar so board i j equal to dollar and uh if c is equal to this special character then don't proceed further return from here don't trigger a new dfs on this cell so we have not passed a try here this will also need a try we need a pointer so address of this so we will see if there is a this entry is present in the try or not if it's present that is if t is not null then we will do something otherwise this branch does not exist so terminate this dfs and convert this board ij back to the original character see if the try is present then what we will do so we will keep a string so this was the s string passed from the calling node and here we saw that the current character is also present in the suffix in the prefix tree or the try so we have a larger string so we append this c to this and we trigger four more dfs for all the four neighbors uh starting with and we will pass this new and larger string but we need a bound check if i is greater than or i is less than board dot size minus one so max can be board dot size minus one so it should be less than that then we can trigger a dfs from here and again we will pass board then i plus 1 then j will remain same and result and this will be the new try t and what else this new string is and also we need to make sure that if this is end of the word then insert it into the result so if and next j is less than board 0 dot size -1 then i should be greater than 0 then only we can do i minus 1 similarly j should be if j is greater than 0 then we can call on this neighbor so we have called dfs on all the four neighbors and finally this will keep putting the results to this result set whenever it finds end of word so let's see redefinition of t so let's name it try we are using it as dry so i don't know why it was pasty or null pointer line 19. okay so if this is null then we will create it if it's there we will not create it so this was a mistake and looks like it works so let's submit and this solution is accepted so next we will do it in java hey so we have defined the try now we will define the dfs and let's make it private you so and the java solution is also accepted finally we will do it in python so yes so this is to get the sky value of a character so we will find the difference that will denote the index of that children so and we can use idx here and we have implemented a try finally we will implement the functions of this dfs and the main function so we don't need to pass board since we have added in the cells and also the result and now let's complete this dfs function self so and the solution is accepted in python as well
|
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
|
862 |
hey Chum here so again today we're going to talk about this it's called problem eight six to shortest sub-array with some at least K shortest sub-array with some at least K shortest sub-array with some at least K this is my first heart problem video so I will try to explain this as clean I mean it alright it's clear as I can so let's take a look what does this problem say here you're given an array so the array can be the numbers can be positive but it can also be negative and then you're given a target number K here so you need to find out the shortest sub array whose sum is greater than at least K is greater or equal than the K the first I mean naive solution obviously is the brutal force right so what do you do basically you just loop through you have two pointers you have two indexes and then starting from here and then you try to find out all the sub arrays that be n square right because you need the length of the array then for the four other sub arrays you need to find the square in spend spending n square time and then you just calculate some for others as arrays and then you compare them if they separate the sum is greater than K and then you just record the term the minimum length basically trying to keep finding the minimum length for our sub arrays which would be a time complexity will be unsquare yeah something like that and if you but what can we do better right I'll commit to it better so if you remember there's a like there's a similar problem with us also finding the shortest sub array is some at least K instead of random numbers that array only has a positive numbers right so what did we do about in that time so basically we just keep like two pointers we keep two pointers right so we keep with the pointer from here and then there's another pointer from here and we just keep moving we keep moving this right pointer forward and until we find out we find a sub summary which is greater than K then we try to shrink the left side right if and every time we shrink the left side we also remove that's the number from the Sun right if the evening them if the sum is not it's not a greater than K then we stop why we can stop there because we know since the sum is will always be increasing so the moment that sum is smaller than K we don't need to move forward because we know if we more keep moving forward will be it will be deep basically we'll be subtracting more from the Sun which will be invalid right but in this case that's why this problem it is it's hard because let's say here so from two miners one right from two is some is two and minus one two minus one is one so here will be one and then let's assume in this case it's two then we see okay one is smarter too and then we'll stop but if you keep drinking if you just you add to here right and then you keep drinking you go to here and then the Sun will be three right and the three is greater it's greater than 2 then it's also a valid sub-array than 2 then it's also a valid sub-array than 2 then it's also a valid sub-array right so what can we do about this and the idea we're using here it's called a mono cue here so what does the amount of Q do here it will maintain the index for an increasing some and for the increasing some the reason we need the increase in some is okay so first I think the way we're calculating that there's some erase the some of the sub arrays we're doing the processing of the prefix up right so from array let's see and if we're trying to calculate the sub-array for the sum up the sub-array sub-array for the sum up the sub-array sub-array for the sum up the sub-array so what do we do a sum of here write some stay here and then sum of i right sorry this is J right so the sum of this sub-array will be the sum of J miners sub-array will be the sum of J miners sub-array will be the sum of J miners sum of I right so why we're using this prefix to calculate the sub-array sub-array sub-array instead of like the other one like which is simply removing the last one from the left right to get the new summary because well we have this miners that negative value here so the value we store in that queue is not contingent it would be like jump it will be jump from here to here because we're not storing all the values in that queue we are only storing the increasing some in that queue and okay and in that kill the kill right in the kill what do we say we save the index instead after the sum because with I mean with the index its we can calculate the because we need the index right we need the index to calculate the length so for example if in that queue that the index is its 0 2 all right that's the index right index and we said this is the Monica means the some are on those indexes and it's on the net zero two and four they're increasing right let's say for example the sum is and this is to write some is to so and let's say this is three some is three and index for is let's say six okay right so assuming we have this disc you here right and now let's say we see a new some like let's see the J here I see the C then you'll some is right let's say fill 15 from some 15 the next one yeah let's say that we have this 4 here and then the next sound the next index is 5 let's say this is 5 right so the 5 has some 15 and the K is okay let's see 10 here so with K equals to 10 we want to find out the shortest write a shortest sub array that the sum is greater then K here so what can be what can we do here since C okay notice so the index is increasing right in this direction and the sum is also increasing in this direction so if we check from the left side right basically we just use this sum and the miners did this some remember this is a sum right we miners this sum and then we get a sub array right regarded the seborrhea the sum of summer in this case sub arrays the sum of summer erased 13 right 13 okay it's greater than that 10 so it's a valid candidate and the index will be what so 2 5 minus 0 right this is 0 right so and then the length will be 5 less we keep doing it right big we keep doing it and because we know if we find another candidate also satisfy the sub the sum is greater than K and then we know it will have a shorter length because remember this index is increasing right we keep doing it until we find the next element that will make the sum the sub array the sum of sub arrays less than K then we stop so sorry so why we're doing this because every time when we saw a valid candidate we can remove it from the queue so that the next time we won't be processing this element again why because let's say if this one like I said if this one is the candidate right we just remove it because we know since we already record the length here we know the next one the next possible candidate will definitely has a smaller length will definitely tenth definitely have a smaller length so we can we don't need to consider this element anymore right okay I think that's the basic idea and also about this molecule here so why this molecule will help us right let's see here we don't need to insert all the element into this queue only so basically every time let's say current currently there's like this zero one in this queue right say the sum is 3 6 right 3 & 6 so let's say the sum is 3 6 right 3 & 6 so let's say the sum is 3 6 right 3 & 6 so let's say the next element what it let's say the next element is 4 right let's say the next element so 0 index to right this is for this atom the in that leads to here right let's say the next element index to but the sum is smaller than the first element right so what does it mean doesn't it means that with this element we can get a smaller we can get I'm sorry we can get a shorter sub array right because this index is bigger right let's say in the here will be like index like 50 years or something and the index is like 10 so that means in the future if what if we ever want to use this earth queue to calculate the sub the sum of the sub array with this new admin here we can get a smaller sorry a shorter sub array but with a bigger is a bigger with a bigger some right which will be out which will be a better candidate for us because remember we use this that current 50 try them to these substract from this value right which in this case this element is obviously a better candidate than this one right because see from this from here 50 - 60 see from this from here 50 - 60 see from this from here 50 - 60 50 minor six will it will be 44 right will be 44 how about the length will be 10 minus 1 will be 9 right but with this one the some of the sample rate will be 46 but how about the length will be 8 right obviously this one is better so we don't need to worry about this one that's the logic of Kip how do we maintain this Manik you basically every time because we are retreat we are looping from smallest index to the big the bigger one every time we see a new element which is smaller than the current top one we will just replace it basically we're not replacing we'll just keep popping it until we will discard the worse the worst candidates and we replace with the better candidates okay I know it's a long explanation I have tried my best ok let's try to code right okay let's try it to code and see how we can do okay so first like I said we need to maintain a pre prefix um array first right so we do a laugh in here a land here and then we'll create a sums of zeroes the prefix sums and the land here will be doing my and mine and plus one so the reason we want to a plus one is because let's say for the first element the first for the first sum it still needs to subtract something from the queue right to get its own sub array the sum of sub array but without a default value in the kill if there's if the sum is the first element right so the queue is empty was empty at the time there so there's no way we cannot calculate the sum of that sub array right so that's why we'll be inserting at 0 at the beginning and then we're calculating the so this will be some the prefix terms for the rest of the further for them for the a for into the array itself so we starting from 1 to the n plus 1 and then the sums I will be what will be the OB the a I minus 1 because we're starting from one here right since they were starting from one here two loops from the beginning of this from the a we have been it'll do n minor I minus one and then it's gonna be the sounds i right so this is a after this one will get a like a prefix some a prefix pre exam erase then we'll be creating like a queue to store the increasing that the indexes of the increasing sums right q and then of course the result will be system Mac size because we're getting the minimum of length will be initialized the result with the max value so we can always get a smaller one right and then we'll loop through the sums right some this will be a right pointer basically you can do basically it's also like a sliding window solution so I prefer to use the right to indicate the end after of my sub array so and then this is going to be the sum in subs right okay so what do we do here so first for each Sam right for each some in the end right in the for each some will check what first step will be maintaining the mono the model Q right so what do we do with while the queue is not empty right obviously if it's empty there's no point of popping anything from the key right and the current sum is it's not greater right it's eco or smaller than the first element of the queue right so why we do a an eco here because if it's eco one the current sum is still a better candidate because even though they have the same they will have the same sum of the sub-array the sub-array the sub-array but the current candidate will be worried will be resulting into a shorter sub-array right because the a shorter sub-array right because the a shorter sub-array right because the index is always increasing so in that case we still want to pop we still want to discard that first element right so now we have a we have updates that monarch you so the next step will be update the result right so still while queue is not empty and then now we're going to loop through trying to look through all the valley the candidates from that monarchy which and we have updated try to see if any of them can give us a valid result right which will be the some miners queue right the queue so now we want to check the first one remember the first one is as a smallest small this sum and that small is the queue right if this one it's greater or equal than the K right so what does it mean it means that from current index right from the current index right - to this index the current index right - to this index the current index right - to this index remember the queue we store the index right to this index sorry so yeah that reminds me so this is gonna be the a yeah since it's the index well we need to get the sum of that index there will be some index of that yeah so it means the away from this right from this index right to the index of this index - to right to the index of this index - to right to the index of this index - to the index of the q0 right if that if the sample rate if that some of the sub-array as it's greater than k right sub-array as it's greater than k right sub-array as it's greater than k right then we know we have a valid candidate but now i written then we just updates right we update the result we know we find like another candidate it's gonna be the right since the miners the q-pop yeah right since the miners the q-pop yeah right since the miners the q-pop yeah here at the pop remember so what did we say so every time when we find an candidate we can just discard it right because we know and if there is ever and another candidates that has a sub have the sum of the sample rate greater than K this will be a the length of the sub where it will definitely be smaller right so we don't need to care worry about this element and anymore we can just discard it that will increase the performance because we're not maintaining ever increasing Q right will be removing the Q and then in the end once we find that we find the that Q we finish updating the results don't forget we need to append the current sum to this Q right that will be so this will be the that the head off the Q remember so at this time we already pop everything that is smaller than the Sun so the disk you will be will still be mano-a-mano q right so in the end will mano-a-mano q right so in the end will mano-a-mano q right so in the end will be returned in the result right if yeah so remember it could be we never entered this thing here right then it means it's not a valid if they're third there's no valid rate result right so when then we'll be returning minus 1 if result is not equals to system max right size else minus 1 okay I think that's pretty much it is let's see the minus one come on range yeah numerator sorry yeah too many typing arrows because it's hard to type while I'm talking okay this one past let's see why yeah it's so easy to miss this thing because I'm keep telling myself this is that this is the Q stores the index but I'm still treating it as the value itself so it should be some right the index we use the index to find the sum to maintain is Q and it's still not right okay let's see what else are we missing here what are we missing here Q Oh like oh yeah pop left oh yeah okay I've totally for God so like I said we need to pop from the left not the right because the left side is still as the left side has the because we are checking that the left right sorry but checking from the left first and that's why we need to pop from the left and they still know oh my god this is a disaster I know I'm so okay so many arrows sorry guys so we're maintaining like the index sorry I keep confusing myself with this index and then some here okay finally yeah finally all right I know it's a long video but I'll try to recap what we discussed so first we maintain a prefix um prefix some sub-arrays prefix some erase so that we sub-arrays prefix some erase so that we sub-arrays prefix some erase so that we can calculate so that later on we can calculate it's this thing we can calculate the some of the sub arrays later all right and every time we see us a new some we're maintaining this molecule Monarch you with the index so that we mean we are sure we will make sure that the element in this kill will have its in will have its some be increased because we discuss about that right so that because that will be if we have a smaller one and then we know the smaller one will be a better candidate so that's why we just discard the worst candidates and then we just keep that always keep the better candidates and since we have all the other candidates right at this stage we have all the candidates we need in this queue and then we're just trying to loop through from the left to see if there's anyone any candidates that can give us a valid submarine then we just update the result with the with a smaller one so and remember here every time we have a candidate we can just remove it because we know in the future if we have a another one that satisfies the same as the condition here we'll have a solar array right so we can we don't need to worry we don't need to consider this one anymore then in the end we just insert this one to keep updating the model queue in the end it's like regular chat here okay cool guys it's a long video and yeah let me know if there's anything you wanna ask me okay cool guys it's a long video I'm a bit tired alright see ya thanks for watching
|
Shortest Subarray with Sum at Least K
|
find-and-replace-in-string
|
Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1\], k = 1
**Output:** 1
**Example 2:**
**Input:** nums = \[1,2\], k = 4
**Output:** -1
**Example 3:**
**Input:** nums = \[2,-1,2\], k = 3
**Output:** 3
**Constraints:**
* `1 <= nums.length <= 105`
* `-105 <= nums[i] <= 105`
* `1 <= k <= 109`
| null |
Array,String,Sorting
|
Medium
| null |
378 |
Hello friends welcome to my YouTube channel Tier-3 to Jhal Ajay, in today's video I have channel Tier-3 to Jhal Ajay, in today's video I have channel Tier-3 to Jhal Ajay, in today's video I have brought another question whose name is Cat Smallest Element in Sorted Matrix, so basically the question is of medium category and there are many different ways to do the question. But we will do the economical traditional method which will be the other wise method of binary search. There is more so let's read the question first given a question matrix given 14 columns expressed in ascending order written updates smallest element in the matrix so basically what to do is a There will be 1001 in which in roses and columns to get send a quarter we have to tell which is the smallest element so this time let's take glass on the score board like we have given a matrix of cases 129 adv1 phase do not take anything 1011 306 Now what is said in this that it is said that the smallest element has to be given, it is equal to Let's Support Key, so the first way to do the query is to keep traveling in the entire matrix and check that as soon as the address smallest element is found, the return is done but time complexity. If you laugh and go away, then let's do a binary search, how to do it? Now let us understand one thing that without the questions of binary search, one thing is common that it is a range, either it is one of the range, now we have to do something strange in this. Rate Jeevan is not there in the question, but we can definitely say that whatever answer comes, from this element of the matrix to this last element, this one in between is small, it is 101 percent. There is a range, looking at this remedy, it seems a little side that every binary search can be applied, so what is the life of the ranger that this maximum of Mansarovar will be under-15, it will that this maximum of Mansarovar will be under-15, it will that this maximum of Mansarovar will be under-15, it will not happen, after doing so much, what did we say? This we came to know that now the range is also included in the range, so the binary number, the first task is to tell us the middle element, if I say, what comes between 115, which is 18. Now the task is to tell us this. Because we had to find out how many means a small extent, we had to tell the absolute elements, so first we took out and checked how many elements equal to this middle element or smaller than the media, smart likes in it, so as I thought, I said that this dynasty also has this dynasty. If it is intimate with the lekar then small element should be made in most of the cases so in 108 I have job lets support only four these elements so now this roti makki is coming that if I have once admission four elemental something then it means I have to give my answer one If I can't meet on the side then why should I increase my range then what can I say that if the craft comes in countless numbers then definitely I will have to mute plus one on my lover point because this is because together So friend, if my work is going to be done then more will be done and if this case is made that how does the account come, if more comes, then unaffected Gomez - turn it on, it has become Gomez - turn it on, it has become Gomez - turn it on, it has become an album of basic binary search that it is of lage or and This has to be done to increase the lower point and reduce the upper limit - it must have been clear to you here, reduce the upper limit - it must have been clear to you here, reduce the upper limit - it must have been clear to you here, now let's talk about counting like this, so for cutting, we can do this that as soon as the phone stops every second, the last packet pointer is used. This IA point is this point on the faces, this is a fax on the last column, we checked whether this element will be a bigger target than the target, Middle East will definitely be, which is one, definitely increase J, decreased the nose, best point to dislocation. What is this element? It has increased from the melt. No, it is not big, so it means all the elements which will be behind it, what will be all these elements will be smaller than the target because the shots are in decreasing order, so we have given this account in our Regarding the difference, the meaning was out, it was added in the real, after doing so much work, now it is definitely a matter because when this limit was made, then below this limit, we have to drink, then because all this is increasing and this has been increasing. Therefore, in the scenario of the year, if we have never found any element in this row, how do you understand that this intake is marked? If I do n't find anything then no problem, I will go to the letters, the naturopath will appoint me again under the same condition and check the same condition. If I find something small, then if I code all the numbers behind that, then how many accounts will there be behind. Jaap Lakshman till agent intake's plus one because if this injection was in zero then control sequence plus one would be this account, then by doing this you can remove this question ma'am account that how many element sir letter on request target element account it is equal to two What request is Z plus one? So if you fold it, then first of all our work is done. Here, first of all, our work is to take out the definition of the matrix from the lattice, which will be the metric dot length. Now the most It was small, what did I say, the kinetic roots have been cooked on the strong side and where will be the biggest answer, the maximum amount will be on the last corner, I have taken that out and kept it, there is no problem, now I have inserted the binary search wheel, first zinc object, intermediate question divide, then Where is the exit point placed? There is a mark on the last column for inter-caste inter-caste inter-caste 208 is the loop plus 1 0 the matrix set I is increased from the table. If it is larger than the target then what to do. You have to simply keep decreasing and in the account In the last control sequence to Z plus one, this is our work and what we will check after coming here is that if the account is small, keep it, my answer will like ahead of the chat, otherwise we will decrease you. The last return will help that Once I came to the stage and saw, A got the target, there is no target, what is the place in the side, I have MP, the target is ok, I am submitted, so I hope you would like an explanation, so guys, with this I would like to say that please channel Subscribe and comment in the comment section so that you keep getting motivation and you keep getting amazing content like this regularly. Thank you, we will see you in the next video.
|
Kth Smallest Element in a Sorted Matrix
|
kth-smallest-element-in-a-sorted-matrix
|
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_.
Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element.
You must find a solution with a memory complexity better than `O(n2)`.
**Example 1:**
**Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8
**Output:** 13
**Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13
**Example 2:**
**Input:** matrix = \[\[-5\]\], k = 1
**Output:** -5
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**.
* `1 <= k <= n2`
**Follow up:**
* Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)?
* Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.
| null |
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Medium
|
373,668,719,802
|
1,510 |
The range has come back and we are being disturbed. One of the problems in the list is number 15. This is the problem of stone game. What is there in this? The total has given us an end stone and two free Delhi wholesale prices. What is to be done by these two, that we take something out of that injury. There has to be a loss in this tape and what will happen in the end that it will come out only after connecting it will go fine as if assume and this conditioner that whenever you will take out the stone from it, these people are fine, so you can always complain about pulling the arm chair, fine as if Let's say that we have some oil, we ask for it and requested it, okay and given a question, we will always start a beat first, okay, so quickly we have found a solution, we have a dream, awareness is important in this festival, Pimple Kumar is there, so if that is for what. He takes it out tightly, so what time do you have it, instead of these, 9981 quarters, okay, the office will take it out, okay, there someone took Mukesh more because on this, take out this, click on this, I will give you the admin question cleared, you accept this compound like You had a team, Government should take it, okay and what you have to do is to try to collect it, then you Bhopal based team can recharge up, work hard to cast certificate means question was given that it always removes only on this, okay NDA Bollywood It can do four countries, it can do notes, now you tell me, if you remove this for the human world, then this above of the new machine, if Vivo does this for others, then that will be saved. Now how will you know which man will I remove Fox? Looted help, design left on one, now what do you mean if you removed then what will happen I wish whatever is peer VP you nine means I am getting some previous states towed that as under before this tell the result in this program If you were there then I was easily fine judge they have York based you know like let's say if I have the name who will win if you know it then this inch is limited to print from here fine like hair down ghee pm nov was your GPS Take the right plant so that it will stick to it and understand that if it is an oil hot one remove perimeter then I will lose for sure how when the name is you life you are the one in front of the remove in one whether not at all and what is it any mind is engaged ok If you have typing, you came to know from this. If you want to use it well, then instead of increasing market BP, Jaswant and DGP of Quid will do GPS off. Tell us which player will win in Quantum. Siddiya Bhai, what is it that whoever has to do, tell us who will win DPIP. Current player has lost, will win if it is difficult means current will become difficult will be cleared, okay, so if I say that Filmy Beat - 1929, then if you subscribe, then now look at the top of this that Jhalar Fall Hai, what is the system. If he goes to Bhopal, what will he do with it, the result will be released on Pimple Day, what is left from DP update all, you will go out after doing yours, if it is difficult to subscribe, you have appointed JBT, you subscribe our channel, okay, it means school will be there, nine accused this year. If you subscribe then do this and subscribe the channel that tomorrow Vivo will watch Karbi special so was the previous one pass or not right idea you must have decided this let's come a little bit what has malaria made of this wearing vigilance so I have There is a function which will get it meaning how many total stones we have and it will give me stress or edit to a person named courier which is camp electronic paltu sahib ok abhinmantrat or erupted which means it was zero ok astrology toe were and What is it that everyone is not able to muster the courage so that Nakul should understand that the one who is doing UP will go, then on whose side will he start, it is time for the edit, so if you are not able to do it, then it is okay and put in it that means make it difficult, current. Clearly's Simran is 2221 so make it a limit and give it 1000 for Laxman. Electronic Quinn said that once you have got it then ask for it. What will we do first on gas i.e. i.e. i.e. subscribe first of all and this is for jail. This stick is needed. Because youth and subscribe and share, subscribe the channel and can add it in the last, do subscribe.
|
Stone Game IV
|
find-lucky-integer-in-an-array
|
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer `n`, return `true` if and only if Alice wins the game otherwise return `false`, assuming both players play optimally.
**Example 1:**
**Input:** n = 1
**Output:** true
**Explanation:** Alice can remove 1 stone winning the game because Bob doesn't have any moves.
**Example 2:**
**Input:** n = 2
**Output:** false
**Explanation:** Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).
**Example 3:**
**Input:** n = 4
**Output:** true
**Explanation:** n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).
**Constraints:**
* `1 <= n <= 105`
|
Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them.
|
Array,Hash Table,Counting
|
Easy
| null |
368 |
today we'll be going over largest divisible subset so this question is basically asking you to find the largest group of numbers in the provided input such that every number can meet this condition so the larger number mod the smallest number is equal to 0 so that means when you divide by this smaller number the remainder is 0 and it looks like if there are multiple solutions any subset is fine at an example to help us build some intuition around how to solve this question so say we have 4 8 and 16 20 and 240 so let's look at these two numbers first so 8 can divide 4 evenly right and that means that the subgroup that I have has 2 elements 4 and 8/10 cannot divide 8 so 2 elements 4 and 8/10 cannot divide 8 so 2 elements 4 and 8/10 cannot divide 8 so 10 cannot be a part of this subgroup 16 however a can divide 8 which means that 16 must also be able to vote divided by 4 evenly so it must be a part of this subgroup and that gives us a subgroup of size 3 so this should lead to a dynamic programming solution because we know can kind of break a problem down into smaller pieces and reuse previous computations we're going to initialize our DP array to all ones and essentially what this is saying is at this index what is the largest subset that I've seen so far and they're all gonna have size 1 initially so now let's process the rest of the array with two for loops and the way this is going to work is we're going to fix our RI and iterate through the rest of the elements using J and what this means is basically does the element at J divide the element at I even Li if so we will add one to the size of the subset that we see at element I let's take a look at 4 & 8 so element I let's take a look at 4 & 8 so element I let's take a look at 4 & 8 so 8 divides 4 evenly which is why now the size of this subset is 2 10 does not divide 4 16 does divide 4 so that's why this is also data to 220 divides for 240 also divides for so each of these subsets are gonna have size to now because it could be 16 for 24 or 240 for the next iteration and I is now element 8 so just 10 divide 8 no it doesn't which is why the maximum subset size is still 1 here 16 does divide 8 and now it has a size of 3 so 16 8 and 4 so notice the way we updated this is we just add 1 to the maximum subset size at this position or what we saw at element 8 does 20 divide 8 nope so we just preserve the previous DP value and does 240 divide 8 yes it does and we add 1 to what we saw eight and that gives us three so these subsets with size 3 right now are 16 8 4 and 248 and 4 move on to our next iteration I is at value 10 and the 16 divide 10 no it doesn't which is why this value is unchanged there was 20 divide 10 it does so we will add 1 - d/p of I which is 1 so we will add 1 - d/p of I which is 1 so we will add 1 - d/p of I which is 1 and that gives us a value of 2 now 240 divided by 10 that also gives us a remainder of 0 so we'll add 1 - d/p of I remainder of 0 so we'll add 1 - d/p of I remainder of 0 so we'll add 1 - d/p of I here however notice that 3 is more than 1 plus this value here so this implies that our DP equation is actually going to be what it was currently or 1 plus DP of I whichever one is higher that's the value that we'll take that's why we keep this at 3 as opposed to updating it to 2 so for the next iteration let's say I is at 16 now 20 doesn't divide 16 but 240 does so 240 plus DP of this value which is 3 gives us 4 and we see that the maximum eyes is four and we can trace this back by looking at okay it was four at 240 now if we move to the left who want to find a subset of size three because we're not including this 240 so that would be 16 and then 2 would be 8 and then 1 is 4 and that's how we compose our final subset so now let's look at the code first we'll handle an edge case if no numbers are provided we'll just return an empty list then we need to sort the numbers and the reason for doing so is that we need to make this I and J double four loop traversal work and if it's not sorted well this line is not going to ever be true right so we will always want to be checking the larger number divided by a smaller number has a remainder of zero and this line is the key equation for the update of the DP array we are the want to take the maximum level we have so far or you want to add one to DP of I what we want to do is after we have the maximum size of that array we want to be able to reconstruct the array to figure out what elements were inside of it so we find what the best value was we find out which index had occurred at and then we find the corresponding value in the original number array we know that has to be part of our output so we'll just put it in here and say the best size we had was four well now the best size that we're gonna be looking for is three right so we subtract off one and then we iterate backwards from the array which means that we're processing elements in descending order so if the DP value is equal to our current best and the best value mod the number that we're looking at is equal to zero which means that it's part of the largest subset then we append the number that we're currently processing and because ok now we have another element in the maximum subset we are looking for one less than the best size that we found and we do this all the way back and we would return output
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
130 |
welcome to june's leeco challenge today's problem is surrounded regions given a 2d board containing x's and o's capture all regions surrounded by x a region is captured by flipping all o's into x's in that surrounding region if we're given a board like this we can see that these zeros this island here is all surrounded by x's so we want to flip all those into x's as well the only remaining o will be at the border reading the explanation it says surrounded regions shouldn't be on the border which means that any o on the border of the board are not flipped to x okay so that's big when you start looking at this problem initially you might think oh we could have some variation of the counting islands problem and just make some recursive calls to flip all zeroes into x's but how do we know that it's surrounded right rather than focusing on what's surrounded try thinking about okay how can we figure out what islands here are not surrounded in order for that to be the case one of the o's have to be on the border right so forget all these zeros in the middle um rather why don't we check all the cells on the border right so the first row the last row the first column and the last column and if any of those are o's we could recursively call to check to see if anything horizontal or adjacent to it is also a no and mark those to say hey this one's connected to o on the border so don't flip this otherwise flip everything else because if it's not connected to a border considering that it's an island then it wouldn't um be unsurrounded it would be surrounded so that's kind of the approach that you need to think about this is very similar to the counting islands problem but rather than caring about just uh going through every single cell all we need to do is worry about the first row the last row first column last column and if any of those are o's then check recursively to see if any of the connecting if it's connect connected to any os and mark that somehow so that's what i'm going to do i'm going to mark those by making it something other than an x or o i'll make it like a c and after i check to see which ones are connected to the border then i'll flip through the hole i'll iterate through the whole board and flip the ones that are connected to a border back to zero otherwise if it's a zero we'll make that an x so we'll flip those back to an x so let's first initialize some variables here let's call height and that would be the length of the board what about width is going to be the length of board zero and what if in case they don't give us a board it's an empty list we can just return um return nothing okay so now let's make our health method and we call it mark and all we're going to input into here is the row and column so what do we want to check well first we've got to make sure that's not exceeding the borders right so for make sure that if r is greater or equal to zero and less than the height and the column is greater or equal to zero and less than the width and make sure uh we're going to check to see if this guy is a zero right or uh oh and if that's the case then we want to recursively call okay uh well first we gotta mark it let's first mark this cell um and we'll just call it c we'll say okay mark it as c and now we'll make a recursive call first up and then down then left and right okay so this is going to be our recursive helper method and what it will do is flip all zeros connecting o's into c's and that's going to be our marker okay it's cool now what now we have to do we're not going to do this for an entire board we only want to do it for the first row the last row first column and the last column right so first row last row and how can we do that well let's just say for r in let's make it a list and say zero to heights minus one and we'll just make that list so that we can do it for the first row and last row and we'll do what here we'll say for c in with call our recursive method okay in the same way we want to do it for the first column and the last column so 4c and i'm going to do the exact same thing with -1 or r in height and i should say range oops we'll do the same thing call rnc now finally now our board should be marked with x's zero o's and c's right so this is our final go through and what we'll do here is if it's a c we'll flip it back to an o and if it's an o we'll flip it to an x so range of height for a column in range of width we'll say hey if board if the cell is equal to c let's flip it back to o otherwise if it's an x or i'm sorry if it's an o then we want to flip it to an x and we don't need to return anything as they mentioned above because we're changing the board itself so let's first see if i made any typos and it looks good so let's submit that there we go accepted so this is how i solved it there are possibly better solutions but it's really just a variation of the counting island problems the only thing that might trick you is to think oh okay let's find the surrounded regions but if you focus on rather the unsurrounded regions then this problem becomes a lot easier so thank you
|
Surrounded Regions
|
surrounded-regions
|
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Explanation:** Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
**Example 2:**
**Input:** board = \[\[ "X "\]\]
**Output:** \[\[ "X "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is `'X'` or `'O'`.
| null |
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
|
Medium
|
200,286
|
430 |
That Ajay Ko Hello Everyone Welcome Back to the video The question that we are going to solve today is an English question, a question on Delhi, a question on flight number, develop play list, a question, which is an intuition, before understanding it. After looking at the beautiful, the question says, then we will go to the intuition approach. Okay, so Asaf Bane, taking the family, I have seen the data of the holiday list, I have made it, I make the connection on the leaf, touch, Dublin treatment, you will be connected to it here and Here one came that 1 to 2 connected means written add volume that if I go between two notes means translation for black on this what happens if I am standing on the same note then I will be able to track that note from this point of my button I will not be able to track the note next to it, meaning the 100w request standing at that turn is just a modified version of the same, that if I am standing on one note with one request, then I can erase the note after that. Ansh I can also try the coming note tight so what is it like what does it mean in English that neck point is now set on the previous point and here in the question there will be another point here which is damage hair style point. Now for example in this is a point of food pinpoint disorganized note chapter note means a son whose Sam his I am talking about okay so this is if it has to be flirting hot then the output should come if I went to one packets now If I will bring Mittu after flirting then want to give a fiction gone vinegar also give a cup of style on its side and hence if this is the stop then come for its printing home after that if there is no suicide note on the fluid that has gone on 727 then on the seven side How to return first passenger fare and found soldiers who DOESNT we have to slide and give the list if you look at this one here then this one has 123 6006 1238 04562 isko can do me phenomenal side one Hindi dub what can we do Like we used to do levels and traversal in the tree, we will do fixed deposit reversal on this link and on Horrible, we will break it down with so many notes, through a mapping and pin in it, what will we do, we will check with which note. Which level was mapped but here is my second level map with this note, I am the third level map with this note, so accordingly we both completed the updater and took the final list, then that can be ready. Have an idea but what will be there in it, we will use two extras here and you will use the end process holidays also in the factory, if you forgive me, then we will have to keep that level computer with a note, right, this is not a simple, similarly, we have to do all that only for so many. If all the notes are forgiven then we will have to check that also, then you can just try that approach, if you search for Badkot points also, then you can make this question smaller in another way, that if we have a link list, what can we do in it? If you are one note behind, we will put it in our final right, then we will call for its next, now display, when will we call, if I have anything like style note, no rate, if I have something like silent, then now. We will call for this, if there is something on my silent, then I will first call for this island, then the function that returns from the child note, then I will call for this, if I do this president, then I am on the first festival note now. I have a tap on this side, so I called the function for a second, I inserted it, now I see that my child is using it, thanks to this, so on the function, I am going to English at this point, then okay, my take this. Now I went to the site, minuted the pipe, he doesn't have a child, I insulted whom sex Pragya and saw these settings and finally store these, set OK and after deposit, see, let's do his childhood, I had told that on the function. Send it to the ad, now it has been sent to cricket. If the stomach is hot, then the admin has made me go out to hurt you. Now his side reaction does not happen. We do not make a special effort to put it on the line, so I have done the night shift. After returning, now after returning. How should we present from Noida, its call has been completed, so I say left, it means that it has called for the next, I am on seven, I will send a message to the house, I have muted the seven in the final English for myself, Abacus, what is this? It has side effects, otherwise you will return these tankers for Rs. 5, the whole game is over for Lattu. Opened it back for 898 end service committee, so see this, I insult you first, after doing frequent search. I'll see if my side adjusts to it now, if not then it's fine, call for it, I went as a so, then when I came home, I accepted the four, now I saw that the four is a child abuser, no, now. I called him for this, now if there is any question then he will come back only after returning, then finally in the morning it is 12583. Then if you want the intake which I said, apply for it and try posing another 12 examples, then the approach road is also clear. Similarly, if you look at the discussion, I said that solve it for a note, then call it for its child, and if there is no child, then directly call it for its lips, so we do something similar. In our solution, let's code it once again, make notes, I will explain it to you again, I am remembering it step wise, but the puja will be done, I will show it to you once again on any exam of D.L.M. Okay, thank you, so will show it to you once again on any exam of D.L.M. Okay, thank you, so will show it to you once again on any exam of D.L.M. Okay, thank you, so let's. Start the code first so if we are all more here we have to do this note button toll free customer route then dip for this the answer route and Vikas Hansa answer head so the note of lips this notes is the answer head o then hit the initial channel. The oil we use is this, ah, first we will set one in, then we will do minutes near them, then keep attracting that we will put five after two, it is not that we will put you after man, then once on us, link Discover India. If we have to keep Delhi Metro tracks, then we will also make oil, but after which track, we will put my element which is coming there, it is supposed to be one, I have put it in one, but the thing made on it has come, I have put my two beads there. Now I have got only OK now I need to know that I side clove after two is not like that I will put the pipe in the next of one so keep attract camera which is the last element then I will put the more current element on its next for I make oil in battery water and many people can fold it in many ways without using detail and refueling tail. If he believes detail then admin finds it a little easier for me and if you want then you can solve the questions with your approach. Today we can do this in the evening of the most an answer Tell Atal Pension Recording to 9 a friend then Amit will call the call function and in solve we will also pass the answer and will also tell the 251 team that and rather normal Will also give password to the rate and when the answer is given, I will return the final answer. Points after calling. And now what will this function do? Like I told you, one in soft, friends, I want to record fabric, so first sell it to us. If we have to give, then first of all we make a function, after that we will go to the base, then how to leave for all type A sense is passing by residents to Ayush dresses boy type function because Mary does not have to return anything, then it should be used in the function in a free manner. The answer is, if you want to keep updating the liquid made from alarm set A, then every possible reference is given as Rahasya Loot and 650. If you want notes of his, then for this reason you can name it like this. Edit, not necessarily, then simply want. To this request Shivling, it is very important to do a best. Whose base is it? Anytime, if we are going on a tena note, tight, if we are going up on any turn, then we have reached that note like this batter check, it is vernal then. Do four digits on that or its next will execute in the stomach this is our problem has happened so if I this note now I'm standing effective hate or amazon drain so everything the returned from the function recording eminem that function for president home When I go, if you don't plant my tree, Hussain, will I return the tax ? If it is not there, like I told you, ? If it is not there, like I told you, ? If it is not there, like I told you, I first checked that it is in the tap, it is not complete, it is not in the tap, so if it is online, then put it in the text of the current list, people are fine. So and one naive function which is in struggle east, so I am putting one thing in Anil, if I go to find one, then I am putting one time and one thing on oil, the function of doing in retail pack two wheeler is the notes and still of every note. So print it here, I will again send it to the answer head, I will send it to circle 25, I am standing in Redmi Note 4, I will send it to its spread on the net that now I will check whether I am standing in this note, does its child adjust 19, then if that But if the child tweets then I will call the function for him, will the function call assembly polls from the brief plan at the higher level and Ameet Singh copy this in the function and write it Shravan, here we will not give the speed, this if we have got the side, then we So if you press this then because of this link S5 laptop mahal point I will send you to the girl child battery left for the next more office call rate then he adds four digits and call the function for that and if unite or not then his It does not depend on the above, we will simply open it for the next one, fine, tell me solve all these, it gives special results, setting it here, we will fold it, then one, what will we do, then question tooth age 10, we have to make this retail function. ₹ 2 inside were violated, ₹ 2 inside were violated, ₹ 2 inside were violated, that soil, I have come to interest in it, I will not return anything, this plate here is my finality against Airtel, I will update it in this, then enter reasonable password for that, injustice was looted, are still and your data infection is the point. If I have sent a lot in my function for data into me note so let's post note star mode echo that in my note of director of now you know you have aspect on this from some elements to 12 so if they have 5 inches What will you do to set the SIM? Come on, now you will put it in the fraction of the oil point where you are pointing. Right but if you assume that there is a Yagya limit or not, then you will have to make a note and hit its growth rate and hit the oil on the same. If you have to write, it is only mine, there is no element in the disappointed woman's disappointed means, so this note of held roadways point to the mode was similar to the evil point, both Twitter, I have only one note, this is mine, so right now it is 12th that if I say, I have come till line 2824, Dormant Salah is not a channel, but this is a note, so I have to invest in the oil of this note, the budget is ours, if I have come 20%, I have reached the ours, if I have come 20%, I have reached the ours, if I have come 20%, I have reached the example that now my lips are Mukesh two, they were pausing on 162. Pausing the previous one, I have just got an element. To do this for 5 minutes, I have made a note for the size and what I have to do is the tail point is here, the depository is here, so point this towards the tail point. He is doing his next, now he will appoint this note, till the note, the previous one will appoint this note and it will also be done, then money will be given in this function tomorrow and outside and once any leader comes to insult, then he will set 25 interviews or not. Affairs Planet Mukesh Bhatt Clear Speech So that I have the actress on this Ek Hai Do Hai Se Mix I keep watching then 427 is the previous point of Connected Two, that is my friend from 101 Connected Two, now Taylor is here too, like I said, that's the last Note appoints force note, now I have to tighten it for 5 minutes, if 52 current appoints, then two will be junior, he will appoint you, five previous tour will appoint, now suppose again some other update comes to me, cases its dead sales man. Where will the platform be inside these five? Next, whenever we are doing a data insult, there is some unique sense printing and tell Sudhish needs to exit poll for maths important function call 100, now where is the oil, this Function and after that oil will go to oil's next and they need to update go right so think we will not see the practice investments will have certain elements in the earliest to oil's next wave nothing son spears will point dilip on show me so If update detail soft absolutely ninth some test next point 210 oil for code so let's click on check button and see that the code is building that okay sub skin here the answer is D pass ke then check that this is the answer this simply Let's slide the point was Surya Koti time, I am adding all the tests in it, so let's see whether this previous running 501 is completed by default. Let me explain to you once more here, what is this from this function call. It is happening and how is complete exit is happening and debit the for example to make you understand I and once again the birth code of toilet how are we becoming so reach out to me English to 1234567 98 99 that this is connected to this If it is connected then from free to that from the end it is 416 but phase 680 is half side on it, service is suffering so look in this, answer comes here, how I want to see this wave answer, Ashram only 125 Chhath 9721, now I call this function now. What is happening here, let me explain it once. Sam straightened the vestige friction and first sent it to the bread, then there is no tap, development is Dr to 9, medicine at nine, so we insulted him on our final list, so he took my final in it. What is one, I bring it in the ride, that is four digits on it and said otherwise it is not credited, now I have called it for this, now I have brought it on it and we have called, so is it ₹ 50 or right to The ₹ 50 or right to The ₹ 50 or right to The cartoon lahar-1 * Only tuk interested made it cartoon lahar-1 * Only tuk interested made it cartoon lahar-1 * Only tuk interested made it two minutes till now four digits are done there to my channel taxes so I used this function to send chat on chat in tak so now my friend plants this function posted 5 days here But it is said that the benefits are final, if the benefits are not ready, then there is no fiber kernel, then set the typing, here I have written how, set these, then I have set the face, if you want, I do this, otherwise open this for this, then next. If we are on six then this fictitious one has made it a few minutes tunnel needle interested 6 minutes, its chart uses it to adjust us a bit, so send this function till Mukesh, wicket admit card, I am on signal right now, so it is edged with Edison Motivational. Videos Peeth, we did it for a minute, then we got interested at, the child of eight adjusts, I said no, then call for this, we will see, we are on the line, this is 948 tap Praveen is Abhimat Abhi where we are, what made Take it or not, once you lead this note lying there, if you are not afraid of it, then include a reminder add, if you use lemon juice, then open it for mixing, then now I call for it, otherwise I Returning here we come here, its function's anger is over, its function is over, and its function is also over, the one next to it on the seat is under the control of its function, now its function is over, now we have called for minutes. If we went to this, then from 872, the coin is not national yet, so we should take it, he printed it, folded it in Sunday, adjusted its side and said that it does not come down, so I called for the next one, so I went to this. Like Share So I returned to Seventh Stories of Fear of Death and came back to five, then this Redmi of mine went from function to reduce the previous song of the set, so here I told you that it will be written nicely, so all the people at eight are deposited there. It must have been torn, so now I have come to two that the lining of the said side function is finished, I opened it for this, Gayatri appoints the criminal, weight history or and this note, I am interested in it, okay, insult him two. And sorry, I click on the rate so that there is confusion later, right now I am Preeti, okay let's do four digits, I said no, its sides do not adjust, so I directly open it for the next one, then the net profit is free. So now I am appointing this point as my exit pole on this track, so I said that this is for external point, till that point there is rain note, it is in the back row, first of all, I will leave you the photo in. I squeezed it and inputted the right for, you said and it has four digits. For tiles, only Capsicum and Kalidas do not say that it has a tap on the side, so if it has a channel, then I simply say, what do I do with its next key? I called for a gift on next, I remove it in solid confusion, I write it with a point that I opened it to fold and after doing this, if you have not read anything of knowledge, then after returning this simple to you, the rate has come to the floor. So my phone did not eat anything from the connection, it was done properly, then the force option call ended, it was completed, so I returned and here is the further method, yes, it is done, yes, if you ever get it completed, then go there, one mine, so that the note So its function is completely finished till co tight means my whole recursive function is not finished so when I return solve functions I have my answer is demi answer ten list updated test match played but we were decided out in this case 12568 70348 hot read it from here 12512 2a torch light 6680 ki 734 sorry tha whole testis ka diner you can enter you are not understanding the service now I will ask you to record the video once and watch it friend you will get 12 more test cases than this If you do some driving then understanding this code will become easier, then in this 10 all for the tent planning video, let's do another new video bye . .
|
Flatten a Multilevel Doubly Linked List
|
flatten-a-multilevel-doubly-linked-list
|
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below.
Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list.
Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`.
**Example 1:**
**Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
**Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 2:**
**Input:** head = \[1,2,null,3\]
**Output:** \[1,3,2\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Explanation:** There could be empty list in the input.
**Constraints:**
* The number of Nodes will not exceed `1000`.
* `1 <= Node.val <= 105`
**How the multilevel linked list is represented in test cases:**
We use the multilevel linked list from **Example 1** above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
The serialization of each level is as follows:
\[1,2,3,4,5,6,null\]
\[7,8,9,10,null\]
\[11,12,null\]
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
\[1, 2, 3, 4, 5, 6, null\]
|
\[null, null, 7, 8, 9, 10, null\]
|
\[ null, 11, 12, null\]
Merging the serialization of each level and removing trailing nulls we obtain:
\[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
| null | null |
Medium
| null |
1,619 |
hey guys what's up this is steve today let's go through another legal problem 1619 mean of array after removing some elements let's take a look at the problem first given an integer array return the mean of the remaining integers after removing the smallest five percent and the largest five percent of the elements answered within 10 to the magnitude of negative five of the actual answer will be considered accepted let's take a look given this array one of so many twos and one three after you're raising the minimum and maximum values of this array all elements are equal to two so the mean is true you can just return to remember is this is a double integer type this given array is already sorted so it's very easy to spot the first five percent and the last five percent is one and three so they are stripped off so the mean of the remaining is just this which is true so this one is more regular which is which means this is this one is unsolid how can we find the first five percent and the last five percent we need to solve this array first before we can get to know the first five percent and the last five percent after sorting that out we'll just count all of the middle ones add all of them up and divide them by the total number of the elements in between the same goes for these examples right this one is labeled as easy so the thought is very clear and easy we'll just solve this and add up all of the middle ones the middle 90 and then divide by the total number of elements in between then we'll just return right so now with that sorted out which is to start writing code so first we'll want to sort this array given this array we just want to sort this then we'll have a variable called n which is the length of this array and then we can start from not start from zero but starting from the fifth percent so how do we get to the fifth percent that is we can get we need to round this from n times 0.05 this is going to be the starting 0.05 this is going to be the starting 0.05 this is going to be the starting point we need to round this double indigene this round api is going to give us a double and then we need to run this to be an integer because this is an index this is the first one that we need to traverse through then we go all the way up to what then we go all the way up to n minus 0.05 times n this is of course we do not want to go all the way up to the nth because we want to strip off the last the top five percent this is where this is the range that we should be going through of course before we go here we need to have another variable which is called sum which is going to help us add up all of these values and then in the end what we want to do is we just need to return sum divided by n times 0.1 n times 0.1 n times 0.1 where do we get this 0.1 this is one is where do we get this 0.1 this is one is where do we get this 0.1 this is one is because the first half the first five percent and the last five percent add up is ten percent is point one now let me hit run code and see all right accept it now let me hit submit all right also accept it not simply impressive but uh there should be other ways to optimize this let me hit submit again uh um now it's 99 it's i guess the submissions there aren't enough submissions to really distribute this to give me a very consistent view all right time complexity is oh and log n depending on the sorting algorithm by default it's unlocked n very optimized and then we just need another variable to go through all of this so the entire time complexity this one is o n and this one is o and log n so the entire time complexity is o n log n space complexity is just o one we don't need any extra space if there's any extra memory needed by the sorting algorithm that's the extra that's it for this entire video um hopefully it helps you understand this if that is the case just do me a favor and hit the like button that's going to help a lot with the youtube algorithm and also don't forget to subscribe to my channel feel free to check out as i have accumulated other digital tutorials data structure and algorithms and also amazon web services if you want to prepare for any aws certification exams feel free to check them out hopefully i'll just see you guys in just a few short seconds in my other videos thank you very much for watching
|
Mean of Array After Removing Some Elements
|
path-crossing
|
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105`
|
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
|
Hash Table,String
|
Easy
| null |
79 |
hey guys welcome back to another video and today we're going to be solving the lead code question word search all right so we're going to be given a 2d board and we need to find whether a word exists so the word can be constructed from letters of sequentially adjacent cells and adjacent is only horizontal or vertically neighboring cells and the same letter cell cannot be used all right so let's just look at an example real quick before explaining what's actually happening let me just explain a few variables i declared so i have the variable x which iterates through it horizontally so we have this has an index of zero then one then two and then three and then i have a variable called y which uh which iterates through our board vertically so we have this has an index of zero over here one and this one has an index of two so what i'm going to do is i'm going to put this entire board and i'm going to look for the word c so our first step is going to be to look for an s so there's no s anywhere over here but we find an s over here and as you can see we are at that as over here so an uh index of x equals zero and y equals one so over here we have an s so now the next step is to look for the next letter so now we have to look if any of the adjacent letters are in e so we're going to look here it's not an e this is not an e either neither is this and we're going to look at and it doesn't even exist so this s does not matter so now we're going to look for a second s so when we do that so let's go to next step and we find this over here at x equals 3 and y equals 1. and that's referring to this s so now that we're over here we need to look for the next letter so let's look to the left it's not an e let's look to the right it's not an e but now we're going to look up top so as you can see we went up top and three comma zero right so it's referring to this over here and now we need to look so now that we found the second letter we need to look for the third letter so the only uh adjacent characters to e so we have nothing here and we cannot go back to s so the only thing we have is c but that doesn't matter we're looking for an s so this e over here is useless so now what we're going to do is we're going to look at the next e which is this so if we go to the next step over here we're going to go to 3 comma 2 which is referring to this so now that we found the second letter we need to look for the third letter which is also an e and luckily it's over here so if i go to the next step i'm going to get the index of 2 comma 2. and once we reach that we've covered all of the letters inside of our word and that's when we're going to stop our function so if i go to the next step we are done with it and it returns us a value of true over here so now let's just actually now let's actually write the code for this and i think it should be a lot easier to understand that way so our first step is to iterate through our board and look for the first letter so we're going to do for y in range so the length of board so this is the vertical one and now for horizontally so for x in range length of board and then we're just going to look at whatever is at the zeroth index doesn't really matter okay so if board xy actually no sorry it's going to be if board yx is equal to the first word so the first letter in the word so word zero and so now we're going to call our function on that so i'm just going to call the function search i'll explain what all we what this function is for later so we're going to give it the board we're going to give it the current y value the current x value uh we're also going to give it the index of the word we are at so we're at index 0 and we're looking so the word we're looking for and if that is true then we're going to return true and if it's false for all of this we're just going to return false all right so now let's construct our search function so def search so it's going to take self then what else it's going to take the board the y value x value index and then the word all right so how do we know when to stop searching so in that case so basically if our index is equal to the length of the word then in that case that means that we've uh iter we've found all the letters inside the word so in that case we're just going to return true uh now we need to see when is it when are we going to return false so anytime we have y or x values which just do not exist in those cases we're going to always return false so if y is less than 0 or the y is greater than or equal to the length of the board um then for the x we're going to see when x is less than zero and also when x is greater than or equal to the length of board and then we're just going to put y and so that's one condition so these four look if they if the x and y values even exist and now we just see if that whatever letter is there inside the specific spot in the board if that's the same as the letter we're looking for in the word so if board y x is equal to is not equal to the word and the index that we're looking for so index let me zoom out a bit all right there we go so in any of these cases we're going to return false all right so now we're going to have a temporary variable because we need to account for this rule over here which says the same letter cannot be used more than once so we're going to store the value of whatever that letter is in the board so temporary variable is going to equal to board and then yx now we're going to change the value of yx to just anything so we're just going to make it an empty string just to denote that uh we've already went over it okay so now we're gonna have something called found and found is gonna be a boolean value of true or false of whether the next letter actually exists or not so now we're going to so we're going to call this function again so self.search call this function again so self.search call this function again so self.search and we're going to call it on whatever is above it below it to its right and to its left so we're going to call it for our all of that so uh everything so board is going to stay the same so we're going to do y plus 1 which means that we're going to be looking for 1 below then x is going to be the same in this case our index is going to increase by 1 and we're going to be looking for the same word so we're just going to repeat this but each time we're going to be looking at different directions okay so now uh okay so we have y plus one so we're just going to change this to y minus one and now again a board so this is gonna now the y is gonna stay the same and we're gonna just change the x so we're just gonna do x plus one uh copy that for the last time and now we're gonna do x minus one all right so this accounts for all of the directions up down right and left and even if all we need is for one of them to be true for the value of found to be true okay and now finally we need to replace the board because we gave it an empty value we're going to replace that with its original value so board y x is just going to equal to the temporary variable which we defined and now uh in the ending we're just going to return the value of found okay so now let's submit our code and as you can see our submission did get accepted and well finally do let me know if you have any questions or if you have any better solution to solve this and finally don't forget to like and subscribe if this video helped you thanks a lot
|
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
|
988 |
hey everybody this is Larry it is January 23rd uh of 2023 hit the like button to subscribe button drop me a Discord let me know what you think about today's part so this is not the bonus question yet or this is not the uh the daily question uh because I'm just it's a little bit before the time release I think there's like half an hour before that so I'm going to do uh do a bonus question first and yeah that's uh let's get one in today's bonus question or Larry's extra question is 988 smallest string starting from leap again not a premium questions so definitely feel free to deal with me okay so now you're giving a good of a binary tree each node has 0 to 25 representing the letter A to Z which I guess they could just use a to z but what's gonna return the lexicographically small string that starts at the leave and enter the rule as a reminder any shortest prefix of a string is lexicographically smaller any shorter prefix of a string a b okay yeah of course okay uh okay so there's this is a complete tree I guess it doesn't have to be right um let's think about how to best do it I mean well that's really specific I mean you can definitely do a linear thing uh like if you my first thought process is trying to see if I could do a different search and of course maybe you can but then you have to do comparisons and I don't know that you know uh like it can probably degenerate into something like N squared but I could be wrong just by like the number of comparisons for the lexicographically smallest but maybe it doesn't come into play so we'll keep that in the back pocket and not do it yet um so the weird thing about this particular one is not the real thing but um and I think we can also maybe do a bucket sword type thing um in that we basically uh keep track of the parent which is the next node in the string right uh or next character in the string and therefore also the next note in that tree and then um and then kind of uh not quite a bucket sort but like just walk the smallest thing right and at worst that's going to be 26 times n if you have one necklace or something like that in the OR Zeds or something um and I think that should be good yeah okay let's do it that way it's a little bit weird a little bit annoying but maybe it is fine it's um I'm trying to think Reddit is even a Slicker right um because basically what I'm kind of doing now that I think about it is kind of like doing it like a try almost right um and if we're doing it like a try can we do it in a smarter way right other than you know um everyone because basically what I was thinking of is just like almost like every start at the leaf node and then kind of go up and then up and up but that can actually degenerate as well so maybe that's not actually good enough can we do something with respect to um it's also possible that I'm overthinking it to be honest but I think if we have a way to just ask aquarium like okay it's the leaf with a and then it's their second thing with b and so forth I think that should be okay but as long as we're able to do it all at the same time wow this is am I over a complicated thing thinking about it because I think that a lot of my cases and just maybe I don't know I hope that this isn't one of those problems where the input is just not strict enough right because then that just means that I'm raising my time but there definitely can be a way to kind of degenerate both of those things in a square or n Square problem is that if all of them are the same then you kind of keep on just going up like basically if you have the entire tree is the same letter for example then you just keep on going up and then if you have a complete tree of say n over two notes at the bottom then that's gonna be n over 2 times maybe that is not well in that case if we log in but then the depth of the tree we log in so then it'll be n again um press n log n let's see so the N of them and then and again Taps maybe but then what if you have one of them that's hmm it is definitely very awkward try to think where it is a way to do it backwards from the root I don't know that there is down that's the thing and of course the random case is going to be fast but it's about the worst case thank you and we want to be able to process stuff about processing all of them I mean maybe we can merge them if they're the same node but I feel like that's hard to bookkeep too right not um this is only a medium but am I missing something obvious I mean we do want it to be greedy in some way but it's not sure how um Maybe all right let's try it and then maybe this is just one of those YOLO problems where maybe I did math silly uh all right let's go um yeah let's go Traverse all right uh yeah it's a left right tree okay like that and then just foreign like okay if no dot left is none oh I have to do this none and note that right is none and this is a leaf and then we just set it into the uh I don't know let's call it start someone like this maybe foreign okay that's good maybe I mean it's expected and then now we want oh excuse me yikes I did Heavy squats today so I'm just like really tired it really burns down my system maybe it's time to take a break from that but uh yeah uh okay so then now we just basically for um how do we want to do it we actually want this to be maybe someone like this and then someone like this okay so then now we can reconstruct um answers for um maybe something like wow true or maybe change the condition later for and maybe this is uh yeah start as a table name maybe a current I don't know if current is better a bit um and then maybe like next level is equal to collection foreign list okay and then for I in range of 26 right something like that if I and current then we break enter that append um I Plus this to get back to fame and then we break and then what are we doing right we basically go it's not gonna do something like this then now for current Supply right for node and current sub I no uh we want to get to parent get the value and the next level we want to append apparent dot node right or parent sub node basically the same thing that we had there right and then afterwards current is to go to the next level and then we do it again okay uh and then maybe this is families are good before us and then finally if you go to true if so if not found then what do we do if it's not found also we do actually want this to happen to point a none so then we can maybe do a thing on it the current node is none then we'll return um put this in first time because that means that we hit the root after using this character okay if it's not found then then no I mean I think this is fine because this should go until it hits a route eventually so it should be good you know this looks really awkward maybe I'm wrong this is infinite looping all right I don't know if this time's out or not so we'll see but apparently it's fast enough maybe I did the analysis as well because I was thinking about this pretty early on but let's see I mean I guess the worst case is that there are n over two leaves but then the debt is over log of uh log n is there uh if the depth is n over two then I guess you only have two leaves is that right now I guess it doesn't have to be here but it maybe there's some like analog n bound type thing I don't know I'm not really good at proving this one so but I think maybe that's right and that the worst case is that you have n over two leaves um and they're all the same character but then in that case the depth will be log n and then it's n log n and I did the naive thing and thinking about finger down and square it's kind of tricky though I don't know that I explained this one because I wasn't sure about this one basically the idea is just keep track of all the node value or the leaf values um by using the traversal um this is linear time linear space and then almost kind of like a breakfast search or something like that where you greet it go okay is there an A in the current level um and the current level is just the leaf right so it doesn't it's not the same level as the depth but it's just the same level from the leaf that the node is from right and then if there's an a then we do this stuff and then we add the A and then we go to the next level for each of those nodes we go up one to go to the parent if one of them is the root then that means that we're done because well it's we want this the shortest prefix anyway so that means that we're done if not then yeah then we repeat this again um we then we repeat this again with the next level being the you know set to the new level um and then we see if there's an A so basically in a greedy way you go okay then hey there is a okay it's then a no is there a b is there an AC dot and then in that way you do 26 times n at most or 26 times the depth of the tree which I guess could be n could be log n but um yeah apparently it is fast enough though I don't know just is there a better solution on this one this is not a very useful discussion I'm curious before is the before it's fast enough this is not an old n though but uh I mean I guess I could have done it this way I wasn't sure but it's still not all of them because of this comparison uh this comparison is not constant um but I guess I wasn't sure hmm I guess that would have been fast enough just simple pre-order uh okay I mean just simple pre-order uh okay I mean just simple pre-order uh okay I mean maybe I made this problem more communicated I can't even say anywhere maybe I made this part more complicated than it is so let me know what you think stay good stay healthy to good mental health I'll do the dairy problem well when it comes up next uh and I'll see you in a little bit bye
|
Smallest String Starting From Leaf
|
flip-equivalent-binary-trees
|
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
As a reminder, any shorter prefix of a string is **lexicographically smaller**.
* For example, `"ab "` is lexicographically smaller than `"aba "`.
A leaf of a node is a node that has no children.
**Example 1:**
**Input:** root = \[0,1,2,3,4,3,4\]
**Output:** "dba "
**Example 2:**
**Input:** root = \[25,1,3,1,3,0,2\]
**Output:** "adz "
**Example 3:**
**Input:** root = \[2,2,1,null,1,0,null,0\]
**Output:** "abc "
**Constraints:**
* The number of nodes in the tree is in the range `[1, 8500]`.
* `0 <= Node.val <= 25`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
744 |
all right so we're going to do number 744 find smallest letter greater than target so given a character's array letters that are sorted in non-decreasing order that are sorted in non-decreasing order that are sorted in non-decreasing order and a character target return the smallest character in the array that is larger than target note that the letters are up around so for example if target is equal to z and letters a b then the answer is a so you're basically going around a circle let's try to represent this pictorially and then we will try to write the code so go over here this is left this is right and by the way we're going to do binary search because it's going to be the most efficient solution in this case and this is going to be your midpoint right so let's just say that your target's d just like in this example and then our midpoint is obviously going to be f so f right so what does that mean well we gotta move right is equal to mid minus one right so what we're gonna do here we're also gonna copy this that didn't work so whatever i'm just gonna write it again all right so now that we do that we're going to move over our mid and we're going to move over our right so remove that so this is going to be r and this is going to be mid as well right so now our target is still going to be d however we have a new uh num we have a new midpoint so our new midpoint is going to be c here and we notice here that d is greater than c so what do we do when d is greater than c we're going to move left over one place right but we notice here that right is no longer right is left so therefore we must return the left right so that's a premise of how the algorithm goes but let's just handle some of our edge cases if right falls off the map basically if right goes off the map we want to return whatever l is here right so now that we know that and what if right is equal to let's just say that this one was here right is equal to the target what are we going to do there or we're still going to move left over one right so this is actually going to be so basically our conditions are for here target is less than uh letters nums right and then we have the same thing here where target is greater than letters and what happens when we do that well we're going to move left is equal to mid plus one right so now let's translate that into code so left is equal to zero right is equal to length actually what i'm going to do is i'm going to call it r letters minus 1. so while left is greater than or less than or equal to right what we're going to do is we're going to set midpoint to equal our left plus right divided by two if target so we're going to do the first condition here of target is less than letters numbs what we're gonna do is we're gonna set r to equal to mid minus one else left is equal to mid plus one and we also had to consider edge case that we talked about briefly where if right falls off the map here and left falls off the map then we're gonna return the left hand side right so if target is less than letters left or target is greater than equal to right because right is like the letters minus one right and we're going to put letters here return letters left and we're going to copy that and we are going to return that value it should work let's see left is not defined made a little mistake there and this one is not numbs should be mid put a capital there alpha sar and let's run our test cases here see if it works it does work submit and accept it so if you enjoy the video don't forget to hit like comment subscribe and i'll see you next time
|
Find Smallest Letter Greater Than Target
|
network-delay-time
|
You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter.
|
We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm.
|
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path
|
Medium
|
2151,2171
|
1,834 |
hey everybody this is larry this is me calling over q3 of the weekly contest 237 um and it seems like this was the one that i wish i had back because and probably the hardest problem of the contest not just by me but for other people um and it is single directed cpu so it's i think the hardest part at least for me about this problem is just thinking about it in two steps but really if you slow down and look at every step or like follow what they tell you to do uh here you know and implement it using a heap and um yeah a heap and that's pretty much it really um so hit the like button to subscribe and join me on discord and this took me a long time it took me 15 minutes to debug on this problem um but yeah but basically what i do is that okay so for every task i sort it by the starting time how much time it takes and then just index because we have to keep track of it and then we sort sorted and i for me i just put on a cue just to make things easier and then now we start if the current time is equal to zero while um what while there are things on the queue or there are jobs available to be done i do this loop which is you know this is more like rephrasing the problem that they ask you now that we have the data structure in place which is a heap and it is something that you should you know um so my biggest struggle was just using i think i was using the same sort key um on here versus the heap and that's where i got a little stuck and i once i realized that uh that's why i was having issues it became easier but i wish i had it back but basically this is saying okay you know let's say you know we look at the current time and we look at the number of tasks that we can do um that we haven't done yet and for every task that you know now is available we just pop it off to the left and then we push it to the heap of things that are available given the now we want to sort by um the duration of the task which is given in the problem they tell you to do this and the tiebreaker is sort by index and then for i just i actually don't think i need this to be honest to start and i don't so i don't know why i kept it here um well in either case yeah and then once you do that uh so now these are this just this loop just adds hey let's figure out all the tests that are available and then put it into availability and then here is okay if any task is available then we take the first one off the heap which is the smallest one which is the one that has the lowest t lowest duration we now look at the current time and then we add it to t or we add t to the current time and then we execute the index um that's basically the idea now this job is done and then we go for the loop and we do it again if there's no job to be available that means that we want to get the next element on the task list so what i did here is i just set the current as you go to uh to yeah i set the current time is equal to the time of the next uh task otherwise i break but this should never happen um because if this happened because if this end this is for uh force then well this would have this while loop would not have happened so uh but yeah um cool so that is the invariant so what is the complexity here well you know as you see there's a sorting here so it's gonna be at least and login and here this loop will execute you know once or let's say twice per task one to push into the heap and once to wants to uh pop it off the task so it's gonna be uh yeah so this is gonna be oh let's say two times n for each element adverse and for each element it is going to pop left which is just over one and also both push to the heap and then pop to the heap or from the heap so it's gonna be log n time so each item each task will take log n time and there's or o of log n times and there are n items so it's going to be n log n uh so yeah it's a whole album the whole algorithm is going to be time is n log n and of course space is just going to be all of n because of you know the answer we have to store each yeah um and also availability is also oven they're both linear space so yeah that's all i have and you can watch me kind of fumble through this embarrassingly during the contest next okay you stolen this one you bye um hmm you um no this is good oh am i so bad today on this one i'll stop by length that's my that's not good why am i so bad at this so no this is this part is right but we want to push something else that's why you okay that was a mess hey yeah uh hope you enjoyed that explanation or video uh hit the like button to subscribe and join me on discord join me on twitch whatever you like join me on instagram i guess uh yeah uh i'll see you next time but stay good stay healthy and to good mental health bye
|
Single-Threaded CPU
|
minimum-number-of-people-to-teach
|
You are given `n` tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `ith` task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing.
You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way:
* If the CPU is idle and there are no available tasks to process, the CPU remains idle.
* If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
* Once a task is started, the CPU will **process the entire task** without stopping.
* The CPU can finish a task then start a new one instantly.
Return _the order in which the CPU will process the tasks._
**Example 1:**
**Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\]
**Output:** \[0,2,3,1\]
**Explanation:** The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
**Example 2:**
**Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\]
**Output:** \[4,3,2,0,1\]
**Explanation****:** The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
**Constraints:**
* `tasks.length == n`
* `1 <= n <= 105`
* `1 <= enqueueTimei, processingTimei <= 109`
|
You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once
|
Array,Greedy
|
Medium
| null |
1,641 |
welcome to joey's dynamic programming tutorial in this video of joystick you are going to learn one very interesting dynamic programming problem which is count sorted vowel strings this dynamic programming example problem is from the word of strings and i have taken it from the website of lead code count sorted vowel strings can be one of the next dynamic programming interview questions for you and thus understanding it completely is necessary and to understand it completely all you have to do is watch this video till the end i have tried to keep the explanation as simple as possible so i am certain that you are going to enjoy learning it let's check out its problem statement now given an integer n you need to find out the number of strings that can be formed only with the vowels of length n yes the vowels which are a e i o and u the strings should be lexicographically sorted by lexicographically i mean that the strings should have vowels in the same order format as they appear in the dictionary below are a few examples of strings that are lexicographically sorted they are a e and i u to clarify further the strings that are not lexicographically sorted are ia and ea we will find out the number of strings for n equals to 2 that can be formed only with vowels of course which are lexicographically sorted we'll solve it using our favorite dynamic programming approach but before that i want you to subscribe to my channel and press the bell icon that is next to it because that way you will get notified whenever i release new videos on my channel before we begin let us brainstorm a little when n is equal to 1 how many strings can we form using the wobbles that means how many strings of length 1 can we form using the wobbles i say 5 do you agree i am sure you will because there are 5 vowels and each one of them is a string in itself of length 1. now one thing that we can figure out using these strings of length 1 is that the count of strings starting with a of length 2 is equal to the count of strings of length 1 greater than or equal to a which is 5. these strings are a e a i a o a u and double a we can also deduce that the count of strings starting with e of length 2 is equal to the count of strings of length 1 greater than or equal to e which is 4 they are e i e o eu and double e remember they are lexicographically sorted hence there can't be any string like e a on similar lines the count of strings of length 2 starting with i o u will be 3 2 and 1 and the strings are written over here you can check just like there are five strings of length two beginning with a there are five strings of length two ending with u right similarly there are four strings of length two ending with o all of them are infer from strings of length one which are nothing but vowels we will use this logic to find the answer and construct our dynamic programming algorithm this can be one of your next dynamic programming interview questions and i hope that you are watching it closely there are two pillars of this problem one the length of the string which is n and two the five vowels hence we will create a matrix whose rows will be represented by n that is the length which is 2 and columns will represent by the vowels the algorithm will use the zeroth row and the zeroth column hence the matrix dimensions will be three by six that is three rows and six columns i will fill the first row and column with zeros immediately now we arrive to fill the value of this cell represented by index 1 by common sense we'll fill one in this cell because at this sub problem we only have a and the length is one this means there is just one string hence one on similar lines i'll put two in the subsequent cell because now i have a and e in my sub problem so for length equals to one we get two strings let's now fill three four and five in the subsequent cells we move to the second row now length is two but the string that is the vowel is one think what should be the value here it will be one but what string will this one represent it will be double a like i told you moments ago when we were brainstorming that to calculate the number of strings of length 2 the count of strings of length 1 will help so we are deriving this number 1 we are taking this number 1 from the top this represents all strings ending with a just like i said before we move to the next cell now in the same row i know that you are thinking right now that we will derive the value from the top because that represents two strings ending with e which are a e and double e yes you are thinking it correctly however there is one more component of the solution which is in this cell the value of which is 1 this represents double a which we calculated moments ago so 2 plus 1 gives me 3 which i will populate in this cell the strings will be double a e and double e let's move to the next cell the value which gets populated here will be the result of 3 from the cell above and three from the cell on the left so what we get from the top are a i e i and double i and from the left we get these three overall there are six strings of length two when we have just three vowels based on this concept what will be the value in this cell it will be 6 plus 4 which gives us 10 and the value of the last cell will be 5 plus 10 that results in 15. this last cell gives us the number of strings lexicographically sorted of length 2 when we are given these 5 vowels you will find the github link to the java solution of the gown sorted vowel strings problem from lead code in the description box below this concludes this video let me know how you are finding the series of lead code problems and solutions in choice dynamic programming tutorial any questions you have regarding this tp problem let me know in the comment section and if you liked the explanation then subscribe like and share this video until the next video bye
|
Count Sorted Vowel Strings
|
countries-you-can-safely-invest-in
|
Given an integer `n`, return _the number of strings of length_ `n` _that consist only of vowels (_`a`_,_ `e`_,_ `i`_,_ `o`_,_ `u`_) and are **lexicographically sorted**._
A string `s` is **lexicographically sorted** if for all valid `i`, `s[i]` is the same as or comes before `s[i+1]` in the alphabet.
**Example 1:**
**Input:** n = 1
**Output:** 5
**Explanation:** The 5 sorted strings that consist of vowels only are `[ "a ", "e ", "i ", "o ", "u "].`
**Example 2:**
**Input:** n = 2
**Output:** 15
**Explanation:** The 15 sorted strings that consist of vowels only are
\[ "aa ", "ae ", "ai ", "ao ", "au ", "ee ", "ei ", "eo ", "eu ", "ii ", "io ", "iu ", "oo ", "ou ", "uu "\].
Note that "ea " is not a valid string since 'e' comes after 'a' in the alphabet.
**Example 3:**
**Input:** n = 33
**Output:** 66045
**Constraints:**
* `1 <= n <= 50`
| null |
Database
|
Medium
|
615
|
375 |
today we're gonna be working on your code question number 375 guess number higher or lower part two uh we are playing a guessing game here and the game will work as follows you're gonna be picking up a number from one to n you guess a number and then you win the game if you get the right number but if it is if i tell you whether the number i picked is higher or lower you will continue guessing but every time you tell a wrong number you need to pay that much dollars so this explains here uh the output is 16 because um so the number was picked up between 1 to 10 the winning strategy is as follows so you guess a number 7 and if it is not that number right uh like we're gonna be told that whether it's higher or lower but uh we need to pay seven dollars if it is not that one so seven and nine is a combination which can be told uh which is gonna tell us that we have to pay 16 if we make two mistakes right and then we're gonna uh we're gonna end up paying uh sixteen dollars so with sixteen dollars we can guarantee that we can get to the right solution the way we're gonna be doing it is using uh recursion and memoization or dynamic programming so for that one we're gonna be we're gonna have a table okay we're gonna have a table uh which is basically the size of that is gonna be n plus one and in the end once uh we are gonna be using the dynamic programming for that let's call it dp uh and it's a helper function um which also do the memorization uh and after keep updating our table and we're going to be returning 1 through n so this is the range and we're going to basically be returning we need the i throw and the nth column a value for that so we're going to have a helper function let's call it dp and this tp is gonna take the table and it's gonna have the row and the column okay if the row is greater than equal to column then we just want to return we don't want to process that okay and if it is uh if it we have already processed and uh it is not zero we're just gonna return whatever the value is so if the t row column is not equal to 0 that means we have already processed it so you can return it return rtr and then c okay now then we have gonna have a result equal to initially it's uh it's a maximum value j dot max underscore value okay and then we're gonna go through it by saying that our i uh sorry for and i it's gonna start with our row and the i is gonna go through all uh up to the column and then i plus right and then we're gonna have a temp result which is basically gonna be this i plus uh the max between the dp we're gonna recursively call that uh the table and uh the row is gonna stay the same but the call we're gonna uh we're gonna say that our column is gonna change to i minus uh one and the other one is the dp uh the same table but this time the row is gonna become the i plus one and then uh the column is gonna stay the same so between that and uh whatever is the minimum value uh between whatever the result was and the temp so we're gonna do that we're gonna update our row called like the table with this result and we're gonna return the result so the reason we are doing it is because the reason we're doing it is because we don't know whether we need to go to the right or left in order to come up with a optimized cost that's why we need to check both ways once we are setting the column to i minus 1 and once we are setting the row to y plus 1. yep and it works
|
Guess Number Higher or Lower II
|
guess-number-higher-or-lower-ii
|
We are playing the Guessing Game. The game will work as follows:
1. I pick a number between `1` and `n`.
2. You guess a number.
3. If you guess the right number, **you win the game**.
4. If you guess the wrong number, then I will tell you whether the number I picked is **higher or lower**, and you will continue guessing.
5. Every time you guess a wrong number `x`, you will pay `x` dollars. If you run out of money, **you lose the game**.
Given a particular `n`, return _the minimum amount of money you need to **guarantee a win regardless of what number I pick**_.
**Example 1:**
**Input:** n = 10
**Output:** 16
**Explanation:** The winning strategy is as follows:
- The range is \[1,10\]. Guess 7.
- If this is my number, your total is $0. Otherwise, you pay $7.
- If my number is higher, the range is \[8,10\]. Guess 9.
- If this is my number, your total is $7. Otherwise, you pay $9.
- If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.
- If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.
- If my number is lower, the range is \[1,6\]. Guess 3.
- If this is my number, your total is $7. Otherwise, you pay $3.
- If my number is higher, the range is \[4,6\]. Guess 5.
- If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.
- If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.
- If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.
- If my number is lower, the range is \[1,2\]. Guess 1.
- If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.
- If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.
The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.
**Example 2:**
**Input:** n = 1
**Output:** 0
**Explanation:** There is only one possible number, so you can guess 1 and not have to pay anything.
**Example 3:**
**Input:** n = 2
**Output:** 1
**Explanation:** There are two possible numbers, 1 and 2.
- Guess 1.
- If this is my number, your total is $0. Otherwise, you pay $1.
- If my number is higher, it must be 2. Guess 2. Your total is $1.
The worst case is that you pay $1.
**Constraints:**
* `1 <= n <= 200`
|
The best strategy to play the game is to minimize the maximum loss you could possibly face. Another strategy is to minimize the expected loss. Here, we are interested in the first scenario. Take a small example (n = 3). What do you end up paying in the worst case? Check out this article if you're still stuck. The purely recursive implementation of minimax would be worthless for even a small n. You MUST use dynamic programming. As a follow-up, how would you modify your code to solve the problem of minimizing the expected loss, instead of the worst-case loss?
|
Math,Dynamic Programming,Game Theory
|
Medium
|
294,374,464,658
|
52 |
okay lit code number 52 and queens 2 and it is exactly the same problem as the previous problem in queens and this problem is actually less than the other problem as far as the complexity is concerned well the same problem but the output type is different and is less so pretty much the same problem n queens a chess board and on n plays n queens so that the queens don't attack each other and as opposed to this problem where we have to return all the boards possible boards in this problem we just have to return the count so the video i have done this i've went through all this implementation how it's supposed to be so for this problem i'm just going to use this code my own code so i hope lead code won't ban me for this because it's my own code literally just to very quickly go over it so i put up permutations and since no coins can be on the same row they cannot be on the same column then it means that if you were to count from the rows starting from the first row each position of the queen and remember all those numbers that we go along the rows all these numbers are going to be the numbers from 0 to n minus 1 representing some kind of a permutation so no repeating of them because repeating would mean that they're on the same column so no repeating and what i did was actually taking that the other way the permutations from the permutations make the board and then check the board by very simple functions here you can watch the more detailed one in the previous video so in this video i'll just return instead of all the boards i returned the size and run code and it failed that's true because oh i messed up the lead codes okay i messed up the lit codes default code so let's see total and queens okay so it's going to be total end queen so i have to remember that number okay so okay total and the return type is going to be int run code okay seems fine okay and we are done
|
N-Queens II
|
n-queens-ii
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_.
**Example 1:**
**Input:** n = 4
**Output:** 2
**Explanation:** There are two distinct solutions to the 4-queens puzzle as shown.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 9`
| null |
Backtracking
|
Hard
|
51
|
1,977 |
welcome to another video on the coding the present let's start with the joke of the day welcome to another video on coding depressant let's start with the joke of the day so i had my first kiss when i was 14 years old it was just a second before my last case okay let's start with the question so the question is this number of ways to separate numbers you wrote down the many positive integers in the string column however you realize that you forgot to add commas to separate the different numbers you remember that the list of integers was not decreasing i don't that no integer had leading zeros return the number of possible lists of integers that could have written now to get the string number since the answer may be large return to moderate and small number seven so basically i'll be giving a string and we need to find out the number of ways to make different numbers likely 27 33 27 there's two ways there can't be any mods like 32 7 can't be an option here 0 is preceding 9 then in no case 0 can be useful this is the wrong input so i kind of got the idea to this last night while i was sleeping okay let's see exactly take this example one two three four nine six zero eight so my i have a solution of dp first of all let me tell you this is a hard question okay there is 14 000 submission and only three thousand like i have been accepted this seems like a pretty hard question at the first class but then you start thinking about it could be easy so i have a solution with o of n square complexity i kind of had the idea so i am hoping that this works so for this example let's see one two three four nine six zero eight let's see for one so the area will be fit like this and the answer will come over here in the last element okay so for this example let's say first value one answer will always be one because there is one way to do this then you go to one two how so then when a encounter this two so two can be separate number only if it is greater than the last digit single digit one digit number two is greater than one so it can how many ways are there to place one so there will be one now we go to here 12 this one this thing let's assume 12 this is the value of 12 so for 12 how many ways are there 12 can also be a number so there will be whatever the hair is plus one will be two now we come here is three greater than single digit two yes it is so there is one way that is one separate two separate three separate then we go to here two three again this one can be two three so is two three greater than the remaining that is one yes it is so there are two ways one and this one plus this one so it becomes two now we go here one two three so for one two three it will always be a valid number so we just add one to the last digit over here value now we go to similarly here 4 is greater than 3 then 1 then here 34 is it greater than 3 we don't care about 3 34 is it greater than 2 we don't care about that 34 because it is always going to be uh greater than the so 34 we check directly for 12 is it greater than 12 yes it is greater than 12 so we can simply say there are two ways to uh two ways twice can be written like 12 complete digit 1 comma 2 digit because it will always be greater than 2 if it is greater than 10 or 12 it will always be greater than 2 so this 2 plus four uh so wherever 34 is so this two plus this one gives us three now we go here two three four so is two three four greater than one yes it is greater than one then we can simply say three this three plus one equals to four now we go to one two three four that will always be valid so we can i add one to it okay now we go to nine similarly that nine can be written let's go to six that is less than six whenever six occurs okay occurs so six is less than nine so this one cannot happen like this place wall this uh this wave was basically all digits are separate one two three four nine but six comes with the it is not possible then we go to the next thing 96 is 96 greater than the last second uh two digit number that is 34 yes 13 so basically the number of ways to make 34 that is 3 plus 0 this 0 gives us 3 and then we go to sorry here we will hear it yes so 496 is it greater than last 3 degrees that is one two three yes it is then we can add this three to last three here then becomes six okay now we go to here that is three four nine six is definitely greater than these one two three four nine six is greater than 1 2 so simply we can add 2 to the 6 and we get 8 then we go to 2 3 4 9 6 8 2 3 4 9 6 greater than 1 yes then we add 1 and similarly 1 2 3 4 9 6 is also valid then we add plus 1 to it now again 0 it becomes 0 3 7 10 12 and so on now 8 and now 8 is greater than 0 so we will add this 0 to here but now we go to 0 8 but 0 8 they can't be preceding zeros so simply we say whatever written whatever is written here just transfer it over here like the number of ways ah ahead of zero it like eight number of ways of it you can say that will be zero and six zero eight would uh again check for when the three four nine it's greater than that to five this five will be added here okay so similarly this will happen and this is the solution it will be off and scale let's try to code it let's try save okay let's try to code it so for this we first need to maintain our dp okay since it's given that there is this number of since the length is given as a constraint it can't be more than 2500 so you can say it's the maximum value that can have 3500 yes that's right so now let's start with into end equals to one dot if a case comes if number of zero equals to zero i can simply return zero because that's a wrong input now this i think we can't initialize it let's try to make an array if we can okay so this one will be the case when whatever the first digit that will always be valid yes because first one is not zero okay h p j minus now what i need to do is that i need to check with the i need to make a different function and that will check whether this j i is less than the last one i comma jay let me just open that uh paint thing again okay so ij basically if this one is given then i will be given j will be given and j minus 1 yes j minus 1 comma this should be i minus j minus 1 minus t should be so basically for example in this case i will be 4 j will be 5 3 1 here and i will be 4 j will be 4 3 2 so what will be given back was will be 2 minus 1 comma 1 minus 4 minus 2 that is 2 1 minus 2 minus 1 okay now if any point of time if i 1 is less than zero then i can simply i one is less than zero then i can simply say that this is a smaller digit then i can return true but before this if dp off i think i don't need to check this one i think i will be checking it now if dpo dp it should be so j should be the real value i think it should be i yes j should be the equals to zero and i can return false if it's not zero you if go to that number okay let's see now so basically in this loop my js will keep iterating for example let's take this example 630 here uh it's the comparison between four nine six and one two three so four is greater than one definitely uh so far oh i don't need this actually i don't need a while statement i just need a if statement is equal to okay i can make this so basically when while it is equal to us or here if j is greater than i that means it was the same thing then i need to return false but if it's not that if norm of j is greater than num of j1 return to so okay like four nine sixes compared with one two three four since four is greater than one i don't need to check others because obviously it doesn't matter what happens later 4 is 1 greater than 9 and then 496 is always contributed to 123. okay but if g is at any point greater than i that means we have that means the comparison was made between the same digits throughout the loop so that means they are the same otherwise if the otherwise then other cases this one is less than that then in that case the upper one will be like one degree was like you get the gist of it so it was basically then it will be less than so it will return false i think you get the rest of it if i1 at any point is less than zero we can return true because it will be greater than that okay so now i check this if check is done then i can say dp of i comma j is equals to dp off j minus 1 comma j minus 1 minus d now the thing is that so j will always be the least value of j can be 1 so i can reach to 0 so that would not give me any problem but j minus 1 minus d can actually be less than 0 so i need to make this as max of 0 comma j minus 1 because whenever it is less than 0 then it returns me true which means basically if i was comparing 3 4 9 with minus 1 2 -1 digits up so it will return me 0 and -1 digits up so it will return me 0 and -1 digits up so it will return me 0 and i can simply say this thing and i need to use this one because c 1 4 9 is greater than 2 1 2 12. so that will be our gpu okay so if it checks out then it is this else tp of comma j is equal to also sorry this should be dp of i comma j plus 1 this should be dp of j minus 1 comma j minus 1 minus d plus 1 plus dp of i comma j plus 1 now here whenever this else statement appears j minus 1 minus d can't be less than 0 because if it was less than 0 then it will directly be converted given to me as true also i need to get a string over here i don't remember if you can pass it like my reference okay one more thing if now if i see that num of j equals to zero then i can simply say its tp is going to be whatever the tp of the next thing is okay let's see how it runs then i can return dp of n minus one comma zero okay so basically in this else statement if i encounter the place that is great and not greater than that so let's assume here was a six so in case of four then 60 is not greater than 69 okay but so uh so but it is definitely greater than nine so we take the next value of 69 wherever that is stored here 69 would have been here then we can calculate how many ways are there two to be it would be a 60 can be greater than 9 1 so 16 would have been one i think you kind of get that okay let's see what problem we are facing let's look for as i guess okay so we are getting that answer right let's try it with our only example it was one two three four nine six elevated answer should be one two three four nine six seven eight answer should be 17. okay so we are having some problems um what problem are we facing over okay so is it initialized or not i don't know it should be i think okay i need okay let's try this like this i don't know if you can compare two character values yeah some other problem addition of unsigned offset overflow okay it should be g1 i think first it should be achievable okay and this should be j1 i think this should also be saved okay so this was my problem before basically we need i was checking for i should be checking for j okay let's just try one month also i need to see if you can simply compare characters or not yeah we can't i think oh no oh yes you can i think so this kind of thing should work i think let's try submitting it problem wait isn't it strictly increasing which is non-decreasing which is non-decreasing which is non-decreasing okay so basically now if j equals to i then also i return true that's what happens when you don't read it clearly okay let's see how this happens yes that was a minor exchange okay sorry i forgot that we need to take the mod as well it's that kind of question okay let's make a mod variable you okay and time limit executed how is it exceeding time i think this is a problem okay so in the last thing is only it's uh exceeding the time come on man how was that thing in the last test case i just need to pass this one okay so now wow it is really big one now it will be executed 3500 into 3500 times because i'm thinking there are 3 500 ones over here oh it's exceeding the time but how's that is it working when i remove some once or not okay still exceeding the time what is the time limit exceeding okay working here but it's very bad okay i need to do something i think i'll have to think about it then come back thank you okay so i kind of got an idea to okay so i kinda okay so i kind of got an idea to this basically we can add a line that will check if the substring is are the same or not if they are same i can simply return true that can save me some time i don't know if okay all right okay although it is taking a lot of time i think memory limit excluder how can memory limit be exceeded i've never seen that okay time limited okay so we are facing some problems because when i submit this it shows tle for this input so i had an idea okay so the answer should have been this now it should run i think and you see now we have solved the question
|
Number of Ways to Separate Numbers
|
minimum-interval-to-include-each-query
|
You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros.
Return _the **number of possible lists of integers** that you could have written down to get the string_ `num`. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** num = "327 "
**Output:** 2
**Explanation:** You could have written down the numbers:
3, 27
327
**Example 2:**
**Input:** num = "094 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Example 3:**
**Input:** num = "0 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Constraints:**
* `1 <= num.length <= 3500`
* `num` consists of digits `'0'` through `'9'`.
|
Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?
|
Array,Binary Search,Line Sweep,Sorting,Heap (Priority Queue)
|
Hard
| null |
11 |
how to find out the container with most water so there are vertical lines drawn in the two endpoints of height and I 0 to I height so basically we have given one graph okay so this is one graph in this way so we have a vertical line which is drawn something like this so we have to check that container each of the vertical line will two of the vertical line will combine together to make a container so we have to find out the container which have the maximum um water storage capability okay maximum unit of water can be stored there so let's see this example what is we are having so this example says that so in this example if we can see it is very clearly showing that we have a input of height one eight six two five four eight three seven and uh the maximum unit store from this point to this point and so this is the uh container which is having the maximum store water so basically how we find out odds we have a seven unit here right seven and this is height is also seven so we got this as a 49 so the 49 is the outcome so basically the vertical lines are represented in Array and in case the maximum area of water that is being shown in the blue section Now understand now let's understand the approach how we can achieve this so basically suppose if I am having this graph and this is my index which I am having here as 0 1 2 3 4. 78 okay so what I'm going to do I'm just taking one index here this particular position and this one okay so first I will be choosing this area so for this area my maximum contain store area is this much correct which is nothing but 8 unit so what water store I can take it as water as it this I will keep it with me in the next attempt what I'm going to do in the next attempt I will be sifting my this area part this particular index 2 1 okay so if I have shifted my this index to 1 so now I got this point to this point so my store area is this much correct so I will update my water to from 8 to 49. from it to 49 now once I have updated to 8 to 49 let's move my index from this position as I have to move it to the bigger end so I will moving 8 okay 8 I will moving 7 or to six okay so now I will be getting this one as a point so this area I will be having the water store here I can see it is this is five unit and this is 7 units so it is going to be 35. okay it is going to be 35 so if it is going to actually it is 8 unit till here okay till here it will be so it is going to be 40 unit so I can see This is 40 unit and this 40 unit is not bigger than the water which I have stored which is 49 so I will keep 49 as it is now I will iterate for the next bar so what at the end what I will be getting that my x i index or X index and Y index both are at the same point so when both became at the same point then my iteration will end up okay so once my iteration ended up whatever the maximum water I will be having I will give it as a return let's do the same thing in coding and we'll see how it works so basically in this program we are going to write the maximum area which will be storing the vertical that is maximum a maximum area we are taking left and right of the height and then we'll Loop until the left and right will meet okay with this while loop and then we will be sorting the a pole of the vertical lines update the maximum area if it is required and also if there is a longer vertical present that we are going to check okay so that we are going to check and then we will return the maximum height now we'll run this code and we'll check how it is going to be okay so it throws an error that error says that maximum area so here I have it's supposed to be M also so let's run this okay so here we go so here we got the output thank you so much guys and do subscribe to code for placement we'll meet in the next video
|
Container With Most Water
|
container-with-most-water
|
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104`
|
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
|
Array,Two Pointers,Greedy
|
Medium
|
42
|
1,672 |
today we will try to solve this problem of lead code which is problem 1672 reaches customer wealth if you haven't seen my previous video go and see my previous video where i've solved the challenges before this so we'll try to solve this challenge in javascript and so what we have to do is basically we have to find and so basically it has an account i j is the amount of money that it customer has in the jet bank account return the valve that has the richest customer okay a customer wealth is the amount of money that they have in all their bank account they just customize the customer that has the maximum wealth okay so one two three two one three six this one is six equal so each of them return six uh not the one okay so see this one so it's one five seven three five so output is 10 okay so this one is 6 10 and 8 so yeah so basically we want to return the array inner array with the largest num with the largest sum right so if this is 10 then we want this one as the answer and we just want to return it so we will have to run two loops for sure here so let's try to tackle this take up this problem so first what we need is so we will need to create a variable right so we will create a variable let's say called uh store variable to store the value so if i create a storage and set it to zero that would be first thing i'll do second thing i'll do is i'll run a for loop so you know we'll just write down each step so if you write down how you want to solve the problem your 50 of the problem is already solved then you just need to implement the code logic like in terms of programming and then you can do it so see so we're gonna run a for loop here and we're gonna run it on accounts.length right like on accounts.length right like on accounts.length right like on accounts basically also we can get access to all these inner arrows these ones i'll just put it here sorry yeah so this one right so you want to get access to this and answer would be 10 okay so we'll get to this so now we'll have access to this one now what we want so now we want to run again a for loop right and we want so for that we will need to create one more variable which will store all the sum so let's we'll call it sum and we'll put it zero then we'll need to run a loop again on the value we stored right from accounts of i that particular element so we'll run a for loop again then a for loop and we will add that sum which is 0 and always the value which we'll get from account set i right that it value every time like sub inner array this array will try to add it right and then at the end we will need to know that which array has is maximum so for that we can use the method in a use method in javascript to find maximum yeah okay so let's try to do this so as we said let's create a variable called store so what it's gonna store max value just try to see how we're gonna solve this very easily and i'll explain you everything so variable store max value equals zero now i'll try to create a for loop so for variable i equals zero i should be less than accounts dot length i plus right now what we want is basically i'll create a variable inner array so you know the element which we're gonna get hold of using this for loop will be in an array right you see here one comma five this one so it's really easy see how we're gonna do it so we're gonna get we wanna get accounts at i see we got it we got access to this easy now what we want to do now we want to create a new variable so we will remember we said we're going to create a variable sum which will be equals to zero right so we created a variable sum which is equal to zero so inside this for loop currently we have an in an array so in this example it is one comma five c one so we want to iterate over this one so what we do we create one more for loop we get four variable j equals zero j should be less than so we already store this thing inside this inner array so j should be less than inner array dot length easy and j plus right cool now what we can do so now i want to store this value inside this sum equals to sum plus inner array at j yeah cool i think i'm doing it correct yeah so we've got this now what i want every time i run this for loop inside this so i got for this instance let's say i got six answer what i want to use this sum and uh store it inside the store max value so what i'll do i'll use the method in javascript so what i'll do i'll use the store max value so i want to every time update my max value right so i'll repeat this whole process every time and see what my max value is so for that i'll use the method math.max that i'll use the method math.max that i'll use the method math.max sorry so math.max sorry so math.max sorry so math.max and you just write both the values through what you want to check every time so one is the one we have which is store max value which is zero in beginning this is the value which we're gonna written at the end and the value which get updates every time which is sum right so if this method will return the maximum value so currently the maximum value in this case will be one comma five sum which will be six because this is zero this is six so it's six it will return six as the value and it will give it to this variable again so this will be six second time sum will be ten so this will be six this will be ten and okay it will say okay which one is maximum okay this one is maximum sum then it will give this value to store max file what we'll do we'll just return it store max value right so if you do this then that's all so if you understand whatever i said uh yeah so now if you try to run it should work see we got run time of 402 i mean if you try to submit it should pass all the test cases as well yeah it's just 56 cents and faster than 97 of the online solution so really good way to solve the problem and yeah really good solution and if you didn't understand anything in this video because this challenge could be a little bit hard because you had to use two for loops so comment down and maybe i can come up with a on the technique through which you can understand but yeah hope this helps thank you make sure you subscribe my channel and comment like
|
Richest Customer Wealth
|
find-the-index-of-the-large-integer
|
You are given an `m x n` integer grid `accounts` where `accounts[i][j]` is the amount of money the `ith` customer has in the `jth` bank. Return _the **wealth** that the richest customer has._
A customer's **wealth** is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum **wealth**.
**Example 1:**
**Input:** accounts = \[\[1,2,3\],\[3,2,1\]\]
**Output:** 6
**Explanation****:**
`1st customer has wealth = 1 + 2 + 3 = 6`
`2nd customer has wealth = 3 + 2 + 1 = 6`
Both customers are considered the richest with a wealth of 6 each, so return 6.
**Example 2:**
**Input:** accounts = \[\[1,5\],\[7,3\],\[3,5\]\]
**Output:** 10
**Explanation**:
1st customer has wealth = 6
2nd customer has wealth = 10
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.
**Example 3:**
**Input:** accounts = \[\[2,8,7\],\[7,1,3\],\[1,9,5\]\]
**Output:** 17
**Constraints:**
* `m == accounts.length`
* `n == accounts[i].length`
* `1 <= m, n <= 50`
* `1 <= accounts[i][j] <= 100`
|
Do a binary search over the array, exclude the half of the array that doesn't contain the largest number. Keep shrinking the search space till it reaches the size of 2 where you can easily determine which one has the largest integer.
|
Array,Binary Search,Interactive
|
Medium
|
786
|
1,431 |
welcome to this video now we have according interview question kid with the greatest number of candies here's the problem statement you're given the array can and the integer extra candies where candice i represent the number of candies that the eighth kid had for his kid check if there is a way to distribute extra candies among the kids such that he or she can have the greatest number of candies among them notice that multiple kids can have the greatest number of candies this is the problem statement if you're given this array and extra candies equals to 3 then we have to return this array rt represent true and if represent false how this array is calculated we have here extra candies three and the maximum value we have in this array is five we have extra candice three if we if i distribute this extra candies to this zeroth kids this will be evaluated five and that's equal to the maximum value we have in this array so in this case it's true then we have here three plus 3 is 6 that greater than the maximum value we have in this array so we inserted here true then we have here 5 plus 3 equals to 8 and the maximum value we have 5 so 8 is greater than 5 that's why it's evaluated true then 3 plus 1 is 4 is less than the maximum value 5. so in this case it evaluated false then 3 plus 3 is 6 is greater than the maximum value we have in this array so at this position we have true if you're given this array as input and extract hand is equals to 1 then we have to return this list the maximum value we have in this array 4. if we add 1 to this element 4 this became 5 so 5 is greater than 4 that's how it evaluated true then we have here two plus one is three is less than the maximum value so it's evaluated fault and for the rest all right now how we can solve this problem let's suppose that we're given this array and the maximum value we have in this array five first our goal is to find the maximum value in this array we found maximum value 5 this is the maximum value then we're going to iterate through this array from left to right first we're going to add 3 to this value 2 that's equals to 5 then we're gonna check does 3 plus 2 is greater than or equals to 5 yes it is if that 2 then we will insert true in our list corresponding to this index then for next iteration 3 plus 3 is 6 is greater than 5 let's insert 2 to the corresponding index then we have 5 3 plus five is eight is greater than five let's insert true to the corresponding index then we have three plus one is four is less than five in this sketch we have to insert false to this index then 3 plus 3 is 6 is greater than 5 so we'll insert true if you are given this array what we should return also we are given extra candies equals to one first let's find out the maximum value in this array we have the maximum value in this array is four then we're going to iterate through this array from left to right first we have the element four this is current element one plus four is five is greater than max so at this corresponding position we'll insert true then 2 plus 1 that is less than 4 so insert false then 1 plus one two that is less than four let's insert false then one plus one that is two that is less than four let's insert false one plus two is three is less than 4. let's insert here false in this case we have to return this list now let's see how my solution might look like in pseudocode first i'm going to declare a functions kids with candice it takes an array of candidate and extra candidate let's suppose that this is our given array and this is extra candidate and we have here empty list that you need to fill off first we declare the empty list and this is the empty list then we're going to initialize variable max equals to the minimum integer we can store in an integer variable then we're going to run a loop from left to right to find the maximum value this loof will find the maximum value and the maximum value in this case five after that we're going to run another loop for i from zero to length of the cantiz array minus one if can this i plus extra current element is 2 extra s3 3 plus 2 is 5 so 5 is equals to max let's insert 2 right here then for next iteration our current element three plus three is six is greater than five so let's insert here two for next iteration our current element is five plus three is eight is greater than five let's insert your true then for next iteration our current element is one plus three is four is less than five so let's insert here false okay and we're inserting false right here then for the next iteration our current element is 3 plus 3 is 6 is greater than five so let's insert here false all right at the end we're going to return this list this is my solutions to this problem the solution will takes big of 2 n time complexity that equivalent to big of n and the solution will takes constant space complexity since we're just using the solution we'll text big of n time complexity to construct our list hope this concept was clear if you have any question if you have any suggestion let us know thanks for watching this video
|
Kids With the Greatest Number of Candies
|
all-ancestors-of-a-node-in-a-directed-acyclic-graph
|
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _if, after giving the_ `ith` _kid all the_ `extraCandies`_, they will have the **greatest** number of candies among all the kids__, or_ `false` _otherwise_.
Note that **multiple** kids can have the **greatest** number of candies.
**Example 1:**
**Input:** candies = \[2,3,5,1,3\], extraCandies = 3
**Output:** \[true,true,true,false,true\]
**Explanation:** If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
**Example 2:**
**Input:** candies = \[4,2,1,1,2\], extraCandies = 1
**Output:** \[true,false,false,false,false\]
**Explanation:** There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
**Example 3:**
**Input:** candies = \[12,1,12\], extraCandies = 10
**Output:** \[true,false,true\]
**Constraints:**
* `n == candies.length`
* `2 <= n <= 100`
* `1 <= candies[i] <= 100`
* `1 <= extraCandies <= 50`
|
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
1912
|
729 |
hello everyone welcome to coder's camp we are 10th day of june lead code challenge and the problem we are going to cover in this video is my calendar one so we have to implement a my calendar class to store our events so it has two methods my calendar is used to declare your data structures and the other method is booking so here the book method has two parameters that is the start date and end date of your event and the return type is a boolean where you have to return true or false based on whether you can book the event or not so here we can book the event based on the start and end date that is if no two events are overlapping then we can return true if not we can written false so let's understand this problem with an example so here is our first input of the event starts at the day 10 and end at the day 20. so we don't have any other events yet so this event can be true as there are no overlapping events to it so the next input comes in starting with the date 15 and ending with 25 so if you see there is already an even starting happening during 10 to 20 so in that case we cannot start a new event which is starting in between of that event we either have to start end it before 10 or have to start after 20 so this is not possible so this event cannot happen so we have to return false and there comes the third input starting at 20 and ending at 30 where our first event ends at 20 so we can start our third event on 20 and finish finished off with 30 without any interruption so this event can happen so we are going to return true so how are we going to approach this so we can have a list which is going to store the start date and end date to maintain the events that is happening and every time a new event is entered to our method we are going to iterate this list to check whether any of the date or intercepting the current incoming event if that intercepts then we can return true if not we can return false but this is actually gonna take big o of n square time complexity as we are going to iterate the list by using big of young time and for every event that enters we are going to iterate the list so overall is going to take big o of n square time complexity so how do we do it in optimized way so if you see the hint they have given it they store the events as a sorted list of intervals if none of the events conflicts then the new event can be added so we are going to implement this only as per the hint we have to store our events based on the sorted order so the best candidate to store the events in sorted order in java is going to be tree map so we are going to get the help of tree map to store our even start date and end date so this maintains the data structure but how do we find whether we can make the event or not so there comes the help of ceiling key and floor key functions you must be familiar with these functions by now because we have used in two other videos previously while we implemented tree map so ceiling key is going to return the greater or equal value in the list or in the tree map if we pass a key same way floor key is going to return the less or equal value in the list so now comes our first even starts with the 10 and end with the day 20. so here in trimap we are going to store this as a key value pair where the starting date is the key and ending date is the value so now our first event enters and we are going to perform the ceiling key and floor key so it is going to return both null because till now we don't have anything added into our tree map so both are null so in that case there is no intercepting dates to this current event so in that case we are going to return true for the first event so then comes our second event 15 comma 20 so we are going to perform the ceiling key and floor key methods for the key of the tree map which is nothing but the starting date so our sailing key method is going to look for equal or greater values but here the only single entry in a tree map is 10 comma 20 where 10 is the key we are going to check only for the key not for the value so here if you check for 10 comma 20 there is no equal or greater value to 15 because there is no 15 or there is no greater value than 15 so the only value in the tree map is 10 so in that case the ceiling key of 15 is going to be returned as null and now the floor key of 15 is going to be checking for the lesser or equal value again there is no equal value but there is a lesser value than 15 which is 10 so the floor key of 15 is going to be 10. so now by using these values how do we check whether it is intercepting with already happening event to do that we are going to check these two conditions so these two conditions are nothing but if we want to perform an event then its end date must be less than or equal to starting date of any other events that is our even must end before any other event start same way our starting date must be greater than the ending rate of any other event which is nothing but in other words our start date must start after ending all other events in the list so now to check these two conditions we know what is the end date and starting date of the current event because those are the parameters being passed to the method but how do we check the starting date of other event or ending date of other event happening so there comes the need of selling key and floor key so here the starting date of the other events is nothing but the key value written from the tree map because a cl key is going to return the nearest equal or greater value from our key so if suppose it returns any value and that is actually greater than the end date which means our current event end before any other date or even that is happening if suppose the starting date of any other event returned is less than the end date that is if the end date of the event is 20 and the return date is like 16 or 17 in that case there is some other event which is happening so if this condition is satisfied then in that case we can start our event and we can put this into our map same way it has to satisfy the other condition as well that our starting date of our event must be greater than or equal to end date of any other events so how do we get the end date of any other events that is get off the floor value return so why get off because the value stored in the tree map is the end date not the starting gate so we are going to get the get off floor value because the flow value is nothing but the nearest lesser or equal value so here the nearest lesser or equal value is 10 so what is the end date of that event which is 20 so if our starting date is greater than that end date which means we can start our event after that event completes if not if it is a lesser value then in that case our date interrupt with the already happening event so if these two conditions are satisfied then in that case we are going to add that event to our tree map if not we are simply not going to add it and return false and we are going to perform the same check for every other event entering into the function and if this satisfies then we are going to return true and add that to our map so why do we need to add that because we have to check further events whether these event is interrupting that event or not so hope you are understanding the solution and this is gonna work in we go of n login time complexity as we are performing the operations that is inserting the values to a tree map that is going to take login time and we are going to check these ceiling key and floor key every time for the new event entered that is overall it is going to take big of n log in time complexity so let's go to the code now so yes as we explained we need a tree map which stores the start and the end date and we have a constructor to initialize our data structure so inside of a book method we are going to find the ceiling and floor value of our start key so here i am declaring this as an integer instead of just int because this ceiling key and floor key sometimes return null value so in order to handle that we have to declare it in integer so now we are going to check that condition that if our flow value is first null so this condition is nothing but whether any other events in date is less than or equal to start and this condition is nothing but whether our end date is less than any other events starting date so both of the conditions are true then in that case our event is not interrupting with any other event present in the tree map so in that case we are going to add that to our map and if we can successfully add that which means we can return true that this event can happen if not finally return false so yes let's run and try yes so let's submit yes the solution is accepted and runs in 21 milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
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
|
935 |
hello guys and welcome back to lead Logics this is the night dialer problem from lead code it is a lead code medium and the number for this is 935 so many of you might be finding this problem a bit difficult to solve but I'm going to tell you a way that will make this problem super easy for you so watch the video till the end so in this problem initially you are told about what a chess KN is so a chess KN is a like you can say uh player not player chess Knight has some movement like it can move uh If It Moves too straight horizontally and then uh either uh one will be vertical like if you see uh it may move two squares vertically and one horizontally or two squares horizontally and one vertically that means like if it moves two horizontally then one vertically and same goes It goes down then it can go left or it can go right one square and then similarly for it if it goes two blocks right then it may go one block up or one block down so this is the movement of the chest Knight so what we have to do now so suppose we have a chess Knight and we have kept the chess Knight on a numeric cell you might have seen the old phones keypad phones in which we have this kind of keypad also in the smartphones if you go in the keypad there are given this kind of keypads so you can definitely remember what this is so what you have to do we have to Define an integer n such that uh how many distinct phone numbers of length n can be this we have to Define and we are allowed to place the Knight on any numeric cell initially and then we should perform n minus one jumps to dial a number of length n so how many distinct phone number of length n can we dialed this we have to Define and uh so let's start the problem is initially asking for the number of distinct phone numbers of length n that can be dialed using a chest Knight movements first point then we need to find uh maybe a recursive solution to calculate the count while considering the moves of the night so let me show you a keypad suppose this is a keypad so what we'll do we'll create a array of moves this array of moves will uh contain the where the Knight can move from a particular index like if it has zero from 0 it can go to 4 and six how suppose we have it at 0o so it can go 1 2 then vertically or 1 2 horizontally and then vertically it can go at six or it can go at four so similarly we have defined for all the other indexes suppose at 8 it is given it can go to 1 or three so from 8 it can go horizontally to five then two then vertically at 1 or three so 1 three is given here so this is a moves array so and also we are going to use a cache that will be used for memorization uh storing previous computed result for optimization so let's start with the coding section see so we need to define a mod as well because the answer May overflow so that's why we are defining a mod and then we'll paste here the moves array which you have created so I've copied it from here you can see and write it so this is the moves array and uh then we are going to create a the cache array so for that I will be using an INT array 2D array of the size may be let's see the constant so it is given 5,000 so we'll take 50001 and this will be 10 because we have 10 numbers and then I think we need to overwrite the function so for that we'll be making an another so we have to pass the n and also a new array of the next numbers so the next numbers we have to pass here and in the next number initially we have to give 0 1 2 3 4 5 6 7 8 9 so these are the index actually so we have pass the indexes here and then we'll Define the you can take the other names for the function as well like helper or any other I have taken the same I have over written um I'm telling you so that you may not get confused so we have the remaining we'll name this remaining here and these are the next numbers so if remaining equal to remaining if remaining equal to not zero it will be one so this is the base case so base case is if remaining is equal to zero we have nothing remaining so we need to Simply return the next numbers do length because this will be the final answer if uh the remaining equal to one otherwise we have to put declare account equal to 0 then we have to iterate on the next number numers so in next number in the next numbers so we pick a current element and then we check this current actually is taken from the cache so if there the cach will be zero then we need to do some computation that means cash equal to zero that means there was no previous record at the particular index and if the cash that is stored in the current is not zero then we can directly do the uh the operation on the count so if the cash was Zero that is current equal to zero so we have to recursively call the night dialer again and in this we will do remaining minus one and move of the next number otherwise no this we have to make current because we need to update the cache as well so we are updating the cache now if then we have to do operations on count if the current is not equal to zero then this operations will directly be um occurring so that's why I'm not using else here and uh after the recursion is over we need to Simply return the count of the entire night dialer function so I think everything is written fine now let's try to formit it on the sample test cases seems fine on the S sample test cases solution is accepted as well the good memory and a good space you can see 100% 100% 100% 94% so the time complexity for this is 94% so the time complexity for this is 94% so the time complexity for this is actually n into 10 because we are making 10 recursive SCS uh for each number so that is time complexity is of n because constant is neglected and the space complex is also ofn because we are using this uh cach ARR and moves is a constant but since we have a bigger notation so of O ofn so the time space complex be o if you want to see my uh C++ JavaScript if you want to see my uh C++ JavaScript if you want to see my uh C++ JavaScript or python code you can go in the solutions section and then check this one this says beats 100% here you will 100% here you will 100% here you will find the written so explanation along with the C++ Python and the JavaScript with the C++ Python and the JavaScript with the C++ Python and the JavaScript codes so you can see it from here and do remember to upload the solution so and like the video share it with your friends subscribe to the channel if you're new to the channel thank you for watching the video have a nice day
|
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 |
347 |
hey everyone welcome back today we are going to solve problem number three four seven top K frequent elements first we will see the explanation of the problem statement then the logic and the code now let's dive into the solution so here I've taken the first example from the lake website so in this problem we are given an input array where we have the elements and we have a variable called K so we need to find the top K frequently repeated elements right so in this case we need to find two elements which has appeared most of the times so here 1 has appeared three times two has appeared two times and three has appeared one time so we need to pick up two elements the top two repeated elements so here one has repeated Thrice right so we will pick one as the first element then we need to pick 2 as the second element since it has appeared two times and we will avoid 3 since we only need two elements so we written one and two as the output and we are going to solve this problem using Heap now we will see how we are going to do this so initially I will create a dictionary where I will store the element and the count of the element so here Oneness the element and the count of 1 is 3 and 2 is the element that is in the input array and the count of 2 is 2 has appeared two times right so the count is 2 then 3 is appeared one time then I will create a heap where I will append the count and the value so initially I will append the count 3 and 1. so the reason why I'm multiplying with the negative is that in Python there is no a direct usage of massive function so If I multiply that particular element with negative sign then I will pop this number as my first element so when you multiply the negative with the large number you pick the large number as the first value when you use Min hue right that is the reason why we are multiplying with negative sign here then I will append 2 and 2 so the first element is the count and the second value is the element that is the number right then negative 1 and the value 3. so when I use Min Heap I'm going to get the largest repeated number so in this case I will get negative 1 and 3 so I will just take the value alone I will append that to a result list right then I will get negative 2 and 2 then I will just pick the number and we are done here since we need only two elements we have picked the two most repeated elements that is 1 and 2 here then I will finally return this list right so the time complexity will be order of n log k and space will be order of n that's all the logicals now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially I will create a dictionary where I will be keeping the number and the number of times it has been repeated right so here I am using counter function to do that task then I will be creating a heap list I will be appending the count by adding the negative sign and the value right then I will be creating a result list then I will be running a loop where I will run the loop for K times where I will get the top K frequently repeated Elements by popping it from the Heap list then I will append that particular values to the result list then finally I will put on result right that's how the code is now we will run the code as you guys see it's pretty much efficient 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
|
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
|
1,822 |
hello guys I hope you're doing great today I will be explaining the lead code challenge which is called sign of the product of an array so here to task is to multiply the elements of a list and return one if it is positive minus one if it is negative and zero if it is zero it is very easy actually but uh you don't need to do multiplication here you can count the minus values in list if the number of negative integers in the list is equal to the an even number you can say that it will return a positive number if there is even one zero inside the list you can return 0 because the multiplication of lists will be zero if there is odd number of negative integers in the list you return negative so how can I write this for noon in Norms I will iterate over the list and if this Norm is equal to zero you just return zero and if this Norm is less than zero you will count the number of the negative values so let me Define it count is zero and if the remainder of count value is zero when it is divided by two uh your return one it means that this multiplication would return a positive integer and we want to return one if it is positive uh actually I should get out of the flow and else return -1 -1 -1 so here in the for loop I count the number of negative integers in the list and if the count can be divided by two return one else return -1 return one else return -1 return one else return -1 let's run this and if you submit it as you can see the solution is accepted I hope this video was helpful for you thanks for watching
|
Sign of the Product of an Array
|
longest-palindromic-subsequence-ii
|
There is a function `signFunc(x)` that returns:
* `1` if `x` is positive.
* `-1` if `x` is negative.
* `0` if `x` is equal to `0`.
You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`.
Return `signFunc(product)`.
**Example 1:**
**Input:** nums = \[-1,-2,-3,-4,3,2,1\]
**Output:** 1
**Explanation:** The product of all values in the array is 144, and signFunc(144) = 1
**Example 2:**
**Input:** nums = \[1,5,0,2,-3\]
**Output:** 0
**Explanation:** The product of all values in the array is 0, and signFunc(0) = 0
**Example 3:**
**Input:** nums = \[-1,1,-1,1,-1\]
**Output:** -1
**Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1
**Constraints:**
* `1 <= nums.length <= 1000`
* `-100 <= nums[i] <= 100`
|
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
|
String,Dynamic Programming
|
Medium
|
516
|
137 |
Hello gas welcome you my YouTube channel so today we are going to solve link road problem 137 single number you so this question is what is this sir number in this is what is in this sir number is thrive except one number. So I have to find that same number, this is the question in simple words, so as in this question, 222 is there three times and 3x 12, then the answer will be 3. In seconds, zero and one are there three times each, and 99 is there once, then the answer will be 99. So basically just solve this and a constant has also been given in it. You have implemented the solution with linear run time complexity and it has only constant. From one side it is fine but if there is such a question then first you have to do it from the basic. What will be the first approach? How many times has that number come? As soon as a number is found one by one for the first time, like keep it here, then you will count it, which is the index on each and then run the loop on k, how much will come if two. Three A's gone 2 then nothing, now we will check further as soon as three pay comes, now we will check it further, if one A goes then we will direct return from D, then this becomes n² and how much space is there O and Then what can be the second approach which can have on time complexity on square 03 times and your one is also three times at 99, now we will travel in the map and will check by tabling in the map in direct map and what can be one approach, now the third approach. Which is beat manipulation, so now how will we optimize it, let's see that, so let's see this, we know this much that we have written it in the representation of sir son. Now I know one thing that sir number is when sir number is. So always which is this which here is this three times so there will always be a number of 3 in the account, this six can also be six on the base beat, you on the beat of six is one and you are also one you on the beat of six is one and you are also one you on the beat of six is one and you are also one on the second, so both are one. So how many times is this happening? Six times, six times, then it can be a multiple of 3, one will be a multiple of three, and one can be a multiple of 3, plus one, neither can it be one more time, we will mode from 3 to 3. If we do mode with then now we will see like this how to see how much zero is here first one is once here so once here means what is this 3x + 14 means what is this 3x + 14 means what is this 3x + 14 means here extra the number is its beat is the extra number. The unit is the extra number which you have to calculate, so its beat is So now here, the value of On this beat, on this beat, we will also slice them by zero. Now go to this beat and go to this and do more with this here and do operation 01. Now here again this is yours 3 * In the form of it means you, then what does it mean, it means extra, the extra number, its date is not happening here, the account is not getting fit, then the account is not getting fit, so now its extra is not getting fit, so here We will check that if the number that comes on 6th March is A, then it is A, which means that there is a one, that is your extra number, its beats are also being counted, so let's see again here, yes. So, if we are here, what will we do again? We will move I to the left, seat I to the left, shift one to left, which means the value of I will remain one, now we will look ahead of that, then if we go here, it will be set to zero again. If there is, then here only zero will remain zero and next to that, sir, look at zero is zero, how much is it equal to 00000, then this one can also be the one with beat, many less, at first I don't judge that much but come in the interview. You will have to do this, if it comes, then this solution will run on such an online compiler because there is not so much space, no compiler checks it. Okay, now let's see its code. What is its code? What was taken first? We will check the result on every beat and account in it. How many times will we band it? How to do it? First, shift right on it and go to one. We will do it three times here, we will right it here, we will check everyone's account, we will check everyone's head number, every time we get one, the account here will be plus one and whenever. Here, if you take a mother, here is any number like this relief, here relief is zero, now we used to shift this also, here comes zero, if we shift it by three, and here with one, if we do more, then zero is relief, then plus. So even if the account is not there then the account will not be plus and then we are checking here, tell us the number which is like the extra number which has come once, it will remain there only if it remains there then only you can give a condition here. If you don't give it, then it will work, here is a condition, you can also give account one note equal to zero, if you look here then what is the meaning of one, that is, if there is 3 relief on it, then by tipping it left, then index it like it is going on the beat. Which is on the beat also, do the same thing, that means 3x + 1 time, like if I take it for do the same thing, that means 3x + 1 time, like if I take it for do the same thing, that means 3x + 1 time, like if I take it for five, then if you do zero for the first time, then how much will come here, zero will come to one, this one which was one here, this one, now what is the answer? Zero zero one what will we do now then if it was on the second beat then we will go to the second beat but make this here now if we do something else with this then there will be zero here then it will become one so now what was here zero one then one here So now if we do it again then this one will also become one, so this one is making the number 101, in this one, this is what we are doing here, by going to the beat and banding it to the beat and making the result. and then the final result
|
Single Number II
|
single-number-ii
|
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
| null |
Array,Bit Manipulation
|
Medium
|
136,260
|
1,491 |
um hello so today we are going to do this problem which is part of Fleet code daily challenge average salary excluding the minimum and maximum salary so pretty uh it's an easy problem today um we have an array of integers salary and the salary at position I is basically the salary of the ith employee and want to return the average salary of employees and want to exclude the minimum and the maximum salary okay so what that means basically is we get the average except we don't include them in the max so logically the simplest thing to do is just to get the sum right of the salaries then exclude the minimum exclude the maximum and then to get the average divided by the number of elements now what's the number of elements it's just the length of the array -2 y minus two well length of the array -2 y minus two well length of the array -2 y minus two well because we removed the minimum in the maximum which are two elements right so very sureful solution if you want you could also sort and just remove the first and the last element and then take the sum the average of the rest that's also a valid option um and so for this solution though we will just go with the simpler approach which is getting the sum of all of them then we subtract the minimum and we subtract the maximum and then we divide by the number of elements which is just the length of the salary minus two right that's how many elements we have once we remove the Min and Max so if we're on this um looks like we yeah just here just to make sure this is done properly yep now it should work and it gets accepted we this is um open because we are getting the sum of the salary and the Min and the max so over and time um in this constant space yeah so that's pretty much it for this problem please like And subscribe and see you on the next one bye
|
Average Salary Excluding the Minimum and Maximum Salary
|
number-of-times-binary-string-is-prefix-aligned
|
You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Output:** 2500.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
**Example 2:**
**Input:** salary = \[1000,2000,3000\]
**Output:** 2000.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
**Constraints:**
* `3 <= salary.length <= 100`
* `1000 <= salary[i] <= 106`
* All the integers of `salary` are **unique**.
|
If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too.
|
Array
|
Medium
|
319,672
|
702 |
everyone so today we're looking at lead code number 702 search in a sorted array of unknown size okay so this question is basically we have a sorted array and but we don't know what the upper bound is we don't know how big this array is and so we need to search through this array and see if the target is in there and if it is we're going to return the index so let's just kind of review over the prompt given an array integers given an integer array sorted in ascending order write a function to search target in nums if target exists then return its index otherwise return -1 return its index otherwise return -1 return its index otherwise return -1 however the array size is unknown to you may only access the array through array reader interface where array reader.getk returns the where array reader.getk returns the where array reader.getk returns the element of the array at the index k zero index okay and we can assume that all integers in the array will be less than ten thousand and if you access the array out of bounds it will return this very large number okay so here we have an input array minus one zero and so forth and our target is nine we don't know what the upper bound of this array is so there would be two ways we could look at this we could scan this linearly and just try to go through each one however if it's if the element is not in there we don't know when the array ends and we can end up with an infinite loop the issue with doing binary search is that's the other approach we could do this but we need to know the upper bound we know the array is sorted but we don't know what the upper bound is okay so how would we go about solving this let's jump over here in the conceptual and think about this so let's say we have this array let's use a different color here i'll use white let's say we have this array and it goes on for length let's say 5000 right okay but we don't know what the upper bound is what we want to do is we want to figure out the range that target is in so for example if the target here was let's say 2500 okay we know what the lower bound is we know what the left is we can start it at 0 okay and now what we want to do is we want to have a right and then we want to multiply this right by 2 and then set the left to the right and then keep on multiplying the right by two so what we're essentially doing is we're getting a range from here then we're getting a range from here and so on and so forth until we find the range where our target is in okay so just to kind of reiterate that so it makes a little more sense let's actually use some numbers here let's say we set our right to one and our left to zero okay and our target is 2500 and let's just say these numbers are sorted one through five thousand okay now if we say is the range is 2500 in between the right and the left no it's not so then what we can do is we can set left to right and then right we can just multiply right by two okay so right will go from one to two to four to eight to 16 so on and so forth until it gets above until right is um above the target okay so let's say right gets to 3 000. right and left is going to be set so as we go up this is left and this is right what we're then going to do is once right is here we're going to place left there so now the range we're looking at is between two and four okay when right gets to eight the range we're looking at is from four to eight when right gets to sixteen the range we're looking at is from 8 to 16. okay and so on and so forth and whatever right is at 3 000 the range will look at the left will be just whatever right was previously which would be half of that which would be 1 500. okay so that's the idea and then once we know that range once we know that our target is in between 1500 and 3000 then we just run binary search on that's all we have to do and so we can get a login solution we just run two login uh passes one pass is getting the range would be log n and then the other pass would be finding the target between that range would which would also be log n because we know it's sorted okay so it's not too bad when we think about it that way we just need to calculate the right and find the range between right and left and then we just go ahead and run binary search okay and i'll just quickly kind of go over how binary search will work let's say our range is right here like whatever the input is and we go ahead and we have our left here grab this left here and let's say our right starts out right over here and our target is nine okay so now right is not less than the target so what are we gonna do we're gonna say right times two right is going to equal well first we're gonna set left to right okay so i'll go ahead and move this left over here and then we're going to say right is going to equal right times 2 so right will move over there okay so now our range is between 1 and 2. now we ask is this right is it less than the target it is so what are we going to do we're going to multiply right by 2 which is going to equal 4 and we're going to set that left to whatever right was previously so now the range is between indices 2 and four okay and now we ask is right less than not less than or equal to but is it less than the target it is not less than it's equal to but it's not less than so we're going to say right times two the indices times two which is going to be eight okay so we'll just go ahead and say right here is going to be at eight okay and left is going to equal wherever right was previously now we know that our target is in between this range okay our target is nine and so now all we have to do is go ahead and perform binary search between that range and we go ahead and get our solution now i'm not going to go over binary search i'll leave that for a separate video but you should be familiar with that pattern binary search it should just come instantly to you uh we'll quickly go over what we're going to do is just find the mid if the target is less than the mid then we're going to go ahead and move this right over here to mid minus one and then we'll set a new mid if the target is less than mid we'll set it to mid minus one we'll set a new mid and then the target will equal mid and we'll get that nine okay and so that is a log n time complexity both ways we're doing one login pass to get the range and then we're doing another login pass to go ahead and get the actual target okay which is pretty good so let's just go ahead and write our time and space complexity here our time will be o of log n and our space complexity we're not creating any new space we're not storing these numbers anywhere we're creating some variables but the space is not increasing relative to the size of the input so our space complexity for this will be constant which is really good and the big clue on this is that anytime you see sorted array you should initially you should immediately think binary search can we run binary search on this if there's some sort of search that we need to do and the input is sorted okay so let's just go ahead and jump into this code let me move this down a little bit so we have some space okay and so what we're going to do is we're gonna set our left to zero and our right to one okay and so now what we're gonna do is we're gonna first figure out where is the range so while uh reader which is this method here so we'll do reader.get write if it is less than target what do we want to set left to right and right is going to equal right times 2. so that'll keep on running until we get that outer that upper bound on right okay now what do we want to do we just want to perform binary search so we just say while left is less than or equal to right we want to get our mid let mid equal floor left plus right divided by 2. got to make sure you have these extra parentheses or you're going to get a bug because it'll do right divided by 2 plus left so we want to go ahead and do that and now what do we want to do first we want to check does the mid equal are we at our target so we can just do a quick if statement here and we can say let reader dot get mid equals target if that's true then go ahead and just return mid because we want to return the indices of where our target is not the actual number okay and now we want to check if reader.get left is less than or equal to reader.get left is less than or equal to reader.get left is less than or equal to target and target is less than reader.get mid if that's the case reader.get mid if that's the case reader.get mid if that's the case what do we want to do we just want to update our right okay because it's going to be on the right side so we just say right is going to equal mid minus 1. else what do we want to shift our left so left is going to equal mid plus 1. and if we don't find it in there then we just go ahead and return minus one move this down so you can take a look at that code okay let's go ahead and run this make sure everything works okay and we're good i don't know why it does this 26 it's uh you can see here that if you just run it again and it's 80 you're in the 90th percentile but it's log n it's the time and times complexity is log n and our space complexity is constant i think my internet may be a little slow that's why it's uh taking longer uh you can see here so 97 94 run time and then 80 on space so that is lead code 702 search in a sorted array of unknown size i think the thing you have to think about this is you can easily apply binary search to this that's not a difficult pattern match but it's how you get that range which is this block of code right here getting this right thinking of multiplying right by two and getting that correct range so that's something that's uh a little tricky about this one but other than that it's not too bad okay so that's lead code 702 i hope you all enjoyed it and i will see everyone on the next one
|
Search in a Sorted Array of Unknown Size
|
search-in-a-sorted-array-of-unknown-size
|
This is an **_interactive problem_**.
You have a sorted array of **unique** elements and an **unknown size**. You do not have an access to the array but you can use the `ArrayReader` interface to access it. You can call `ArrayReader.get(i)` that:
* returns the value at the `ith` index (**0-indexed**) of the secret array (i.e., `secret[i]`), or
* returns `231 - 1` if the `i` is out of the boundary of the array.
You are also given an integer `target`.
Return the index `k` of the hidden array where `secret[k] == target` or return `-1` otherwise.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** secret = \[-1,0,3,5,9,12\], target = 9
**Output:** 4
**Explanation:** 9 exists in secret and its index is 4.
**Example 2:**
**Input:** secret = \[-1,0,3,5,9,12\], target = 2
**Output:** -1
**Explanation:** 2 does not exist in secret so return -1.
**Constraints:**
* `1 <= secret.length <= 104`
* `-104 <= secret[i], target <= 104`
* `secret` is sorted in a strictly increasing order.
| null | null |
Medium
| null |
950 |
hey what's good guys it's ilya bella here i recorded stuff on youtube chat description for all my information i do all lit good problems uh make sure you subscribe to your channel give me a big thumbs up to support it and this is called reveal cards in increasing order in a deck of cards every card has a unique integer you can order the deck in any order you want initially all the cards start face down and rolled in one deck now you do the following steps repeatedly until all cards are revealed first take the top card of the deck reveal it and take it out of the deck second if there are still cards in the deck put the next top card of the deck at the bottom of the deck third either still unrevealed cards go back to step one otherwise stop return and ordering of the deck that would reveal the cards in increasing order the first entry in the answer is considered to be the top of the deck well let's look at this example we got this input right here and we return this output uh this order doesn't matter we reorder it after we order and we have uh this right here two is the top of the deck we reveal two and move 13 to the bottom to the end then we reveal three we move 11 to the end then we keep doing that 5 10 17 to the end 7 then 13 to the end then 13 then 17 to the end and finally we reveal 17. since all the cards revealed are in increasing order the answer is correct the length of that array is greater than or equal to 1 and is less than or equal to one thousand a i is greater than or equal to one and is less than or equal to two by standard raised to the power of six a i is not equal to a j for all i is not equal to j well we can solve this problem using q data structure q means that we are elements to the tail to the end of that q and then we can pull the elements from the head of that cube and how that works go ahead first we create and which is going to that deck uh then the result which is uh new array of the type integer has the length which is equal to n and we need to sort um this deck in ascendant order means that we um use a variation of quick sort to pivot uh that takes big off and login time we create q of the type integer q new linked list type integer create a for loop in type which is zero isolate then n and i plus and we keep adding in this is that q uh create another for loop in i which is zero i select an n and i plus and at each duration we say result at q dot poll and is equal to q on deck at i and let's say q dot offer or let's say let's use offer right here instead of q dot pull finally we return the result that's it let's run this code accept it let's submit um there we go um this right here means that we reveal the element then right here means you know we pull the element from the head of that queue uh we insert this volume at the position of this element which is already revealed and we which is already pulled right when then we move the next um element to the bottom to the end of that queue we insert to the end we update the position of that element of that index that means this right here means indices right q contains indices and finally we return the result let's look at this example we got this input right here n which is three six seven then result which is you know indices zero one two three four five and six um then we sort this array in increasing order after that we have um two then three then five seven 11 13 and 7 and this is 0 1 2 3 4 5 and six um next um we can delete that say tech now q has this indices 0 one two three four five six after this loop we enter this second loop uh we pull you know we are at the position of zero right here into that you know tag and right here right we got two at i into that deck and we insert 2 at we pull 0 from the head of that queue and we insert at the position of 0 2 which is right here then we increment then we need to move the next element to the bottom right which is right here we pull this element from the head of the queue the next element which is one and we offer that element we add that element to that end right here then we increment i by one we are here we got three right here then um we pull 2 we insert at 2 3 then we update this position we got three right here we increment i by one we got five then uh we got at four we got five right here five we got five right here okay right here then we pull this five we update this position of that index we increment i by one we got seven then we say at six we got seven means right here seven then we update one which is right here uh we increment i by one we are at 11 at four which is eleven uh right here then we pull uh 3 which is uh you know we got 11 at 3 and we have we need to update five and we increment i by one we are at five which is 13 we pull one and at one we insert 13 right third thing and um let's say yeah then we reveal five and we are five again and at six we got seventeen uh we pull this five which is 17 at five and finally we have nothing to offer because this uh cue is empty and we are done you know that's it finally we return this final answer which is 2 13 3 11 5 17 and 7. you guys for watching leave your comments below i want to know what you think follow me on social medias on instagram add me on snapchat um give me a big thumbs up to support my channel and i'll see you next time have a nice day bye
|
Reveal Cards In Increasing Order
|
x-of-a-kind-in-a-deck-of-cards
|
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`.
You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.
You will do the following steps repeatedly until all cards are revealed:
1. Take the top card of the deck, reveal it, and take it out of the deck.
2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.
3. If there are still unrevealed cards, go back to step 1. Otherwise, stop.
Return _an ordering of the deck that would reveal the cards in increasing order_.
**Note** that the first entry in the answer is considered to be the top of the deck.
**Example 1:**
**Input:** deck = \[17,13,11,2,3,5,7\]
**Output:** \[2,13,3,11,5,17,7\]
**Explanation:**
We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it.
After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\].
We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\].
We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\].
We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\].
We reveal 11, and move 17 to the bottom. The deck is now \[13,17\].
We reveal 13, and move 17 to the bottom. The deck is now \[17\].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.
**Example 2:**
**Input:** deck = \[1,1000\]
**Output:** \[1,1000\]
**Constraints:**
* `1 <= deck.length <= 1000`
* `1 <= deck[i] <= 106`
* All the values of `deck` are **unique**.
| null |
Array,Hash Table,Math,Counting,Number Theory
|
Easy
| null |
486 |
hello everyone so today's problem in the predict the winner okay so here you are given an integer array norms and two players are playing a game with this Adder player one and player 2. and player one will start first both players play optimally and both let's start the game with a score of zero at each turn the player takes one of the number from either end of the array again it can uh take the number from first index or this last index okay so which will reduce the size of the array by one the player adds the student number to the S4 the game ends then there are no more element in the array so you have to return two if player one can be in the game otherwise it will you have to return false okay you have to give one thing in mind that if there is equal then also player one will win and imagine that so here on array is given and let's suppose player one will start first so it can take either it will take uh one or okay so which is the maximum for it will take uh that element okay so let's see the example like one five and two so if player one will take one then for player two five and two will remember okay and player 2 can choose any one of these two elements so and let's suppose if player 2 will choose five so now player have only on one option he can choose only two okay so player one have one plus two and player two is five so you can see here one plus two that is 3 and less than five so player one will never win and if suppose player one will choose first two screw up player two has two option one and five then also will player two will choose uh five so in either both of the cases player one will lose this match so you can think like uh you can choose okay which is the maximum okay so if one will be the maximum or two will be the maximum which is the maximum you will choose okay so this will not correct why I am giving you an example here like if the 1 5 and let's suppose to keep I'm sorry two three and seven is there okay so you will think readily like okay which is the maximum either of the end of its index you can choose okay so one and seven so we will choose seven okay so now for uh for player two it is the range so layer 2 will choose okay two three you know player has the one and five option so player one will choose five and now player two will choose only one has option so it will choose one so here you can see that player 2 has 234 score okay but player one has only 12 score so here you will say that okay player one will never win this match but it's not correct let's see how so let's suppose one five two three and seven is uh here so okay so you can think like okay player one will choose one so player two has the option of file two three and seven okay so player two choose can five or seven so let's suppose player two choose seven okay and player one has that one so now player has the option of five and two three so player uh one can choose two three and now player two has only one option that is five so you can see here player one will win this match okay so that's why you can't uh use the gradient algorithm here so that's why you have to use the DP here okay so let's see the code here you can use the DP put it on find nums and first Builder range will be the from 0 to n minus 1. and pass the first write only the person then I will memorize it will find and if idx1 the base case if idx will be the greater than ID X2 then we will return 0 and then okay idx1 or idx2 so the player one has the two options either you can choose from idx1 so index either you can choose from IPS to index okay so first assume that it will change from idx1 and then she had to uh he had a difference take the difference from the uh its next player so let's suppose player 2 has the difference of X okay if so you can see the player one has the difference of minus X where you can see here if player one has the score code and player 2 has a score of 2 then for player 2 what is the difference so you can see here by the example okay so now it's clear that if layer 2 has the difference of X then player one has the difference of minus six and if you can add the add this nums IDs one to score of player one then it will increase the differences okay so let's see here to init A1 equal to if you have to add this number to S4 of player one two and the difference of player 2 has a 5 and if you are taking idx1 then for player 2 has the option from idx one plus one to idx oh is the difference of player so the player one has a difference of minus of this and you just have to add this number to the score of appear one so it is the difference between player one and player 2. and if you are tickling let's suppose from the last of the uh this vector so what will be the range for player to remove the range and you just have to return Max of A1 A2 so let's see so white giving wrong answer okay so here you have to see that if it is greater than zero or not okay or equal so now it should be accepted let's see okay password test case let's submit it although it's accepted but you can use here DB also okay yeah you can see constant uh it is very less so it's accepted otherwise it will not so what you can do better and in DP okay and here path argument of DP here you have to memorize idx1 and idx2 okay and if DB of idx1 and idx2 is equal to not minus 1 then you already store the answer in this DP you just have to return this is accepted
|
Predict the Winner
|
predict-the-winner
|
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` or `nums[nums.length - 1]`) which reduces the size of the array by `1`. The player adds the chosen number to their score. The game ends when there are no more elements in the array.
Return `true` if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return `true`. You may assume that both players are playing optimally.
**Example 1:**
**Input:** nums = \[1,5,2\]
**Output:** false
**Explanation:** Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return false.
**Example 2:**
**Input:** nums = \[1,5,233,7\]
**Output:** true
**Explanation:** Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
**Constraints:**
* `1 <= nums.length <= 20`
* `0 <= nums[i] <= 107`
| null |
Array,Math,Dynamic Programming,Recursion,Game Theory
|
Medium
|
464
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.