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 |
---|---|---|---|---|---|---|---|---|
118 |
I have work Compact Zeta Monica Today When stored for Pascal day will germinate single and Twin birth number of errors that are you want to go Pascal tricorder Wat Temple the want to exert ourselves in garment and number Live Show me what purpose language phytic goals and this is an example of strange events And you Lost the first goal is open Contest is single word you'd ever want to tell you the second hand to various spiritual about uses the first doubt you in a struggle away for the pier one and weep icecream bar snacks group based on the First Love show our attention germination is number In just see some of the two number the rest will come base Tich season pass Cana for told put on islands and this for you to use the work will be aware of the one for you just leave with other things around property is want to be a Road Together We're one and spa travers exacting standards that knows were directly ever thought about in the last One We are one and Dad where are you want the code in the sport emotional caper Hill restaurant show you can Write Script One because Musical To The old Republic of Little What ever Want to Live with Sounds better with you later She is right i defend National Heartstrings National buddhist page goal is to the fall back to us work Harder of thinking ability because our website is Tomorrow is the best singles of the first goal is it Can Be our prayer My name is explore r&b love you How are you My name is explore r&b love you How are you My name is explore r&b love you How are you want And The One Dinh nexpro inspiration for you want to and Man EXID would Save The Way handspring Dragon Quest I want to want And now I wanna berman explore the voice pro plays out game Call of the faster You in this part please app about the life we've made some Of The people interact with Perfect kick Sugar in the condition of Wonder When the greater the one with reverted Back To Life is not in their prey show How I need you There are cold When is the way I would care instruments are you we experience can never seem to year-over-year Epic battles are seem to year-over-year Epic battles are seem to year-over-year Epic battles are over heels simily furnished with Someone with some methods are Over Here Waiting to me a little about the One Pieces of War in the Space speakers She noticed The Beginning and the end of this allows day We skinna match is the first with me tell you why it's own pace with content aware of rivers were collected stunted is Used At The Beginning of and realistic and the best and disk in America with so much is it me see you Shout Soobin weather for tourists when i can feel about you for all the first sport in this well now how obacana compute for small value We have to work and play well as the first value and this is where of size free size fibrate acetic malware excites find our prayer want to personal you want to say about What makes us some of the two values of the Divine of the two values of the Divine of the two values of the Divine disciplinary reports were added to Guess what is one in the first sport next month We not to be you every day set and response to be and the export and number and read about is the first single eyelids Girls and results exhilarate Musical picture that makes and there Over Here are the world and takes about this problem is really want What's her and to click If the main Story speaks and valid synnex would have one purpose and another person of here to force One punch industry and sport nextgen supported gansel cupid's one and You're something which I want and defend against the one for ourselves and one of accounts that I will start your scars are allowed to see you will notice we want free one and indirectly nestled written in which occurs in the US with parapa makers aware of family entry of stages and to the Speed and support Michael clayton to the Speed and support Michael clayton to the Speed and support Michael clayton explore the flow of fire ghosts plates and is pogorelov ashkan dejagah you think and users are Turning and the previous work and Ethiopian g.na Gold previous work and Ethiopian g.na Gold previous work and Ethiopian g.na Gold now the dentist ADC Super respects the most personal guard your time What i don't go and wet and its part number of ground array shinji Musical ability of all your love and the fires gokart size of to end the event and serve and went to type of person in the world is spacious with me if you work hours as just could happen last weekend has been together now Parkinson Outlast accordionist unep resort and concise format a How does It's Over have recently been everywhere Winner the perfect with spices easy Cash flow of value Which is one and what you work of avarice Core 2 Dual port in a strange number is my next One People very well prepared and when it 's you It's safe work All Day And Rain 's you It's safe work All Day And Rain 's you It's safe work All Day And Rain and passwords and improvement nextgcal Town is next row canopy Toyota previa Slow Waltz previous Global offensive jokes are established and resort which one is the moon and back to bed and People want of reporting and supporting moncceau number Secret the one I used to wish list of that love would take Over Flowers which will spend the rest of any other One you are you today and the Best And The Beginning of play all We Know in the face on the screen is Used with complete with this Hurt When doing is a Popin In You awareness mind modified to work with your way to be a gentleman stupid templation of best time to work together worked modified developer the us whitening us your time with me and returning natas and one of duty pingnet Gold Dragon Riders in the second work Westlife and well and now unlicensed product of quests and water wandering Lost there and requests will pentozo World War Vienna passwork and stamp of prayer and time of There was one of your personal assistant Super magical Battle Arena you can use of tabs and Words I never want is celebrated It's What You're Black Ice wine load in drawing explanation show once in a good is the skin I have to grow the work and travel guard take is intended to the resort and demand of Westminster cold War head and recurrent live show How to demonstrate the world's end the ball From The Stars and You can see the Switch is very sweet home to weapon shop want Please like and Subscribe and support all our hope for simplicity and passwords
|
Pascal's Triangle
|
pascals-triangle
|
Given an integer `numRows`, return the first numRows of **Pascal's triangle**.
In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown:
**Example 1:**
**Input:** numRows = 5
**Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\]
**Example 2:**
**Input:** numRows = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= numRows <= 30`
| null |
Array,Dynamic Programming
|
Easy
|
119
|
312 |
hey what's up guys John here so today let's talk about this like another list called problem number 312 burst balloons this is like another thing classic TP problem dynamic programming so let's take a look you're given like a array of balloons and each balloon have it has a value on it and you can burst any balloons so when every time when you burst up along you get coins so the way you get coins is the left of the balloon you cuber state times the current balloons value and times the right sides value right so basically if you'll burst for example if a person won you got a coins right what's the coin left times current times right and after bursting up along those basically this button will be removed and this array will become three five and eight right and then you can choose any of them to be able to pull to burst I'd say for example we purchase five right and then we got we get three times five times eight right and then we'll be adding like two boundary belongs at each end basically why because when we purge the last the blasts belong there's no left and right but we still want to get some coins right based on the coin the balloon itself so that's why we need an one on each side and in the end we got a total and then you need to write a program to get the maximum basically you need to find a way about how to burst what sequence super in what sequence we should burst this balloons so that we can have the most coins out of it right so what should we do right I mean I think first right so we need to do like I write a DP function DP formula right or TP function whatever you want to call it basically let's assume we have a dpi entry right so what does dpi J means TPI J means he goes to from I and J from belong right from balloon from I to J yeah we ready burst right burst from I to J maximum coins right so T pIJ means if we burst the balloons from I to J no matter how they burst it the Mexico the maximum coins we can get will be that value in the DP IJ right and then the problem comes down how can we calculate D P IJ right and let's say we have a dpi J's three one five six right I mean we can loop through basically we need to try each of the possible possibilities here right let say we purse three and five one and five and eight and then we get them the most the maximum from all the positive possibilities right but what does solution work right no why because if we if K let's say we have a k right let's say K send for reverse number k case index balloon first right let's see we reverse that one first and then but the problem is that once we were starting the structure of this array code change right now the neighbors of 3 becomes 2 5 all right it's not 1 so if we just keep bursting choosing the K to be the first one to burst and then there's its if there's no way we can track the neighbors basically right that the values will the neighbors of 3 and file they're out they all got change so how can we solve this problem right instead of using K to be the first one to burst we can use K we should use care to indicate the last up balloon to burst right so how does that work then let's say we have a I n train right balloon i and j right so we have a balloon and from I to J I'd say we have a we choose K right let's see we have a k right in the middle here so k is the one large the last two first right if a case the last of burst basically when wouldn't K was burst the balloon from I to J they're all they were all bursted until except for it for k right then what's the VAT then what's the value of this of the K you when the cake outburst right it's gonna be a noms right so first right so firstly the cake fight okay itself right and then what and then we need the times the left side because remember at this moment I and Jade they're all gone right until except for K so it's gonna be that it's gonna be I minus one here right and J plus 1 right so then when we burst K the value the coins we get by bursting K will be the num nums K times numbs right what I'm I minus 1 right and times J plus 1 right that's the coins we got by bursting k ID in the end right okay and then what and then dia okay so that's the person of K right and then once we have K here then we have the left and right side right then what's the left side is the DP what I sorry the left side is the buddies it means by bursting everything right from I to K minus 1 right k minus 1 that's the DP that's the value of the maximum coins we can get from the left side remember the DP means the first from I to J maximum we get a maximum coins right so on the left side start how about the right side DP k plus + how about the right side DP k plus + how about the right side DP k plus + 1 + 1 + 2 J right so that's the left 1 + 1 + 2 J right so that's the left 1 + 1 + 2 J right so that's the left side of the K the maximum coins we can get from the left side of K and then that's the coins we can get from the right side of K right and then in the end we just up some rice these three this one two and three basically 1 + 2 + 2 + 2 plus three that will be the final answer right and that's for the four answer for the answer of K and for K we need to loop through I to J right with I to J we need to pick all the possible possibilities of the K then we get the maximum out from often and then in the end we'll be having a DP write DP what I think it's a 0 2 and minus 1 right 0 and minus 1 means from 0 to the last one that's our the fact that's the value basically bursting other balloons from the first one to the last one then what's the value of that right ok so with this like formula of TP 1 plus 2 Plus 3 let's try to call this problem ok so first let's add this these two boundary numbers to the array first right because we need those to boundary arrays for us to get our DP s and R in our calculation we need those numbers for us let's see so that's gonna be a numbers right so we just add one more and class right numbers plus 1 right that's how we add those two boundaries and then we're gonna have an end now we haven't numbers here right and then we're gonna create our two to the array DP at the beginning the coins are initialized to be 0 and for in range and right so now since you know we already have this one right we have this one three one five eight and one right but we only want to loop out these numbers right for the privet the first one last one we ignore it because we don't want to pop those things right that's how we I'll keep it here right that's why we have this like this is zero right that's the so now this is it to zero right and this is the minus one right how I put those there's a diagram here so you can see it better and so since we're doing the from I to J so I will be true traversing from the bottom right from the right side so I can do i equals to J otherwise I need to do a j @ ej j TP j i since i'm i wanted do a j @ ej j TP j i since i'm i wanted do a j @ ej j TP j i since i'm i wanted to a TP IJ so I'm gonna do a 4i range right so basically we'll be moving from right to the labs that's our first I right that's our starting point basically so what's gonna be out the first starting point it's gonna be 8 right so what's the 8 and minus 2 right and then we're gonna change word to a reverse so it's gonna be done - reverse so it's gonna be done - reverse so it's gonna be done - - to establish - 1 but we don't stop by - to establish - 1 but we don't stop by - to establish - 1 but we don't stop by - when we stop from 0 right because we - when we stop from 0 right because we - when we stop from 0 right because we don't stop at 3 not 1 but if we put a minus 1 here we're gonna stop from 1 but in this case we wanna stop from 3 which will be 0 right how about J here right the J is the from I right first is from hi and how about the end the N is n minus 1 right so because that's the exclusive so basically it will stop from beer that's the end that's our end all right and then we will have a third for loop for K right so what is the K for K in range what I - 2 J plus 1 right range what I - 2 J plus 1 right range what I - 2 J plus 1 right basically that's other Possible's basically we can will pump through treadle burst try all the possibilities from i to j right we try that we try K to be burst at the last right and then we have a DPI J here right IJ you know so well it comes to what we have max right because since we're doing the every time we do a max since we try all the possible possibilities from i to j so IJ what's the second one second wise first we burst j the last right so what's the weather gonna be that's the Nam's right hey burst k at last right and then it just K where K minus 1 when it comes to number here so I think this is the 0 and minus 1 that's yeah I think it should be okay because at this moment since the numbers we already changing the numbers of atoms now so I'd so right now this is number here this is number with one with two more elements here so at this moment the K means the correct numbers we need right so Caicos and then what I - went right so Caicos and then what I - went right so Caicos and then what I - went right that's the left one after we bursting all the balloons from I to J right when we burst the last one the K times what nom noms right J plus 1 right so that's the coins we get by bursting the last K and then we need to get the left side right that's going to be the left side out of K that's if you're gonna be the DP from I to K minus 1 right class what plus DP the right side that's gonna be k plus 1 J right and in the end we return what we return the vitals from here to here right that's going to be returned from DP 1 2 and minus 2 right so that's the range we want right that's our actual range let's run it cool yeah finally works all right okay so yeah so I think that the concept the key idea on this problem is that well every time we have iron J here right I read we have iron J we get K we try each possible positions of K in the range of I and J and the case means the last balloon to burst and then the last one we saw the movie lappers the last balloon the coins we get will be the current values right times that the left out of I because at this moment both I and J that they were all per state left half I and the right of J plus the left side max coins plus the right side after man the max corn and then which for each of the K we keep track of the maximum value out of them and in the end we just return this cool I think all right I think that's it for this problem all right thank you so much for watching the video and okay I will be seeing you guys soon bye
|
Burst Balloons
|
burst-balloons
|
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons.
If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it.
Return _the maximum coins you can collect by bursting the balloons wisely_.
**Example 1:**
**Input:** nums = \[3,1,5,8\]
**Output:** 167
**Explanation:**
nums = \[3,1,5,8\] --> \[3,5,8\] --> \[3,8\] --> \[8\] --> \[\]
coins = 3\*1\*5 + 3\*5\*8 + 1\*3\*8 + 1\*8\*1 = 167
**Example 2:**
**Input:** nums = \[1,5\]
**Output:** 10
**Constraints:**
* `n == nums.length`
* `1 <= n <= 300`
* `0 <= nums[i] <= 100`
| null |
Array,Dynamic Programming
|
Hard
|
1042
|
1,318 |
My Tab 20 Channel I am and today date just went to you and also equal to see that let's train to see this question on see that let's train to see this question on see that let's train to see this question on this day Kajal song and question is alliance positive numbers A B & C is alliance positive numbers A B & C is alliance positive numbers A B & C Retention Minimum Balance Required In Summits of eggs pay to make egg and biblical 264 operation only change any single bed 2020 change from 0001 gheet message to this is more or file and seriously to eyes you to-do list bluetooth you ahmednagar spoon is very romantic and If it is Shankh Wagh then we are like this, I don't understand if anyone is okay and it will remain and we have to get the being rude done and tell us the minimum number of chillies is 1 or even MS loop should be done so that our and its college goes to CTAE college, so this is our whole question. You try it please set the shopping that now I am going to do the sorry sentence of it okay so to understand this we have to understand and what is the meaning of operation when we start Kuru and then it definitely comes. When we true and false, our cents come through, we start and then our results come again, we fall and fold, if we pay attention then every wound is there, okay then look, it is good, okay Sunil Singh Jhala's that China is ours so this is what I set here what do we have to do and saw through if I keep the coin Gurjar unity goodwill life live dedicate to what is 0105 what is 108 66 that is 1030 E 1 minute half from now If you look at the hours then see the website and it is not 3000 but if I cut this and this one which is 2050 this is one of these then whatever one pin has to be set it is fine for that so this is fine from here this is also fine by default so here See here that A is new here, open it for 1 minute and see this 5864 plus two Have to see if this is Calibrated Satanic it is absolutely set which is vast in the answer and look here any one of Indore is one minute then we will ask which one anywhere else and what is the result of this, the same thing will be there in this piece too, okay If it is okay to live with someone when the lower butt is set and the upper two patterns are set, then what will we have to do, we will have to set one of them in Indore. We are here if it ever happens that both the upper feet are set. Have and the button below is set, okay, so what do we have to do and we have to turn off both of them, okay, we have to turn off both of them, we have to clock off, like collect, basically the saying is that look, which we are better, which we meet, resulting son unit certificate. Which is basically what is better in C, okay if it is set, then there should be one website, okay, so there is only one case that if there is no other selling eye acid, this one is bent and gift, after minutes the alarm is set. Add plus one in the answer, it's fine, but if the result is set in these buttons, then both of them are 59, then if any of these alarms are set then it will be Kanchan for any one or there will be no doubt, then nothing will have to be done. Because see because zero in something all three condition score is neither and point to and stop makes tattoo and cholesterol makes power to do okay because of this if there will be any shatter and by the way it will not make any difference to us simply forward on our channel Some ads will increase, there are no ads, okay, if it is as per our settings, milkshake, then we will serve the information simply, okay, if rotting is stopped by hormones, then there is ego, then two things happen, either it is sexual, still any of these websites. Annie Besant Okay, this means only one is ISBT, the other is by Additional Chief or Ad BJP, both will set 63 boss website owners, this will be the end of this mission, according to both of BJP, in this condition either one, we want result but If any one of ours comes, we will have to click on it, so if it is ineligible, it will be belt set, okay, if any one, then we will do it in the cost, if about both, okay, we will have to do both, so if egg Subscribe if you want anything else then it has completely looted us we will do it daily beet loss sugar 100 people ok so now we see it in the court ok and in the court we think how to women it so now we are bread and here When we open it, first of all we are there, first of all, develop the exam and yes sir, we will add it to it, okay, now this point I 2205 132 This is not imaginary Kulbhushan Duggal says, so see, if we click, then yes. Tell me, this festival, what does it mean, I am doing it, similarly, BJP Chief, what does this mean, we will check the same, okay, then this is our loot, we have been robbed of the letter, okay, and this grade is zero, if If there is more, then we start from here, so similarly, all the school or sales that we have to fold are the weight part of this rectangle, FB and in the midnight children, we are the chief of that to-do list children, we are the chief of that to-do list children, we are the chief of that to-do list and from here also. We will start from here, now we will turn on the gas and tell me, show it to someone in the house. 13 Now we will tell this Schezwan, basically this was the pin code or the fire brigade of the other is set, so see this, ah, so that you have got this Lodhi community of mine. If it is fine in this channel then it's ok now tension or if your story was told then keep it in such condition and to CR 66 if you have confirmed from here meanwhile center what will we do we will do there will be a question in this festival this answer sheet Have given this note egg and not given that brinjal which is so call them then answer administration will do that we have fronted any one of them is okay this number will do the condition okay answer follicles and will check that to officer answer If it is so, then these conditions were completely absent in Dhaka Tigaon that the trees were intact and we all got positive, then what to do at that time, this is also MS Word, how many rupees for this festival, if both of them are set, the answer is declared as completely inappropriate. If there is a specific York, then they have to set one and show two, so some work is fine, it is somewhere else Chief, if any of the three is set, then the answer is to arrest. Okay, and now we will have it done. Who are you? Simply answer. I will give here, it is not surprising that this is another thing that it is not equal to Bhuj city because it is possible that if the contact is reached, then loot was selected and he is the chairman of the committee. Play candy crush Raghavan, so this is our happy inside, it is fine, its not developed. That I will tell you how I will check it is okay and pigmentation will go to 5330 if you were three do the great salute then basically this will give you the minimum balance of the entire portion to make egg and also someone will ask minute and you understand the question end electronics films had left the cigarette do two jhal
|
Minimum Flips to Make a OR b Equal to c
|
tournament-winners
|
Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation).
Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
**Example 1:**
**Input:** a = 2, b = 6, c = 5
**Output:** 3
**Explanation:** After flips a = 1 , b = 4 , c = 5 such that (`a` OR `b` == `c`)
**Example 2:**
**Input:** a = 4, b = 2, c = 7
**Output:** 1
**Example 3:**
**Input:** a = 1, b = 2, c = 3
**Output:** 0
**Constraints:**
* `1 <= a <= 10^9`
* `1 <= b <= 10^9`
* `1 <= c <= 10^9`
| null |
Database
|
Hard
| null |
133 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem clone graph so we're given a reference to a node that is in a connected undirected graph so it's convenient for us that the graph is completely connected and all we want to do is return a deep copy of that graph in other words a clone of that graph and for every single node we have two things we are given a value and we're also given a list of its neighbors so this is what's telling us you know how the graph happens to be connected these are the edges in our graph now if you're not super familiar with what a deep copy is so let's say that this is our example our input graph we're not just going to create a shallow copy meaning like this is the exact same graph like the color is yellow for both of these meaning like it's the exact same graph we didn't actually create a clone of it so this is not what we're looking for this is also not what we're looking for so this is a new graph because the color is slightly different but you see that the values aren't exactly how they're supposed to be we have a 3 here whereas we have a 2 in the original graph right so basically we have these two's values mixed up so that's not what we want either we want an exact clone so it has the exact same structure and values right the values and structure is the exact same and this happens to be a new graph this is not the exact same graph as this one because this one is blue whereas this one is yellow so how are we going to solve this problem well you can see i'm going to use a hash map like pretty much every graph problem and we're going to use depth for a search where you can also use breadth first search if you want but let me show you the general algorithm so you can see these edges are undirected meaning you know if one has a neighbor two well two is also going to have a neighbor 1 in its neighbor list so let's say that 1 is our entry point in the graph what are we going to do you can see initially our hash map is empty what we're going to try to do is map the old nodes to the new nodes or the copy nodes so we start at one so what's the first thing we should do well obviously we should create a copy of this node that's what i'm gonna do so create a copy of one now this copy of one is not complete yet right because take a look at the original one it has two neighbors three and two so what can i do we know we're gonna have two neighbors for node one right can i just take these two original nodes and then put them over here three and two no i can't do that because for these nodes three and two we actually have to create copies of them as well so you can see that this is gonna be recursive so first thing i'm gonna do is i'm gonna go to its first neighbor which let's just say it happens to be two in this case right so i'm gonna now i'm gonna start cloning starting at two so we're at two we're gonna create a clone of two oh and by the way before i forget before we make a clone of two we know we just created a clone for one so what are we gonna do we're gonna map the original node one to its now clone node once we're mapping the old node to the new node and i'm going to show you why we're doing that in a second so now we're going to go to node 2 right and we're going to create a clone of node 2. so let's create that clone node 2. we're also going to add it to our hashmap right we're mapping the old node 2 to its clone so the clone in blue is the new node so now we've cloned one and we've cloned two and for two now let's look at two's neighbors well look you can see that it has a neighbor of one right and it has a neighbor of four so first we're gonna end up trying to do is create a clone for two because we know that we have to in the list of neighbors for two we have to add the clone one which we haven't done yet so what we're gonna end up doing is we're gonna try to clone one but we're gonna see in our hash map look we already ended up cloning one so basically what i'm saying is now we can say okay we can add this edge that two is connected to one that two has a neighbor that happens to be one and basically the reason i'm doing that is because we know this edge is going to be undirected it goes both ways so that's what i'm trying to do here so now we know that 2 is connected to 1 we also know we have to clone node 4. so now we're going to visit position 4. let's create a clone for 4 so let's add it to our hash map as well we're mapping the original node 4 to its clone so now we're at the node 4. we want to clone 4's neighbors first you see that 4 has a neighbor 2 which we already cloned so we're going to take this original node 4 right we know the original node 4 has a as an original neighbor of 2 so then we're going to take that 2 look it up in our hash map see okay we already created a clone of it and this is the clone and then we're gonna end up taking four and connecting it to two and let's just say that you know when we created the node four we ended up connecting two to four so let's just make this edge go both ways because we know that originally the edges are undirected so now that we've for four we wanted to create a clone of two we also want to create a clone of its second neighbor three so now let's create a clone of three so we know that four is going to be able to connect to this neighbor of three so we're creating a clone for it and we're gonna take the original three node and map it to its new copy node of three so now we're almost done right you can see that all four of the nodes have been copied but for three we haven't added threes and neighbors right three isn't ended up connecting to any other nodes yet but we know in the original three has two neighbors the first neighbor is four so we're going to say okay we know that this 4 needs to have a clone but the good thing is we already created a clone for that node and this is the clone so now we have it so we're gonna take three and ah and connect it to four so we're gonna make this edge basically double directed and three also has another neighbor of one and so basically what we need to do is make a clone of that one but we look in our hash map first and we see we already cloned one this is the clone so we're gonna take three and connect it to one right but wait we have one last problem right this one should also be connected to the three right you're right and that's what we're doing recursively now so we originally started at one then we went to two then we went to four then we went to three now what we're going to end up doing is reversing that because we remember we're doing this recursively so we're gonna pop back up to four we're gonna see four has already cloned its neighbors three already cloned its neighbors we're gonna pop back to two already cloned its neighbors we're gonna pop back to one we ended up cloning the neighbor two right but we didn't end up going this way so from three now we're gonna end up checking okay did we already clone three let's look in our hash map yep we already did so this is the clone that we created so all we really need to do is make one connected to three so basically make this edge double directed so now you can see that we finally created a complete clone of the graph we did this in o of n time where n is basically the number of edges plus the number of vertices right the number of nodes plus the number of edges connecting them because we have to basically make a clone of each of these and with that being said now let's jump into the code so we remember that we only need a single data structure old to new which is a hash map mapping the old nodes to the new nodes and i'm going to implement this in depth first search and you can see that this function is nested in the outer function which just makes things easier meaning that this data structure doesn't need to be passed into every single function call but we do need to pass in everything every time the node that we're visiting so in depth first search we're going to pass in the node first thing we're going to check is if the node is in our hashmap if it is in our hashmap then that means we already made a clone of it if we already made a clone of it then i'm just going to return that clone we don't need to create another clone so if it exists return the new node so if this statement doesn't execute that means a clone doesn't already exist so let's create that clone i guess i'll call it a copy so we're going to create a copy of this node so we're going to use the node constructor and the value we're going to give it is the value of this original node and we're also going to take that copy and then add it to our old to new hash map so old to new so the old node is just node and the new node is the copy so we're mapping the old node to the copy and then we want to make copies of every single neighbor of the original node so node.neighbors node.neighbors node.neighbors let's go through every single neighbor and let's run depth first search on that neighbor for the and so basically if we run debt for search on that neighbor what it's going to do is it's going to return the copy that we end up creating and with that copy what am i going to do i'm going to take this old node or this new node the copy that we made and i'm going to take its list of neighbors and i'm going to append to that list of neighbors this uh the return statement from this debt first search call so let's copy and paste that in here so that's all i really need to do depth first search and add it to the neighbors of this copy that we just made and once we're done making all the copies of the neighbors then we can return the copy that we just made in the current function call and it's actually that simple because even though this is called that first search it might even be better to call this function clone because cloning is basically what we're doing we're taking the original node and creating a clone of that node and we're cloning all of its neighbors recursively that's what this recursive call is right and then to the neighbors that we're creating we're adding them or appending them to the list of neighbors of this node and so it's actually the last thing to do is easier than you would think we're going to call debt for search passing in the original node that we're given in the original function call and then we're just going to return the result of that because that's going to give us the connected graph it doesn't really matter which node we return i think so any node that we end up returning is good after the entire clone has been made oh and one last thing we forgot to check one edge case the original node that we're given could be null so if the node is non-null then we're going to call is non-null then we're going to call is non-null then we're going to call this function return the result else if the node is null we'll just return null so with that being said this function should work and there you go it's pretty efficient even though this indication makes it seem like it's not i think if i ran it one more time it would probably be closer to like 50 or 60 percent but i hope this was helpful if you enjoyed please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
143 |
everyone today we're going to see reorder list which is a challenge problem for today this problem is absolute pressure for linked list you know it got all the techniques for list in terms of list you can have two pointers in terms of linked list you have reversing the linked list you have middle of the linked list and then a complex operation on top of the linked list it's an absolute treasure first to go into the problem we have one two three four and we need to reorder it to one four two three so when i see this problem at first if it is an interview what i would do is you know i would absolutely use two pointer and finish this problem so how would i do it is put all the elements which is all the nodes in this linked list i would put it in a list and i would make all the node next as none and then using two pointer i would move from one to four that would be the start point would be one end point would be four and i would append one two one dot next would be four and four dot next would be two and two dot next would be three so that is what i would do which is a two pointer approach to solve this problem so that is one way of doing it and we can try uh try to do that first so the in two pointer approach what we can do is the algorithm would be convert the node element append node elements in a list and then what you can do is make all the elements next as none then uh what we can do is this using two pointer first and last we can solve this problem okay so only thing is if the length of the linked list is odd then we need to find the middle so find the middle if the length of the linked list is odd and what can you do with what happens here is if it is even our algorithm our output would be one pointing to four and then it would point to two and then it would be pointing to three right and if it is even so what happens is uh one start to end and this would be the start and this would be the end so we can with this it would be solved with this step two three steps it would be solved but if it is odd what happens is we have this element which is which wouldn't be present in our two pointer because we will not uh equal equate both the start point and end point so this would be separate so we need to add this at the last so we would find the middle and we add the last element which would be the fourth because uh yeah first start point would be one five would be last in the next iterations start would be two last would be four and that's how our loop ends in two pointer so the last would be four and that would be pointing to the middle so for all we need to add step four so with this approach you can complete this problem right so first step is i'm going to find the middle because that's the best thing to do so if you don't know how to find the middle of linked list i've just uploaded a video you can check that out and come back to this so which will make sense so we'll have to point out going ahead till next dot next is there we can run the loop slow would be slow dot next and first would be two hops which is first to fix that next and your middle is nothing but your slow so we have found the middle and the next algorithm is append node element in list so we have a list a and head would be added to that element so while next is there for head which is the last element in the list you would have been we repent the next note okay and what we needed now is we just need to remove all the next in the particular array because we're going to change what's next for each of the node elements so i'm just going to make it none and now we have all the nodes in the list a so which is nothing but the first two steps we appended the node element in list and we make all the element next is none so now we will have two pointer so two pointer the start would start with uh start with zero and end would be your length of a minus one so while okay so what happens is your start you start should go next with the end so yeah start dot next is your end okay and then your end should connect to two right in the first attempt we should not do that so what we do is we'll have a variable last and if last is present so what would be our last is your f end would be your last so if n would be your last so last is a of end so if last is present then last start next is nothing but your next start okay so that's the algorithm so for two pointer you would increase the start and we would decrease the end okay and if length of the linked list is just odd what we need to do is the fourth step link list is all then connect the last dot next to the middle so loss dot next is your middle and then you return 0. so we found the middle so here we appended the yeah let's write it append element in the link in the list pin node element in the list and then here we are making the note next is none so using two pointer we are ordering the list okay let's run the code okay last start okay start is not there start and okay this works let's check for odd and even and then for single element yeah this works so i'm just going to keep solving it yeah it's accepted so this is one way of doing it this is just simple to point
|
Reorder List
|
reorder-list
|
You are given the head of a singly linked-list. The list can be represented as:
L0 -> L1 -> ... -> Ln - 1 -> Ln
_Reorder the list to be on the following form:_
L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ...
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[1,4,2,3\]
**Example 2:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,5,2,4,3\]
**Constraints:**
* The number of nodes in the list is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 1000`
| null |
Linked List,Two Pointers,Stack,Recursion
|
Medium
|
2216
|
823 |
hello everyone welcome to coderscamp and today we are going to cover another binary tree problem that is binary trees with factors so we are given an integer array and we have to written the number of binary trees we can make from the given values and the constraints given here is each non-leaf node's value should be is each non-leaf node's value should be is each non-leaf node's value should be equal to the product of its children so now let's understand this problem with an example so here is a given example and we are going to form binary tree with factors using this value so here the every value given is an individual binary tree so 2 4 5 and 10 individually forms each binary tree so now if you see 4 as the root node you can form a binary tree with two assets left and right children because it is given we can use this value any number of times so this is one binary tree and moving on to 5 doesn't have any divisibles here moving on to 10 if you say 10 is the root node and the values of 5 and 2 or otherwise 10 as the root node its left child is 2 and the right child is 5 both are agreed to be the binary tree with factors so if you see the left and right children's product is going to be the root notes value so in total we can form seven binary trees from the given value so how are we going to approach this problem so we are going to get the help of dynamic programming to determine how many trees can be formed using the given values so we are going to have two pointers i and j to scan the array and for every i we are going to check whether this number has the capacity of being the root element of the binary tree that is for example if we take two with two you can form one binary tree but there are no lesser elements than two so you cannot have its children so moving on to our next element 4 can be the root element because it has its factors 2 and 2 as its children so for every element we are going to check whether that element can be a root node by using that we are going to fill its corresponding dp array that is how many binary trees can be formed by keeping that element as the root node by after filling all the cells in the given array that is for every element how many trees can be formed we are going to send the sum of this array as a result that is the total number of trees can be formed before understanding the pattern of how we are going to fill our tp array i want us to understand why and how we are going to fill those values so here the pattern we gonna use is if we can form a tree with root node r then the number of trees that can be formed is equal to tp of its left children into dp of its right side consider we are having a node 40 and its children are four and ten so father these four is having children two and ten children is five and two so if you consider four alone using four as a root node you can form two trees that is four is the individual tree and four comma two as one more tree so you can form two trees the same way if you consider 10 alone you can form three trees that is 10 as a single tree and 10 five two as one tree and ten two five as another tree so you can form three trees so by having 40 as your root node you can form two into three six trees how so you can have 40 alone as a single tree or this is tree 1 and 40 with only children 4 and 10 as another tree this is 3 2 and here what we have showed is t three and we can swap five and two to make it three four and we can swap four and ten to make three five and further after swapping four and ten you can again swap two and five to make three six so you can form the product of how many trees formed by its left child into the product of how many trees formed by its right side so by using this technique we are going to fill in our dp array and arrive at our solution so let's start our problem by having two pointers j and i we are going to check for every i whether it can be a root element and j is going to scan the array from j to i so now our dp array is filled with once already because every value is an individual binary tree so already we can form one binary tree with the given values now starting from our second element four why second element because first element we have already filled one here in our first box and we cannot have further children for the number twos because it is the least or smallest element in the given array so starting from our second element we are going to check whether the previous elements in the array that is the values before 4 are dividing the 4 why dividing the 4 because we are going to construct a binary tree with factors if we can multiply and bring a value then we also can divide that value by the factors so now i'm going to check 4 by 2 gives the reminder 0 yes it gives the remainder 0 so 2 is a factor of 4. in this case we can form a tree with root node 4 and its left child as 2. so now we are going to search our right side so how do we search our right child if these two number gives the product of the root element then dividing the root element by one value gives the other that is if x into y gives us the root value then y is equal to r by x by using the same thing we are going to find our right element so now 4 by 2 is going to be 2 again we are going to check whether our array is having the value 2 yes array is having the value 2 as we can use the values any number of times by the problem statement we can have 2 as the right children so now we have constructed a tree by having 4 as our root value so it's time to fill our dp array at position 1 because this is the position of 4 here in the given array so already it is having value 1 we are going to add another tree that we have formed to that position so as i said it should be the product of how many trees we can form from its children so here the both left and right child is two so by two we can form only one tree so one into one is going to give you one tree so already one value is there we are going to put plus one so updating the value of four as the root element it can form two trees now that we have updated the number of trees can be formed using value 4 moving our pointer i to 5 so 5 is a prime number it should have 1 in the array but array 1 i doesn't have 1 and also the numbers less than 5 given in the array are not factors of 5 so in this case you can form only one binary tree by using 5 so still we are having the value 1 in the place of 5 and moving our pointer to 10. so now checking whether the elements before 10 in the given array are factors of 10. so starting from 2 we are going to divide 10 by 2 and the remainder is 0. so now we clearly can say 2 is a factor of 10 so consider 10 as the root node and 2 as its left child so now we are going to check its right child that is 10 by 2 is going to be 5 we are going to check whether 5 is present in the given array yes 5 is present in the given array so phi can be its right child and it can form a binary tree so as i said it is going to be the product of dp of its left and right side so now the left child is 2 so the trees can be formed using 2 is 1 also by 5 also 1 so 1 into 1 is going to be 1 so far we have one binary tree already present by using the value 10 so adding one more one to the position updating there can be two trees formed by using 10 so now we have checked with two now it's time to check with 4 we are going to check 10 divided by 4 gives us 0 no it is not equal to 0 4 is not a factor of 10 so moving our pointer j to 5. so now checking 10 modulo 5 is equal to 0 yes it is equal to 0 so 5 is a factor of 10 so we can form a binary tree with root node 10 and 5 as its left chart now time to find its right shell it's 10 by 2 whether we are whether 2 is present in the given away yes it is present in the given array so it can form a tree so now product of left and right side so the product of left child is 1 and product of right child is also 1 so 1 into 1 is equal to 1 already 2 is present in the cell so we are going to add one more tree along with the two now we completed iterating our array with last value and our dp array is updated so now it's time to calculate the total number of trees that can be formed with the given values the sum of this dp array so the sum is equal to seven so overall seven trees can be formed from the given array with factors so this algorithm works in big go of n square as we have two pointers i and j to loop through the given array twice so now let's get into the code as every time we're gonna compare the lesser elements alone i'm gonna sort my given array so once that started sorted i'm gonna declare my tp where it is given the answers may be too large so the answer modulo 10 power 9 plus 7 so as the values can be larger i am going to declare my dp array as long so once all that is done i'm gonna have a map which is gonna help me to get the index of my left and right child easily or search for whether my right side is present in the given array or not to search it in constant time i'm gonna have a map and i'm gonna save all the values with its corresponding indexes so now our dp array is ready our map is ready to search for the indexes so now let's have two loops to have our pointers i and j is less than i because it light right till where our eye pointer is i'm going to check every time our pointer i is going to be the root node and i'm going to check whether a of j i of j is going to be the left child so for that if its modular is equal to 0 then it is the factor of the root node then i'm gonna calculate my right value after calculating the right factor i'm gonna check if that is present in the given array or not if that is present then i'm gonna get the index of that and calculate my dp array that is my tp of left child into dp of right side so once i have updated i'm gonna add the values in my dp array and finally return the answer so now they have said our answer should be in modulo so we are going to declare one more variable in mod is nothing but 10 power 7 10 power 9 plus 7 so wherever we save the value we are going to do a mod so here we are updating our tp so overall value percentage mode same way we have calculated our answer so finally before returning i'm gonna do a mod and our answer should be in we have declared our answer is long so converting it into end before returning the value so let's run so yes let's submit yes the solution is accepted and thanks for watching the video if you like the video hit like and subscribe thank you
|
Binary Trees With Factors
|
split-array-with-same-average
|
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
Return _the number of binary trees we can make_. The answer may be too large so return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[2,4\]
**Output:** 3
**Explanation:** We can make these trees: `[2], [4], [4, 2, 2]`
**Example 2:**
**Input:** arr = \[2,4,5,10\]
**Output:** 7
**Explanation:** We can make these trees: `[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]`.
**Constraints:**
* `1 <= arr.length <= 1000`
* `2 <= arr[i] <= 109`
* All the values of `arr` are **unique**.
| null |
Array,Math,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
|
2162
|
766 |
766 Mentos pullets matrix and I'm fired to not say that way but a matrix is tablets if every diagonal from left top left to bottom white has the same element now given M times n matrix return true if and only if the matrix is to blitz okay I mean I think that's fine do I want to use Python I guess I've been practice in Python I could use a language of someone really request it well it's a language that I know but actually you see buzz but just because I like to indexing a little bit better on dealing with stuff like matrices but okay which one is which to check so then it's true by default okay yeah I mean I guess I didn't really talk about this farm before I drove into it because for Yeezys I generate don't I mean I guess that's not always true but it's for this one I think it's just literally implemented directly and you just kind of start with it how I'm thinking about it just talk with each matrix on the top row and then just like walk through it using some mod functions and stuff like this to do negatives maybe I didn't consider that huh okay but I still stopped in tableau and I took actually it would be like some wraparound type thing but I guess not and then I guess I was just start from top row and then the first column and then we just go both and I should handle all the cases I think so yeah mr. M no s n so we start and say why or yes I just take a rest n think yes they just blows yeah that's your okay if matrix of I started so I so the first element is not equal to the K 4 K plus I returned for us and we have to do some boundary check K plus I is less than M PI is just an end okay and now we just have to check first column and also 34 is true if you pass all the checks so I'm gonna check the first element twice but that's okay I mean we could actually change this one so now we want it to be my now we do i and it's two and then we actually just copy and paste a little bit not really because now we warn maybe I should have cut in pay so I could force myself to think about it you know we could just modify that but I think that's yeah okay now we want to look at this second the first whoa what the second well could first indexed well I make sure that's less then and capers mm-hm we started that's the first mm-hm we started that's the first mm-hm we started that's the first element in the world it's not to go to okay return for us okay I think it's just good enough maybe I mean one thing I try to keep in mind when I do problems like this as well I'm part like this I mean when I look at the output when it's binary like in this case is true for us I try to be a little bit more flow because you can get lucky in the sense that you get to right like it passes all your tests but it's still wrong because your testes are just not good enough and half the time it's going to be right or something like that but I think in this case it's probably okay is a much easier I mean this is a straightforward ish problem maybe now look this hints nice the only thing I could may think about is maybe I've been off by one in these edge cases but yeah this case I'm okay cool yeah I don't know if there's that much to be talked about for this problem I mean it's just like it wants you to yeah the problem wants you to basically go for the diagonals and you have to beat every element one so there's no like algorithmic layer which is M times n in time and no extra space other than like two variables but one extra space yeah and I've and then don't know if there's any weird tricky parts about this door with that being said I think I well I've always wanted to problems with this stuff in the past where I have like weird or PI ones I think with these just try to keep it as you know was it cool keep it stupid symbol and just do like the most basic thing of simulation that you can think of I think another way I could win this to be given query it's just started with well one is probably just a better variable names to be honest I apply could have done better than I and K I could name just this cases column and this as well and so forth and vice-versa so that it could forth and vice-versa so that it could forth and vice-versa so that it could understanding a little bit easier especially when you need to debug that comes in handy yeah oh I mean you just die ignore it just check to diagnose which you just have to check from the first one the first column okay cool oh yeah I mean I think these have simulation tests are pretty basic it's about 20 lines of code and feel like I've definitely seen maybe not this one but like random interview problems where people like some sort of simulation based on diagonals and like what money for matrix is so definitely I would consider this a problem that you could see on it until tests but yeah
|
Toeplitz Matrix
|
flatten-a-multilevel-doubly-linked-list
|
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._
A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements.
**Example 1:**
**Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\]
**Output:** true
**Explanation:**
In the above grid, the diagonals are:
"\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ".
In each diagonal all elements are the same, so the answer is True.
**Example 2:**
**Input:** matrix = \[\[1,2\],\[2,2\]\]
**Output:** false
**Explanation:**
The diagonal "\[1, 2\] " has different elements.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 20`
* `0 <= matrix[i][j] <= 99`
**Follow up:**
* What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
* What if the `matrix` is so large that you can only load up a partial row into the memory at once?
| null |
Linked List,Depth-First Search,Doubly-Linked List
|
Medium
|
114,1796
|
650 |
hello everyone so in this video let us talk about a problem from lead code it's a medium level problem the problem name is two keys keep okay so the problem goes like this that there is only one character a on the screen of a notepad and you can perform two types of operation on that particular notepad so the operations are copy all in which you can copy all the characters present on the screen no partial copies allowed so if let's say 5 is because there's only a allowed if the five phase you can copy all the five a okay if whatever number of a's are present on the screen at a particular moment of time you have to copy all of that next thing is paste so you can paste the character which you have copied in the last time okay whenever you've done a copy operation you have to use the same copy number of elements and you can paste them out multiple times whatever you can do but at a particular operation you can paste it one time then if you want to like increase the times of a you have to again copy all and then you have to copy all these and then you can paste them then given integer n that is the minimum number of operations can you tell us that is required to print a exactly n times so i hope you get the problem statement more clearly but let's take an example so let's say that you have to print a three times okay then how much is the number of operations you will be required come out of these two operations that will perform to print a three times on the screen now we will always start with a as one like one is typed actually because if there is no a then we cannot copy all base so we will always start with one a on the screen and uh n is equal to one so if we just want one a then we just don't have to do any operation because it is already present so let us check this out let us see that if we have three a's then we have to like what we actually have to do is that we have to first copy this state okay so one operation is done and then paste it out and paste it so what you can see is that we have done total of three operations that we have to do to print out three times of it but let's just take an example in which we have to print a five like let's say 10 times so if you want to print a let's say 10 times then what we can do is that we can first print out a five times okay let's say if i print a five times and then copy all the a's and just print a like just paste it so if you paste it will automatically paste a five times and we got it ten times okay so what you actually have to do is that you have to like divide it out and you have to see that okay if i'm dividing them out then we actually have to divide it like in the half at every moment of time no let's say that we have to print uh six times okay so whatever uh let's not six times let's say nine times so what i'll do is that i will first paste a three times and then what i'll do is that i will copy all the a's and then like paste it so if i paste it'll become a and now i have again one of like two of one of two of the operations i can either copy all of them or i can paste the last copied state so i've copied three okay three years so i can paste three is multiple times as much as i can okay so i can paste three a's and i can again paste three so until i copy whatever is the last time i've copied i can like reuse it so first i use one time copy so i can like use that one time copy two more times so i've used three is then again copy this whole straight out then again paste it out again okay so i've used the paste operation got it that's the overall idea here now how we can find out because we have always two operations like at two things at any point among your time when we have different decisions it's generally like uh and the constraints are small as you can see we have like we either we can do greedy or we can do db okay i generally type of i think of that and it is some sort of a tv problem as well i can like get a hint out of it so what we actually have to do is that we have to find out what is the minimum number of operations required to get a particular uh particular type of ace at a particular n what is the minimum number of operations so let's say dp of any eighth state is the minimum number of operations required to get i number of ways so okay you got the overall idea about what is the state here so let's say that we initialize with some base states that if my db is equal to one i required one so i you know for dp2 that if i require two things so i have to first copy down and then paste out so two for deep code three i required three and for four before we can actually start doing our somewhat magical thing the magical thing is that i can just take two a's and then just copy this out and just space down so two more is okay now like what is the actual problem in this now the actual problem turns out to be is that for any number let's say is let's say it is equal to 24 now to get to 24 what you'll actually have to do is that you have to somehow divide this number now you have two options let's say that's it like 24 is a multiple of let's say six as well and it is a multiple of four as well okay so either or let's say two as well and three as well now what i'm trying to explain here is that you can either let's say take six a's let's say if i just take six is i will not draw 24 a's but let's say if i draw this let's say if i draw six is one two three four five six three four six then i can take this six a copy this out and paste it four times so it will be like 6 12 18 24. okay this is one of the options or i can take go to the state in which i will just put four is and then paste it six times one two three so like four still 24 got the state so what i'm trying to say is that the different options in which we can take any number and then we have to get to that particular state so let's say if i get to total number of six is then i will just copy paste it six a's multiple times then i have to also find out what is the minimum number of steps required to get to six a's okay because if i somehow optimize the way to get to six is then when i've got to success i have to just print six is that's the four times similarly i have to optimize the way to get certain if let's say four is and then paste four is let's say six times similarly i can get to optimize the way to get to 2 and then print 2 let's say 12 times so they are different options so you have to first find out the multiples of this number as well so that's the one thing what you'll do is that whatever n you have the different options is that you have to first uh what you actually have to do is that for that personal number what you'll do is that you have to first find out the smallest states value also okay so let's say for 24 you have to find out what is the minimum number of steps you've got to get to six or four so you can start from the let's say for every number you can calculate for every number because uh the smaller numbers you have to first calculate to get to the larger numbers but what you can do is start from four till let's say whatever n you have and find out for all the values and for uh for all the values what you'll do is let's say for four you have to find out all the factors of four let's say it is one or let's say equal to uh two so for one and two what you'll actually have to do is that how many times one is repeated okay four times what how many times four is like two is repeated two types whatever is the minimum of both of the states this printed out that's the state to get to four then five and so on and then when you get 24 you have all the lower states as well because you've calculated in the dp table and then you can just get that's our logic we'll move on to good parts that it will become okay you so what we have done is that we have initialized the db table the maximum limit is set here so 10 000. sorry 1000 is the maximum end you can get two so i just take that like thousand and five and this is the initializing dp states which you can just find out and it's very simple so that we can fill out some of the states so for zero one two three let's start from my equal to four till i equal to n what we'll do is that when my let's say so one always divide all the numbers in which i can just in the very best way i can just print a multiple times to get that number so let's say for seven i can always just print out seven times a and this we can get done so this is the minimum answer so it is always exist answer that is dp of i equal to i number of five steps are taken okay so that's our answer but we can we optimize that to optimize that you can do it in like a nested for loop in which we find out all the factors of that portfolio so let's say starting from two till t less than i but so if it is factor so if this j divides this i so if you have found the factor then how many more steps i have to required so let's say if i find that for 24 6 is a factor so if see the effect 6 is a factor i have to find out first what is the optimized way to get to six so how we can find out so if six is a factor what i'll do is that if so we have to just minimize over all the particular steps we can get to the minimum steps is i divide by j so let's say 24 divided by six it will give you four so what it acts like 24 so 24 uh let's say we have six so like what i value that we have to find out 24 divided by uh let's say six will give you four that we have to somehow let's say if you like we have to like if we have four is if we have four a's then what you actually have to do is that we have to print six times so six times we have to print this out so six operations are required and what is the minimum like energy is required to alert minimum steps required to get four is okay that is that we can find out by dp value so dp of i divided by j will give you the minimum number of steps to get to that state and from that state you have to print out that partial state let's say j times to get to the final executable state that you want to find out so dpf idea by j will get to the portland state and what is the minimum required to get to that state and from that set you have to print it j times to get to the final state and that is just uh value you have to get to reach the files that you want to reach to and then you have to minimize over all the values why that is dividing that number right though and then we have to just go over the final state that we have you can just print out the that's the world like uh the overall code part so we have used a dp so that is storing an o of n in space so we have taken a constant only but let's say if you want to make it increase by n so it is like of n and uh this is the nested for loop so that should follow so of n square is the time of 3d for this problem that's the overall tank obviously and says completely for this problem thank you for watching coding and bye
|
2 Keys Keyboard
|
2-keys-keyboard
|
There is only one character `'A'` on the screen of a notepad. You can perform one of two operations on this notepad for each step:
* Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).
* Paste: You can paste the characters which are copied last time.
Given an integer `n`, return _the minimum number of operations to get the character_ `'A'` _exactly_ `n` _times on the screen_.
**Example 1:**
**Input:** n = 3
**Output:** 3
**Explanation:** Initially, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
**Example 2:**
**Input:** n = 1
**Output:** 0
**Constraints:**
* `1 <= n <= 1000`
|
How many characters may be there in the clipboard at the last step if n = 3? n = 7? n = 10? n = 24?
|
Math,Dynamic Programming
|
Medium
|
651,1033
|
319 |
hello everyone welcome back to another leeco problem solving session today we're doing the problem of the day for April 27th is called bulb Switcher so there are N Bulbs that are initially off you first turn on all the bulbs then you turn off every second bulb on the third round you toggle every third bulb turning on if it's off or turning off if it's on the earth round you toggle every ith bulb or toggle every eyeball and then for the nth round you only toggle the last ball essentially you toggle you know you go through every bulb and you turn it on and then you turn every other one off and then every third one you turn back on or I guess you would toggle it's not necessarily turning on or off at that point so this actually not too much of a coding problem but more of a math problem actually we'll look at this first example n equals three so you can see that after the three rounds just the first one is on and these the second and third ones are off so the first round we turned second one and third one on and in the second round we turn the second one off and then we never touch it again because after that it's the you know every third and every fourth well we're never going to touch the second one again we've gone through all of the rounds that could possibly touch the second one and for the third one we turn it on in the first round and we turn off in the third round essentially what you do is you turn it on or off in the rounds where the round number divides the number of the bulb itself so one and two divide two so in rounds one and two we would turn off uh to sorry toggle the light bulbs on or off so we have to think okay well if there's an even number of factors then clearly we would have the bulb off by the end of it whereas if there's an odd number of factors then we would have it on because you know on off and then one more or on that would be an odd number so when does a number have an odd number of factors well when you think about it every number if you were to divide by let's say one you have a corresponding let's say the number n if you divide one by n by one you would be left with n and that's the corresponding Factor you can kind of pair up each factor that a number has so for let's say eight yeah it's a good example uh we would have one and eight and we would have two and four so that is an even number of factors so if n is at least eight then we know that we will have an even number of factors for eight and this ball will be turned off by the end of it but let's say let's look at nine well nine as one and nine and then three and three so these are duplicates here which means it actually has an odd number of factors and you'll notice the only time you'll have duplicates is when a number is a square so essentially what we're doing is we're Counting the number of squares up to n well if we square root something like 9 we'll get three so knowing that 9 equals 3 squared tells us well we've gone through 1 squared 2 squared and 3 squared to get to 9. so all we have to do is simply return the square root of n right well then you still have the case sorry let me just import some stuff for math but let's say you have n equals 10 in this case well square root of 10 is not even an integer so that's not going to work for this so what we do is we actually have to take the floor because essentially everything all the squares up to 10. are the ones that will be turned on by the end of the 10 Rounds so we would have one three and nine there's the ten bulbs on after the first round and one chapter round two this is after round three this is after round four it's after round five this is round six this is round seven after round eight after round nine and after round ten so as you can see the only ones that are turned on are the squares the one four and nine so we just take the number of squares less than or equal to n then we should have the solution perfect thank you guys so much for watching if you guys have any questions about the solution please let me know in the comments also please like And subscribe and I'll see you guys next time
|
Bulb Switcher
|
bulb-switcher
|
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb.
Return _the number of bulbs that are on after `n` rounds_.
**Example 1:**
**Input:** n = 3
**Output:** 1
**Explanation:** At first, the three bulbs are \[off, off, off\].
After the first round, the three bulbs are \[on, on, on\].
After the second round, the three bulbs are \[on, off, on\].
After the third round, the three bulbs are \[on, off, off\].
So you should return 1 because there is only one bulb is on.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `0 <= n <= 109`
| null |
Math,Brainteaser
|
Medium
|
672,1037,1491
|
1,689 |
Friends welcome back and speedometer into this scene if this is a problem 250 hours this alarm problem art this vinegar number we need to find the number of number subscribe number only for example 32.2 number three 500 2830 hot [praise] [praise] [praise] 12345 has a problem do it i need to have no idea of one or two reddy123 48 reduce 2515 12345 1205 13151 adh peeli straight variety number 16594 number of places for at least 50 page number 90 number 1090 number to 0000 is finally coming from 0 to 0.5 Inch 11 Number Which Can Reduce finally coming from 0 to 0.5 Inch 11 Number Which Can Reduce finally coming from 0 to 0.5 Inch 11 Number Which Can Reduce Previous Classes Maximum Number Which Of The World Channel Must Subscribe Click On Subscribe Button Office Number That's My Improvement Simply Not Mean That Toe Print Is Number Feed Simple Wash Speed Simple You Chest Point Loop Vs Wash Speed Simple You Chest Point Loop Vs Wash Speed Simple You Chest Point Loop Vs In Which state is the maximum present in dot street lights looter distic which was the number which supported 2768 so i will hair pack abs heart attack lucky number 19 number will be updating the maximum number of numbers subscribe The Amazing Number One Side Key Problem 60 contest time fear
|
Partitioning Into Minimum Number Of Deci-Binary Numbers
|
detect-pattern-of-length-m-repeated-k-or-more-times
|
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not.
Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._
**Example 1:**
**Input:** n = "32 "
**Output:** 3
**Explanation:** 10 + 11 + 11 = 32
**Example 2:**
**Input:** n = "82734 "
**Output:** 8
**Example 3:**
**Input:** n = "27346209830709182346 "
**Output:** 9
**Constraints:**
* `1 <= n.length <= 105`
* `n` consists of only digits.
* `n` does not contain any leading zeros and represents a positive integer.
|
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
|
Array,Enumeration
|
Easy
|
1764
|
152 |
Do it to Ajay, do it 200 Hey guys welcome to food of yours next question is maximum product in the morning, something like this has to be subscribed to each other so that those who talk about the product to the maximum, then in this survey - - - - To subscribe, not to subscribe to the product, if you have not subscribed, then something like this question is almost a little different but here Shahrukh comes out like teaching, before that we also see the boot polish, which is the way to call it. Subscribe We do We people - - - - - - people - - - - - - - - - - Subscribe to the channel - Subscribe to the channel - Subscribe to the channel Subscribe You keep doing the same, whatever maximum product is there in the maximum bedroom, it is returned by its time. If we talk about City, then guys, will it become Bigg Boss's or will we use both the extensions and space complexity will be done, will it become Bigg Boss, then its brute force has been sent, so let's see it in the test match. Optimize is yours, this salary offer is very beautiful dance from us, what do we do, at one time and here, we do, and what will you all do, we will simply start traveling, we will People will do, if we start multiplying, then we will mix some product from the people, we will select this lineage of people, we will do it because when we take out everything, then we slice from the communities and sometimes we take out Bigg Boss product. So Kulwant Saini slices the product because it forms the identity of its product of basic maths and basic of computer. If we maximize this product then it will definitely attack. Then what will we do? Will we start traveling in it? What will be the problem? First started first and their C product of ours Multiple requests to care off side This is my first start We do the elements as per medical So first of all what do I have Six to six* C product Will do So Six to six* C product Will do So Six to six* C product Will do So what will happen, it will be fine, that is, we will check that the product which is there since August, if the current product which is there, also does the oral maximum, then what I will do here, we will install the maximum, it is the current product, it is the basis of floor, dried that. We will be the drivers so first of all ok so what will go here in maximum here I abuse him by doing this race, he can be learned, education will go ok but when - - - - but when - - - - but when - - - - now you were thinking that maximum in the morning if you understand if Shubhendu bhai, why should anyone have negative delay in such hours? We started from here, we used to do this on this maximum in the morning, we used the system by putting it in, I will put its gender in the description, both of them are important questions, friends, if you Meghnad may be doing this question while finding out the people, it is negative in the maximum early in the morning - while completing this, negative in the maximum early in the morning - while completing this, negative in the maximum early in the morning - while completing this, now we cut it, so it may be Subscribe So what kind of infection do we have ? It is possible to get 15 pin numbers ? It is possible to get 15 pin numbers ? It is possible to get 15 pin numbers so that our quantity can be increased, so this option was there that by adding in it, but what will we think here we are multiplying the - we are multiplying the - we are multiplying the - element because it can be It is possible that in the future, if we do another thing like - - - - - - - here, then this positive element can also be given to these people so that our product is based on this thing - on this number. Here, first of all, - on this number. Here, first of all, - on this number. Here, first of all, but that Ghr - - - - - - Ayodhya Company, this festival city will be described in the current product, in this entry our oral maximum, if someone tweets, then the current product is this cross maximum of the host team in the serial which is 181, so now let's talk. It's okay that we pressed positive then we saw what to do negative then what do we do if it happens if any element is such that if it happens then we do we Let's do let's stop it here Basics of Lo SLY threatened that if ever or never if hero comes only then weather hero comes then sign off the current visible and rest of the algorithm we do proper Similarly, what did we do when the hero got money, we became a C product and signed it, next time the job is one, two, if he is doing whatever he is, then I am taking it to the maximum, so now we can have one more. These people try to subscribe something else - Rs. 600 per house or five robbers, here I subscribe to it - Product - - - - - - - - - - - - - - - - - - 30, try this, I do n't know its notification, okay If there is any negative, then just know this, you guys, this is a big negative Admit is fine, if actors five will come, then here we will joint it, so people still see there is a big negative, Yamlok has NDA which is the overall maximum. Well, this body is not able to beat, how will you fry it like this, the problem here is not that it is not able to complete it, we have to complete it, what should we do Do it, we will quote it again, what will we do inside the print product, we will sign it closed, once we will press it from the back, what am I saying in this, once we will mix it from the back side, now we do it in this, now we do it in the back side Let's see that now in school we will do 2222 maximum, okay we will do this product here so come here okay next unknown people - if we next unknown people - if we next unknown people - if we get 6 then - what will happen after breaking by 6 get 6 then - what will happen after breaking by 6 get 6 then - what will happen after breaking by 6 this will happen from Zuma A positive - This is the Twenty20 thing, now look A positive - This is the Twenty20 thing, now look A positive - This is the Twenty20 thing, now look guys, whatever it is not even meeting our overall maximum level, so do n't change it and subscribe to our channel, it won't make any difference, we have one like this from here. Even in the product which is there, the question is that whatever product is there, let us do it in this way, first of all, maybe one minute can be completed - - - - 1 Ay, coming complete, what will be our maximum product in the morning? Look at this, you guys will make even number of elements and number of negative elements semi-formal positive, for this we will semi-formal positive, for this we will do it, so let me show it to you, from that I think you guys will mix it well, okay then we Will take it aside Subscribe Like Subscribe Then I had told that if the product mutes our maximum visible then send the current product in the maximum serial, okay this is done then I had told that Which attacks will have to be kept in mind that if a friend of I, which is this hair oil which is 220, then I send one product, then Assam people have to take care of this and then what I told that we are a What will we have to do? We will have to travel from the back side also. We have traveled with our own power and we still have maximum stored in our maximum visible. When we have traveled forward, now what will we do with the same look again? I will continue from Let's copy this, what will we do now? Now we will use gas on the backfoot, so subscribe and minus one, so we will add them again in 2008, use this. If you have subscribed, then it is being completed successfully. Hey guys, whatever our output is, we can do dry skin and time and try it. If it gets submitted then it will be fun and it will also be submitted. If it is specific then don't submit it will be good. It opens here in this teacher. It will not happen that it will be long here because our interior has absorbed it, so here we will have to make it long, now let's submit it and see, now there should not be so much problem, so now all this will be erased. But if it is submit then let's talk about whose time complexity then friend will be of the time complexity. Time complexity will be soaked off. Once in power traversing, end of inquiry was in travelling. Please complexity is constant, no extra ladies, we are not using it. This was the timing and space complexity of the festival and I hope this complete discussion will be clear to you guys, one more thing guys, we can call this question in one trip also, this question can be solved in just one pass but I am not discussing it here because it is a bit confusing, so do one thing for me, I will put its gender in the description, the flower of the solution, you have to try it once, if you can't do it then you can comment on it. Tell me, I will definitely make a video on that too, so it is not difficult, there is nothing typical in it is just that it cannot be achieved by offering a little bit, that is why I thought not to discuss it, so I thought that we should discuss it on this channel. However, if we look at the scroll time complexity, it is graph end but it will be a little effective in run time because the runtime will increase a little due to this, here I am, share the link of the solution guys, I will put it in the description, if you want, then you can see it. If people do not understand, then I am also saying that if you people do not understand, then you people can comment, I will definitely make a video on that, so that the complete discussion will be clear to you people, that is why there was an end for this video. If you liked the video, then like the video and subscribe to the channel so that you do not miss any latest notification. I will meet you guys on Twitter. Guys, in this video we are taking another question call, on top of this. So I'll see you guys in the next video to see how to use it.
|
Maximum Product Subarray
|
maximum-product-subarray
|
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_.
The test cases are generated so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,3,-2,4\]
**Output:** 6
**Explanation:** \[2,3\] has the largest product 6.
**Example 2:**
**Input:** nums = \[-2,0,-1\]
**Output:** 0
**Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-10 <= nums[i] <= 10`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
| null |
Array,Dynamic Programming
|
Medium
|
53,198,238,628,713
|
229 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem majority element 2 I highly recommend you solve the first version of this problem before trying to tackle this one even though this one is slightly different and the solution definitely is a bit different but we're given an integer array of size n and we want to find all elements that appear more than this many times now this is the floor it's not written super well but basically taking the length uh dividing by three and rounding that down so what does that mean if you took a number like nine and rounded that down well it you don't need to round it right it divides pretty evenly and you get three so we want if we had an array of length nine we want all the elements that appear more than three times first version of this problem was taking n and dividing it by two and that is the majority element like an element that takes up more than half of the array but this time we want elements that take up more than a third of the array if you were to take a number like 10 which doesn't divide evenly but you still round it down we would get three as well so we want elements that appear more than three times and in that case we'd get four is more than A3 of 10 so that's kind of the idea but in terms of the solution it's not super complicated we could very easily solve this problem with a hash M couldn't we just count the occurrences of every single element and then afterwards go through every element in the hash map and just check is the count greater than n / 3 is the count greater than n / 3 is the count greater than n / 3 is the count greater if it is then we add that to the result and if it's not we don't add it to the result well first of all you should recognize that the output is not going to be arbitrarily large I said that we want elements that like take up more than a third of the array how many elements do you think can do that in a single array probably no more than two elements suppose we had an array of size four and let's say we have a one and a two these both would be the result so the result would be one two because each of these takes up more than a third of the array but it can't really be larger than that and it could theoretically be zero like if we have an array like one two three four none of these take up more than a third of the array so in that case the output is going to be zero we're not guaranteed anything in this problem so those are a couple points I wanted to make but going back to the hashmap solution yes a hashmap is actually perfectly valid what is going to be the time complexity for that probably o of n to count all of the occurrences and also o of n for the size of the hash map in the worst case that works but we are actually able to take the space and reduce it down to Big O of one that's actually the follow-up of one that's actually the follow-up of one that's actually the follow-up question if you go to the bottom of the description of this question and it's possible but it's not necessarily easy or at least easy to come up with once you know it's actually pretty easy the concept is pretty simple we once again actually use a hashmap but this time we're going to make sure the size of the hashmap is always going to be less than three in other words the idea here is going to be that this hashmap only contains the two most frequent elements so the idea is actually simple enough now coming up with it and implementing it is not simple until you actually see it and to show you I'm going to basically go through an example so let's do that now so suppose we have an array like this is our hashmap we're mapping a number to the count of that number so we start here we have a one we add one to the hash map what's the count of it's of course one then we have a two so these are our two most frequent elements so far each has a count of one now we get the third element three so we map it to its count three but we don't want this guy to grow arbitrarily large so we have to restrict it so what do we do I mean all three of these have the exact same length which one do we remove we can't like pick I mean there's no intelligent way to pick which one to remove but what if I told you we can remove all of them but why can we remove all of them I thought we're trying to count the two most frequent elements well yes we are trying to do that but we also know that we don't really care about any of the candidates if the like count of those candidates is less than a third or even equal to a third of the input it has to be greater than the length or it has to be greater than a third of the length of the input so my argument to you is this as soon as the length of the hashmap becomes greater than two meaning basically three like when once it's equal to three we are going to then decrement the count of every single number in the input and if the count of any of the elements is equal to zero we remove that from the hashmap so this time we're removing all three but it's guaranteed that we would always remove at least one of them and that's because like at some point like let's say the count was two of each of these and then we add a three and then the count is one like when we add the third element the count is always going to be one so at the very least we're always going to remove at least one element to make sure that the size of the hash map does not become greater than two that's kind of the intuition here so now just going through the rest of this example let's say our now hash map is empty we've already gone through these three elements now we get a one we add it back to the hashmap count is one now we get a two add it back to the hashmap count is one so what do we return in this case we return these two elements they're the two most frequent elements but in this case it does work out the length of this is five divide that by three and round down you get one each of these has a count of two so obviously this has a count like a frequency greater than this and this also has a frequency greater than that but that's not always going to be the case actually if we had a different input array like 1 2 3 4 5 6 and then seven and eight actually we would get kind of the same thing first we'd add these three to the hashmap and then remove all three of them then we'd add these three to the hashmap and then once again remove move all of them by the end these two elements seven and eight would be left in the hash map and we don't want to return those as a result they are definitely not taking up more than a third of the array so what we learned here is that even though we are theoretically trying to keep the two most frequent elements in this hashmap that's not actually what we're doing we actually don't end up with the two most frequent elements at least not in this example because all of these are the most frequent they all have the same frequency and just because these two are left in the hashmap doesn't mean they take up more than a third of the array so what we have to do when we have this resulting hashmap we then have to verify for each number is the count actually greater than a3d of the length and that's not difficult to do we can literally just get the real count of seven and 8 which is actually the same it's going to be one for each of them and then I compare that to n / 3 so and then I compare that to n / 3 so and then I compare that to n / 3 so we can verify that these are actually taking up more than a third of the array another quick example to really get this point across is what if the array actually looked like this we have a 1 2 one 2 1 2 and then we start getting some different elements like three four 5 well our hashmap would eventually like by the time we get to this point our hash map would map one to three would map two also to three and then we'd insert a three we'd get three maps to one and at this point we decrement each of these by one which would end up removing this and we' get these two set removing this and we' get these two set removing this and we' get these two set to two each once again when we get to the four we're going to do the same thing add four to the hash map and then remove it because our like length of the hash map became three so we have to decrement each of these by one so then we decrement this and this down to one as well and then lastly we' get to five as well and then lastly we' get to five as well and then lastly we' get to five now five is going to map to one I know this drawing is getting a bit bad but we'd remove five we'd take this count decrement it to zero take this count and also decrement it to zero and now these would be popped and by the end we'd have an empty hashmap basically there's no solution to this problem does that look right to you yeah because one takes up exactly a third of the array two takes up a third of the array and here is also a third of the array but we want elements that take up more than a third of the array so if we instead in this example actually didn't have a five then by the end of like inserting this and this we'd have a count of one for each of these that doesn't guarantee a solution but then we would verify that the counts like the true counts of 1 and two which are three is going to be greater than 8 / 3 rounding down which greater than 8 / 3 rounding down which greater than 8 / 3 rounding down which is going to be two so this actually does work I know it's not easy to come up with and that's because it's a hard problem especially if you're trying to solve this problem like this with constant memory but that's kind of the benefit but now let's go ahead and code it up so the first thing I'm going to do is create a hashmap and in Python you can actually create default dictionaries which means you can have a default value in this case I'm passing an INT which means the default is going to be an integer of zero so now when we go through every number in here and try to count it and we try to increment the count of this by one we don't have to verify that like n is already in the hashmap because if it's not this will give it a default value of zero and then we'll increment 0 to one but we have this is fine we're just getting the count of each number but remember if the length of the hash map is greater than two then we got to do some stuff we have to decrement the count by one now I know that this is going to get like highly nested so I'm actually going to do the opposite here I'm going to say if the count is less than or equal to two let's continue meaning we don't have to decrement the count we just continue to the next iteration of the loop but if it is actually greater than two then we have to go through every uh number and count and I'm going to do that like this count. items in the hashmap it just is kind of a shorthand and then we unpack the key which is the number and the count and we're going to check and one way to do this would be to just take count of N and decrement it by one and then after here we could then go through the count hashmap again and if any of the counts are equal to zero we remove them you might think first to try that in here like put an if statement here if the count of n now is equal to zero can't we just do count. popn no because we're iterating over a hashmap and we don't want to change the length of the hashmap as we iterate over it so this is not a good thing to do so another way of writing this uh there is that like two Loop solution I talked about but another way is to actually declare a new hashmap a new counter and I'm going to do the same thing default dict with int and doing it this way we can check if the count is greater than one then we know that this number is going to go in the new hashmap why did I do that and what is the count going to be the count is going to be the original count minus one that probably makes sense it's same as the drawing explanation but why am I only adding elements that have a count of greater than one to the new count hashmap well because if it had a count of one that would mean we're decrementing it down to zero and of course we don't want to keep anything that has a count of zero in the hashmap so that's why I'm writing it this way now after we do that we want to update the count to the new count hashmap and then we're done after we do this if there is a solution to this problem like if any elements in the array show up greater than a third of the time they will be in this count hashmap this is actually not necessarily going to be the two most frequent elements as we talked about earlier but if there's a solution we know for sure that those elements will be in there and we want to add them to an array before we return them and how do we verify that those elements do show up greater than a third of the time well it's pretty easy just iterate over those elements and this is misleading like this is not going to be Big O of end time we know there's at most two elements in that hashmap now we want to check well what's the count of each element and this time I'm going to do something not the most efficient but it's easy to code and I don't think it's bad it's not going to affect the overall time complexity I'm just going to take nums do count of n this is a linear time operation but as I talked about this is only going to execute two times at most two times so doing a linear time operation two times is not that bad it doesn't affect the overall time complexity it's still a linear time solution but we're checking the count of this and we just want to make sure it's greater than the length of nums divided by three if it is then we will append it to the result that's the entire code now let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
|
Majority Element II
|
majority-element-ii
|
Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times.
**Example 1:**
**Input:** nums = \[3,2,3\]
**Output:** \[3\]
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1,2\]
**Output:** \[1,2\]
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-109 <= nums[i] <= 109`
**Follow up:** Could you solve the problem in linear time and in `O(1)` space?
|
How many majority elements could it possibly have?
Do you have a better hint? Suggest it!
|
Array,Hash Table,Sorting,Counting
|
Medium
|
169,1102
|
1,021 |
what's up everyone today we're gonna go over leak code 2021 remove outer parentheses now the problem description is a little involved so I'm going to explain that first before I get into the code in the solution so if you already know what the problem is asking you can skip ahead now the input is gonna be a string like this right it's gonna be a string which has parenthesis and what they want is us to first keep in mind what a valid parenthesis is and then they're going to describe to us what a primitive parenthesis substring is so valid substring valid parenthesis is either empty or it's a valid string with the left curve and our right curve so it could look like this right but this is also a valid one because inside right is empty and has a left and a right same thing is eight and a B if they're put together like this right a being a valid one this one down and this one being a regular parenthesis what they want is for us to break down the give an input s into primitives right and they'll tell you in the problem what the primitive is and what they want is once we have these we remove the left and they're right and give us back so if this was the input the output would be like this and then on the right side empty because this guy has is this removed and this one removed so it's gonna be just the inside plus the empty string with this which is just the public parenthesis for this input here what we're doing is first breaking down to give an input into primitive strings like this and then we're taking away this and returning what's left now the way I saw this problem is by using a stack and a list and I'm going to keep I'm going to show you what the values look like and change now the reason I use a stack is to keep track of left and right and closing entities and pop them out as their incoming and the reason I use the list of integers is to keep track of when my stack is empty because that guarantees that I'm either at the start or end of a primitive breakdown so for example when I'm starting my loop for the first time they're gonna be empty so when I push this in it's guaranteed that this is gonna be the beginning of a primitive now when this and this come they're closing so I pop them out this and this cut popping up when this comes this and this are gonna close each other and it pops out now when this pops out the size of my stack is going to be zero so I keep track of every time the size of my stack is zero and that's how I guarantee that these are primitive now using those numbers I'm going to find that I take the substrings and that's how I'll return the output so let's get into it so first I'm gonna have a stack of characters and then a list of integers L is new ArrayList and then I'm going to take the input string s and convert it to a character array for easier access and iteration so as no a are gonna be asked that to char alright so we have these three data structures now I'm gonna get rid of it so it's gonna be clear when we iterate over and work with our data structures so we begin by iterating know where the character array I is less than a our dot length and then I plus so the first thing we're gonna do is check if L if stacks are stack the size is empty I'm going to l dot add I push the character that came on so AR of I and then I'm gonna continue so what this looks like in the beginning is this my stack is it gonna have this right it's gonna happen it's gonna be empty in the beginning right then my list is gonna look like actually I make this bigger my snake is gonna look like this well this is gonna start 0 because its initially empty all right I add it I push this character on there and then I continue next if a R of I is gonna be this opening brace and stack peak is the closing brace what I'm gonna do is I'm gonna pop stack dot pop and then I'm going to L dot and I write L dot I and which is to keep track of a finishing no I'm not gonna add that exact like that if stack dot sighs yeah zero then I'm going to add b5 it will look like five but I'm gonna tell you what that is in second if then we flip it on it if we have closing brace and stack dot peak is the opening I'm gonna talk what I have and then I'm gonna check if the stack is empty if so I'm going to add I else if none of these conditions and match all I'm gonna do is stack don't push Oh ary cool now that I wrote this code let's go over what this looks like I pushed this one for the first time because it's empty and I keep track of zero next I continue then this one it's coming in it looks like this but the peak is not a closing so I push this guy in there as well next when it when this guy comes right I check hey is this closing yes because this one is coming in and the top is this one then I pop it because this and this is gonna close right then I check is the stack empty or is the stack size zero it's not so I don't go in here next this guy comes in he comes in because this one is the left side but the peak is not on the right side so all I do is push it on there next I check this guy he is gonna close with him so I pop him and when I after I pop him I'm gonna check is the stack size zero it's not so I don't do this now when five comes in for the first time this guy in this guy are gonna match right they match here I pop him and then I see hey my side is empty so I'm gonna add I which is fine so zero in five for the first time that's how we get the primitive breakdown that's exactly how we're gonna do four six next iteration it's the sizes empty or the snake is empty so I add whatever I need to add it comes in here next seven is gonna go in here because there's these two are closing then when it comes around eight and seven are gonna close right so seven gets popped and the size is not empty so we're not adding anything to L now for the last time when nine comes a RI of nine is this guy its closing and the peak is this opening gun so this nine and this six they're gonna get pumped and after they get pumped I check oh I forgot to put in a 6 here but after six after nine and six match I'm going to check if this as your own that I'm gonna add I which is nine now because I have this I'm keeping track of the primitive indices now I can go in and use my list or a list of numbers to get the substrings so just look at this take a look go so I'm gonna have a stringbuilder call SP and you stringbuilder and what I'm gonna do is check go over this list twice two at a time so it's gonna be for int I is equal to zero iyslah Steinfeld sighs and then I is gonna be incremented by two because I'm gonna check these two together and DC together now SP is going to be appended by s this so shrink s dot substring of I need to get this one all right so it's gonna be L don't get I plus one because I'm not trying to get this one I'm trying to get this guy comma to close this up string L dot and get I plus one so it's gonna get five it's gonna look like this is gonna be s done substring of zero comma 5 but the way substring works is it's gonna pull this guy so I'm gonna essentially get sorry zero plus 1 comma 5 so this is gonna look like 1 5 here but it's gonna get these guys in here so the first time it's gonna append for the first time it's gonna append like this and then the next for loop it's going to check with 0 plus 6 and then 9 so then it's gonna get these two now this is gonna be the answer that are returned so I'm going to say return speak to a string okay cool so this is how I solved only 2021 if you liked the video please subscribe and like it and let me know how I can improve in the comments below thanks for watching
|
Remove Outermost Parentheses
|
distribute-coins-in-binary-tree
|
A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation.
* For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings.
A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings.
Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings.
Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`.
**Example 1:**
**Input:** s = "(()())(()) "
**Output:** "()()() "
**Explanation:**
The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ".
After removing outer parentheses of each part, this is "()() " + "() " = "()()() ".
**Example 2:**
**Input:** s = "(()())(())(()(())) "
**Output:** "()()()()(()) "
**Explanation:**
The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ".
After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ".
**Example 3:**
**Input:** s = "()() "
**Output:** " "
**Explanation:**
The input string is "()() ", with primitive decomposition "() " + "() ".
After removing outer parentheses of each part, this is " " + " " = " ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'('` or `')'`.
* `s` is a valid parentheses string.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
863,1008
|
668 |
I cook 668 a Keith smallest number in multiplication table nearly everyone has used him one occasion Tama but could you find the cave smallest number cut me from the modification table given the height M and the length and of an M times and what occasion table in a positive integer K you need to return the cave smallest number in this table ok there a couple of ways to do this so the first thing that I would look at is the bounds looks like it is 30,000 is the bounds looks like it is 30,000 is the bounds looks like it is 30,000 and that means you have to be smart because M times and it's gonna be 30,000 square which is 1 like 900 million so slightly less than a billion so but still pretty sizable so you can't do anything like so one time I think about is like putting things in a heap and it's stuff like that right and then just keep on iterating to get the next one but 900 million is going to be too slow so you need to be human smaller than that cave in the range 1 ok I think this and some of this is try and we try to figure out but I would because M and you could probably just assemble or assemble the phrasing of this to just be n square or and because you can always just say oh if M is bigger than n just swap them and you have to same answer so this so in terms of n for complexity analysis we probably need for 10,000 we need we probably need for 10,000 we need we probably need for 10,000 we need either oh man oh and again I don't know if we could do it in just oh and or just like I don't have any intuitions about it and n log n means that there's some kind of binary search ish so there so you could always also just do regular binary search given that your max is gonna be 900 million log of that is about like log base 2 to be clear of data it's about dirty so like so dirty binary search numbers should be okay if given a number we just go through and to calculate how many numbers or how many multiples of ends are there and then you kind of sum them all together and then down and then you check that for against number of KS and then that would tell you the answer and because that operation takes n times and so it's n times log of 900 million which is technically log of n square which is lock N or to log n but then like o of log n so that's M again Algrim right I think that's okay and for n is he got a dirty thousand that should be you know way enough time so I think I'm gonna start kind of going down let me know if I could explain anything this better that's kind of my thought process yeah well my current up process is learn do you do y'all wanna see in C++ or I could you do y'all wanna see in C++ or I could you do y'all wanna see in C++ or I could do any language I think for a binary search it doesn't really matter I could do it okay Oh Java yeah that's let's to go let's take an attempt my java will not be as clean so don't but I mean so I always appreciate feedback about like code and stuff like that so definitely feedback but uh but don't laugh at me too hard I suppose but yeah so what we actually wanted to my first instinct is just to make the problem a little bit easier in that I said that you know you can always swap em and depending on conditions and now we actually want because if you think about the binary search and you chip don't just use this N and in fact if you think about it there's no M in education but at least a log n part is dominated by the end point the constant time of the outside the linear cost of going through and counting you could just take the min of M and end because it's cheaper right so that's why I'm winded that's what that's really in the whole winded way of saying it but that's okay so actually when the other side I would like using an instep attempt so just swap them I don't and C++ you could use swap I think yeah and C++ you could use swap I think yeah and C++ you could use swap I think yeah and now we do a quick binary search so again I used the same ish template a lot so now we can well what is out tail which is the top part of the binary search well just M times n right I'm just for a kind of math I don't know bounding I think I could do that a little bit higher it would never get there so it's fine and then the head is just Silla and then now head first now we just have a standard ish binary loop yeah I'd like to usually just keep track in a little bit so I need to be better about this point that part is behind me I think let's just actually do this way let me do nothing else I'll learn something this is standard binary search the only thing I would say is that nine hundred million so one thing that I have to think about or want to think about is that you know so I write this quite a formula but just omit as you go yeah this is binary search but if head is nine hundred million plus another nine hundred million dollar bite so in this case is okay but in another scenario you can imagine that let's say this is like you know 1.1 billion which is only you know 1.1 billion which is only you know 1.1 billion which is only slightly bigger than 900 million then this will overflow int and then this will give you a pretty sad day so that's how I was saying about via so now yeah if Cal of MIT and they're just given the input if God is bigger than K and what I was thinking about it's just trying to think about the greater than or equal to and what happens in the equal case I guess in the Yuko case then you just return it so maybe I'll so maybe that's what I'm gonna do but if the count is greater than K what does I mean that means we have more numbers for them we want to go lower so Tara is he gonna admit I was okay I just I don't do twice they were from similarity I could to be a little bit bad about this but I was serious less than K you that the head is you gonna make otherwise dad see is K then they just said how did you get a min and then we prac and then we return head I guess we could just return that then but just okay I know we need still I've no it's implicit in it's been a long time let's try it was it called the product and because we need them to kind help out calculations and in this case just to I don't know and this and we just have to do the count right and again the first thing that I would think about because the numbers are getting big it's ready to fit in it but no rebound okay then it should still be bound by nine hundred million I think in theory you could go where you over there but right here we're capping a pie just don't pick a number anyway so yeah and maybe you could even cash maybe you do maybe there's some like even better formula about this to be honest but happen but for now I'm just gonna actually go from I've to the smaller one so I'll do something like this and then see this just you go to the number that we're testing / and no by I my mind yeah testing / and no by I my mind yeah testing / and no by I my mind yeah why I and that's kind of the numbers in the multiplication table that you have but it is kept by M right so we want just a min of these two numbers and also this is an addition not it and I think that's roughly why already in terms of coding let's take a look it's been a while since I've done Java I guess I thought that was it oh I think I'm king of c-sharp in Java think I'm king of c-sharp in Java think I'm king of c-sharp in Java week really two functions start with witch McCoy lowercase I don't know what that would give me company at all and now we try to pick number the same and then again sometime hundred million I would say in my experience I've definitely failed a lot because I miss counting number of zeros in the number oh noes really hmm I would be surprising okay let's go just down back a little bit well let's test these teas first taste test for correctness and then we could think about optimize where this is and I can't imagine that's the case so I just have a minor issue somewhere okay at least that's why and it happens in one millisecond okay let's put all right I forgot okay well that would definitely do it was not within bounds but that's kind of let's double check first before I speak just maybe there's another thing oh really justice hmm this should only execute about 30 times ow I think I'm just being silly I think one of these has to be because it'll never converge for that reason hmm let's forget how much one asked so that means if MIT is trippin Eve quicker than k then we will never consider MIT again and so far okay don't work for the other ones no maybe they just got lucky with justice it's one of the case okay I mean it's well the answer because it's off by one okay fine but still that means is this validation on our algorithm and in once in 10 millisecond when we sent off by one that is in this case is fine because it's just binary search but I this is the point that to be honest I'm always like a little bit weird about I'm always like off by once right need to kind of read it dude maybe reread some literature okay bye oh maybe we remind never join the future let me just do something hacky this is mine stand it and then what I usually do well because there's no answer which is there you quote so okay yeah and then now I just check the first number that goes over it because what happens is that K is in between two numbers and I don't handle it correctly so that's what I'm you century I try to make up for it a little bit oh yeah definitely if you have like cuz I do this because it's way like I don't have to prove anything which is great for competitive programming but I do want to be more robust about it in general so I definitely like you know like way few people doing what I do and that's not bad to be you know what Uncas now in this case it tries to go because oh yeah this is no obviously little wacky yeah okay I know we submit oh no laughs I won I was well hmm oh yeah I mean I think like we're mostly there are we stop to kind of handle and uh exactly the thing all right hmm why do I get it off by one day it's a way to forget in carry that means you want to leave I just can't just now I could do a little bit better Oh No both pi-1 here now this was pretty both pi-1 here now this was pretty both pi-1 here now this was pretty saddle em anything just then need places for misinterpretation unless I'm off by one on um no but no I don't think so unless no cuz just we and it's the most yeah off by once but the album is right but that's why you know I always allocate practicing it is because even sometimes but you know exactly what the algorithm is you may wonder issues and it doesn't I was going to check for a submission time just making sure that I'm way under there are performing time but why does this something I mean I think I have to think about why is it exactly that this is well and maybe they just put it out there wow what is this charlie system dot out dot print line I think that also gave me another Elvis somewhere so telling me he plugged this one okay so on 127 I get four one is that what oh I think I just miss there's an off by one because I misread Kay because I thought it was from 0 to M times n so actually so that's unrelated to a lot of fancy stuff I was doing I just misread some of this problem which is not that hard to fix this in theory that also means that some of my hockey stuff defects I was wrong that's usually the way I structure these is that I do it by a my mama now maybe my numbers that little off because I like usually do it with civil index to it that's your first number one yeah five ones yeah just for I got most of it right except no so I now to think about it a little bit now for this case for five but yeah but now maybe have an off by an actual off by one in another case that kind of this is what happens sometimes when your things kind of wrong in a way that evens out which is unfortunate hey what's up Sonny how you doing yeah I guess maybe I'm ballin that one actually because I used to counting function yeah maybe meters is not necessary happened different things somewhere because I think the counting function it's a little different than my normal thing because you want don't move I staring off by wonder because you've won the counting function gives you the exact number or like giving it say six how many numbers are 6 or the same right which is illustrated maybe perhaps here where they're multiple numbers it's like okay given 500 so I given 3 how many numbers are three or less on the ends is five but that means if what was the answer before right what do I put and I'm not confident right now that it is right yeah you know what once in a while I try to learn stuff and remember stuff for once oh yeah so okay it's cause for three turns five okay so I think I have some I have to think a little bit about how to count there are five once I think that's my issue but the general album is ideas wearing okay so I think what I want to do actually is count by the number that were checking 4-1 okay because then were checking 4-1 okay because then were checking 4-1 okay because then that is the number for the numbers smaller than an inclusive which means it is more than this number exclusive and then you wonder next number that's bigger than that number okay that's understandable maybe come on Larry you can do this okay so what did I say smoke again I don't know this is still in this statement but now so this is strictly greater than what does that mean that means it's okay but you're stealing okay I don't but you could still considered to me so in this case I mean it's just this which someone's adjusted for the headsup yeah my thing is just all the boundary stuff that I always have little issues with wide are you gonna be upturned for that's not given an answer no I went somewhere oh yeah cuz mid now is wait if you go to Kay what does that mean hmm I mean what I actually should do is just well that's let's kind of get this away real quick oh yeah now tell me take a look right afterwards okay so the outfit I get there's three four five and still you know they're way that really given what is that for the end I'm putting one we want the answer to be Z and this mmm did I get the signs backwards now that don't be cray-cray quick okay so that don't be cray-cray quick okay so that don't be cray-cray quick okay so the myth let's bigger than zero so tells you no this is Riteish but there may be enough by something loosely last made right I just print some stuff up maybe Chavez bad luck for me oops so we start with 5 and that gives us X is that right that should give us X yep that's right and now we start with 2 and gives us 1 that's also right so there now it's twice for three plus five also right so what is 4 then 3 is 3 you're also correct so the count function is right so that means my if statement is 2 vs or and it's my return of their statement inside the batter I just put in the wrong frame no 3 1 is what why no but you've been three worst one left in my right why is my left in my why not checking for zero no.5 on jaha oh I gonna get into two years of 5mm it is tricky just having crews have made okay then it just doesn't terminate yeah okay so it's still well to be stuck between three and four so maybe this part doesn't matter how did that happen they didn't have it because civil between two and four is two so we tried number two is too small which no it's one now I guess I don't I took out their equal case yeah okay fine but that should still be okay yes 303 and then it terminates us that way but it sure him right man yeah tricky okay maybe I'll bring back the other thing with the linear help and then I'll have to learn stuff offline yeah okay I mean - exactly yeah maybe like that and then it's gonna run in from the loop because I don't even commit yeah definitely I mean sometimes you just you know one of those things so I once it is one of this was definitely this palm and unlink no like wow I took half an eye on this one just unfortunate yeah hmm why her that - unfortunate yeah hmm why her that - unfortunate yeah hmm why her that - because - is what I was testing I used her henna do it okay maybe I just walked by once 10 I'm really bad about let's just do it that way and this is why I usually do the way I did but I will try to figure out and learn off mine doct handled a RICO case maybe idea and now I turned this into linear search for the smaller cases okay and let me know mister the reason I do this is that it allows me to kind of handle the boundary conditions we better but worse but yeah I mean I just missed him maybe minus one because I was washing in a little bit another long church no yeah another Wi-Fi one just church no yeah another Wi-Fi one just church no yeah another Wi-Fi one just one of my random this once where there's certainly you know how many other you know things are there I am just you know I guess if this is zero then I just return that's him - no No maybe I need to stuff from one maybe just post two is messing it up absolutely max I guess so I don't know finds one of those problems where even I that is frustrating that I'm having and we're off by one even though not that much code for it to be that well fixed are actually cuz I think time I didn't fix it since they'd afford it to head bring it great and this submission was I guess there's no way that's a few second ago I'm just really not quite what something oh hey what's up yeah getting it off by ones and this one is still off by once no I don't know it's just that I mmm now cool ah Congrats that this is right no this should be right Oh No well now the same problem is gonna be even more I think a little bit all my usual trainees have been I'm in Java per second I was like maybe I need this to be something else I have no idea laia this was the one two three I feel like I'm just off by one but except with this case with I think the eternity ring I can do this no count just as a terrible what's happened be better now it's the same thing before I told you let's take a look real quick cuz I do worry about I don't think so though we talked about the math and now so it doesn't overflow okay that's good gotta tell you cosign wall maybe and you gotta be kidding me yeah they just don't know this okay I mean it's a very fast enough I don't even the pound I tried like ten things I can't even give you other side yeah because I tried ten things I'm a little tired and I was so like yeah I'm gonna have to kind of revisit this at some point but and I spent 25 minutes debugging this binary search you end up taking me about 40 minutes I itself just in about ten minutes and it spent 25 minutes on like this you cosine really having that is something I need to kind of practice on about so is it good you know just try to figure out what it is and kind of concerning the lower bound and upper bound yes exactly what I'm voxcom linked yeah Matt I'm trying to I am trying to cut and I do have this template up mentally right it's just I don't know I think maybe my understanding I'm doing it each case this is well like it's not you burn down by edge cases at one person I mean well they are in anyway but I think for me I was I just have to think about like I think for me like you're right in that uh you know it's for certain problems hey so X for some problems you're right in that uh I'm like what I need to do but I think for me I'm trying to figure out like what I learned about this in a matter kind of way and like and what I mean is like trying to think around learning itself and thinking about how it's still like a mental model that I'm going food that's like a little off for some reason I mean like the code like I can do it and you see it and you know that stuff but yeah but that's kind of the things that I'm thinking about in terms of how do kind of structure it in a consistent way but also just making sure that I don't have off by once that's a big one but you've been just like understanding it and converting to education and what are they would do the educators mean like and I think yeah I would definitely have to kind of spend some time to kind of really dig into it fundamentally and yeah I mean I think like the general idea like I obviously got pretty quickly but I have to really think about the edge cases which in this case is like well if you see three numbers before a number what does that mean right and I think that's the part that I got to consider the Left panel in the right band which is kind of similar to what you're saying with upper bounds and lower bounds and I need to kind of have like a point attack that's consistence I don't do silly things like spent 25 minutes on a form that I solved already essentially oh yeah cool again for interviews binary search problems of very straight already was that straight forward by men like very fundamental and expected this is probably a little bit a hard aside especially when you deal with off by ones you and I think you've got an interview you probably get away with off by once only in the sense data you know like what you got ninety percent the problem right but of course on the programming point you don't get any credit for the last ten percent but yeah now zeikos press of course exists you know you can do you don't know what this means come on that just that does stuff it just means headers you get it to a positive 2 in case you're wondering so don't be fooled but anyway but yeah that's why I have about this problem definitely recommend binary search in general though this is just trickier to get in general I'm having the numbers and their analysis is straight for like you know I got it's just that uh I'm thinking off and to get the boundaries right oh yeah cool
|
Kth Smallest Number in Multiplication Table
|
kth-smallest-number-in-multiplication-table
|
Nearly everyone has used the [Multiplication Table](https://en.wikipedia.org/wiki/Multiplication_table). The multiplication table of size `m x n` is an integer matrix `mat` where `mat[i][j] == i * j` (**1-indexed**).
Given three integers `m`, `n`, and `k`, return _the_ `kth` _smallest element in the_ `m x n` _multiplication table_.
**Example 1:**
**Input:** m = 3, n = 3, k = 5
**Output:** 3
**Explanation:** The 5th smallest number is 3.
**Example 2:**
**Input:** m = 2, n = 3, k = 6
**Output:** 6
**Explanation:** The 6th smallest number is 6.
**Constraints:**
* `1 <= m, n <= 3 * 104`
* `1 <= k <= m * n`
| null |
Binary Search
|
Hard
|
378,719,802
|
253 |
hey yo what's up guys babybear4812 coming at you one more time uh today with a problem 253 the meeting rooms problem i'd like to put in a bit of a plug here maybe before i begin uh in that i made a video this earlier this week that i will link down below about how to generally solve these uh meeting room time schedule calendar time overlapper or interval overlap type questions that uh i thought i'm biased i thought it was one of my better videos and i really tried to clarify how to think about these questions in general so if you find yourself struggling with this category of questions check that out again i'll leave it in the description below otherwise if those are mainly okay and you're just like on this one then welcome uh this one arguably i mean is this a bit of propaganda that this is rated a medium could be it could you can argue that it could be a hard one i think that the maybe the intuition behind getting to the solution in this one i'd rank at a hard the implementation may be even at an easy level because there's very little code so i guess maybe that's why i put out a medium either way it doesn't matter i wouldn't stress too much over the ratings um let's uh without further ado i was about to say without further ado but let's clear some of do out of the way by noticing that amazon blue brick facebook and google all really like this question as of recent so i think it's a really good question to go over and well that's over here let's uh let's have a look at what it says we are we're essentially given an array of meeting time intervals consisting of certain end times which are given in a nested array format each of these items is one interval each nested array with a start and an end time and we're told that the start time is always less than the end time so we don't need to do any funky error checking on backwards time intervals or anything like that the ask is to find the minimum number of conference rooms required to facilitate all these meetings in the example here where we've got a meeting from zero to 30 5 to 10 and 15 to 20 we would need two meeting rooms to facilitate all those and i'll walk through that example in a bit more detail in the next page this one maybe is a bit more obvious uh we can get away with only using one room here we have a meeting between seven and ten and one between two and four we can use that meaning between two and four and then reuse it again between seven and ten so the question is pretty short i'd argue it's pretty understandable but again the solution itself might not be all too obvious and here's the reason why let's take a look at this example that they gave us first where the output was two so we're given three intervals of meetings did i miss one no i didn't there were three uh and it's essentially what they would look like whoops we would have one interval here between 0 and 30. so imagine i had almost like a microsoft outlook type calendar with a visual of a block meeting happening at this time and so this here is blocked off between times 0 and 30. the next meeting we have is between 5 and 10. so notice that if we didn't have this third one and i just i kind of asked you and said okay you've got a meeting from zero to 30 and one from five to ten how many meeting rooms would you need you know i think you'd be pretty quick excuse me to point out well we need two because uh you know for the second meeting happens during the first one so i'd agree and then i'd ask you let's think about why that is how is it that you can tell that the second one happens during the first one the correct answer there would be the fact that this the five so we start at five whereas the previous meeting ends at 30. the beginning of that second interval dips into the before the end of the previous interval the fact that this 10 here is irrelevant this 10 could have been a 40 and we would still need two rooms because at some point there is an overlap because of the my current beginning time and the previous end time if all this is confusing again check that link down below on the video explanation on how to go about all these and that will clarify a lot of things anyways we notice okay this question seems trivial for one or two intervals now we introduce a third this next one is between 50 and 20. and if we think about it for a second well the 15 again it cuts into this 30 so we need we definitely need a new room there we can't do it at the in the same room as that first meeting is happening in but what about the second room the one that we had occupied from five to ten well it doesn't overlap with that one does it so strictly speaking we could actually book that same room twice now and have those two non-overlapping and have those two non-overlapping and have those two non-overlapping meetings happen in the same room and so in this case the output that we need is two whereas previously or excuse me even though we have three meetings we could do it with two rooms all right and so let's think about on an even grander scale again even you can argue with an example of only three cases this could be somewhat trivial how would we generalize what just happened here this is how we do it we would check i started with only this room okay i only excuse me this meeting i only started with this meeting and so i had to book a room that'll go from 0 to 30. there's one meeting room required so that means that i had a certain start time at zero and really the end time which i'm going to focus on i'll call it my end time was 30 for this meeting all right then i looked at my next interval and my next interval started at 5 and ended at 10 so because it started at 5 and not something like 35 or 45 we realized that i dug into this because my beginning here was smaller than my end okay so now we need a new room and that end will now be 10. so this one ends at a time 10. and notice that i'm looking at the end times and not the beginning times because when i get to this next interval in 15 i realize okay well i definitely can't use this room but what if i could use this treatment well since this one starts 15 comes after 10 it starts after the previous one ended and we're good we can reuse that room so this one no longer ends at 10 it will now end at 20 for instance now what did we essentially just do we said i'm going to look at my interval my next interval which is this one and i'm going to look at all of the ending times of the rooms that are currently in use of all those ending times did i compare it to the 30 or did i compare to the 10 right i compared it to the 10 the reason that i compared it to the 10 was because i noticed that if there is any room that i could use it would be the one that gets freed up the soonest imagine you're waiting for a conference room at work and you need to know which one you're going to get into next well you could type i wouldn't suggest this in real life but hypothetically you could knock on all the doors and say when is your meeting end when does your meeting end when is your meet again and the one that ends the soonest is the one that you could use that's the logic behind it and so what if there was a way for us to track when all these end and so you can argue okay we can put that in a list and i agree with you can have a list that goes we've got an end time of 30 and we've got an end time of 10 and maybe we got another one at 45 and we can stack up a whole bunch of meetings here the issue with this approach although it would probably time out it would work logically um because you're always checking for that early send time and then jumping in there and replacing that room now with your new end time which would be 20. so this room that ended at 10 which is the earliest ending one see okay cool i'm gonna grab that one and book it off until 20. all right so is there a better way for us to keep is there a data structure we can use i'm laughing because i think you know what i'm getting at it's a data structure that we can use such that this data structure will keep an organized record of our smallest value down to the biggest one the answer is yes i asked ask that question half rhetorically because the answer is yes strict uh not strictly speaking i've overused that phrase already um namely the data structure that we're talking about is going to be a min heap so minips are great for this because they're always going to keep the minimum value at the top and that's what we're interested in using we're always interested in the minimum value minimum being the earliest end time of all the possible meetings that are currently in place all right that's the approach that we're going to take you'll notice one more thing is that here we were we got spoiled we had a zero and then we had a five and then we had a 15. this approach worked because all of our time intervals were sorted in ascending order by start time so i could knock the meetings off one by one as they're coming in as they're beginning and that's what we're going to want to do to actually solve this problem and so that's the logic behind what we're going to do here again we're interested in seeing when is the earliest ending meeting so by default we're going to need at least one room unless we get an empty array we're always going to need one room i'm then interested in when that meeting ends to see if i can hop on in there because i'm the next starting meeting because i've sorted them all by beginning time if i can use that room if i begin after that room ends perfect i'm gonna pop off that room i'm not interested in it and i'm going to push in my own room so i can almost remove it and put it back in the heap however if i can't do that then i'm going to say all right i need another room so and we'll kind of assume there are an unlimited number of rooms here we're not limited to some finite capacity though maybe that would be an interesting meeting rooms three problem uh where we're going to assume that there's no limit to the capacity so we're just going to push to that heap we're going to paint it and simply use up another room when all is said and done at the end of the day we're going to take whatever the sizes of that heap and actually return that because that'll tell us the amount of mediums that we are going to need in order to make the magic happen so i hope that explanation made sense um wasn't too much drawing on this one thankfully which is good because i suck at drawing and writing um but if you have any questions let me know in the comment section down below as always um if not let's dive into the code and see how we can make this happen so as usual i think the first thing we might want to do is some basic error checking we said then that we wanted to sort so sort by start time we are then going to want to create some sort of heap so create heap structure uh we're then going to what do we say next we're next going to have to iterate through the intervals and check to see if they're overlapping or not or whether you need to you know create new rooms so i'll say iterate through all intervals and then eventually we said we're going to return some value and that would be the length of the heap or whatever we're going to end up calling it that's going to be the final value that we're going to return so as per usual let's take it from the top error checking i'd argue just if we have no intervals or maybe even if we have no let's put it this way so we'll say uh if not intervals we are going to return zero all right we don't want to do anything if we're just giving an empty array if we have one we can still go through our logic and that won't really change anything we've then said that we're going to sort by our starting time excuse me remember that the input that we had was a nested array and so this nested part we're going to want to sort by the first element here meaning that i'm going to want to take my intervals and sort them using a lambda function and the way we do that is i think is equal to lambda and then this x will represent any given element you know i can call this interval lambda interval so each one of these items that i'm looking at is an interval and i want to sort these intervals by their first value the one at the zeroth index which is namely the starting time if i wanted to sort them by the ending time for whatever reason this would have been a one all right i'm not going to do d5 into lambda functions in this video next we said we wanted to create some sort of heap structure and what we can do for that is we can use the heap cue collection from the python collections library and so what i'm going to say is maybe i'll do something like this i'm going to say room i'll call it rooms just to make it clear or maybe used rooms and i'll make sure to return that here at the end of the day i used rooms is going to equal some empty array but we're always going to want to start with the like we're gonna have to start with the first interval so we know we're gonna have at least one integral because we're checking for if we have zero and so within those um i'm going to add intervals and again i'm interested in the ending time because i want to only append to my heap the ending time of this meeting room whenever i get a new interval that i'm comparing to see if i need a new room for i'm going to say this is my beginning time here overlap with the minimum ending time of you know whatever that minimum is at the top of the heap so that's how i'm going to start that there i'm then going to say we're going to use heatq.heapify used rooms heatq.heapify used rooms heatq.heapify used rooms to turn this into heap and just for your information you can verify this in the python documentation but as of tuesday october 13th 2020 this operation is done in space so it's all one space and it does so in linear time so it's oven time complexity uh of one space complexity in order to make this operation happen to turn the list into an array this has already been pretty well optimized for us now we want to begin by iterating through the intervals so what i'm going to say is for interval in intervals and maybe what i'll do is i'm just going to interview through the uh from the second one onwards so the one at index one all the way to the end because we've already and we've already looked at this one and what we want to say is this we've got two conditions we've got if overlap else if no overlap and these are the two conditions that we want to work for so if there's an overlap we're going to define it as follows we're going to say if the interval that i'm at if it's starting time is less than the current minimum so if it's less than i guess it's used rooms of zero so that first the minimum item then uh did i get that right we want the starting item to be yes so compare that to the top item of the heap if our start time is less than it then what that means is we need to add to our heap so we need to add to our heap i'll do this one since we want to add the heap we're going to uh heat q dot keep push and we're going to add to the heap used so i'll explain the syntax in just a second and we're going to want to add the end time here right interval one because we're only adding add times to our excuse me tower heap uh the general notation here is we say heap q dot keep push that's the name of the method then we have the name of the heap that we used and then the item that we want to push up so that's how i got the syntax over here now uh i think what i'd like to say is this is maybe we'll say let me think uh if no overlap we'll do it this way so if the and i think this will be a bit more oops a bit more logical to read if there's no overlap then what we want to do is we want to say um now we're simply going to take pq so uh if it will say if interval of zero if it's greater than or equal to use rooms uh i think i'm not going to need this now i'm sorry if this is confusing it does i'll promise to clarify this in a second if our interval is zero so our start time is greater than or equal to the latest end time meaning there is no overlap and we can use the same room also i'm assuming here by definition if uh if a meeting ends at 10 and my meeting starts at 10 i can use the same room okay if this is the case then what i'm going to want to do is say see he is i'm going to want to say heapq.heap say heapq.heap say heapq.heap paw and we're going to want to pop from used rooms so we're going to take that minimum element and pop it out because we don't we're by essentially reusing that room what we're going to do is this is after i pop this item out i'm then going to push in my new one since i'm it almost seems a bit counter-intuitive because we're bit counter-intuitive because we're bit counter-intuitive because we're saying well you're going to use that same room right and this is true in essence what i'm trying to do is this is if i'm going to reuse that room i need to change that top element the one that ends the soonest so i'm going to pop that one right off which means my overall number of rooms used is going to decrease however i'm going to push something right back on immediately that thing that i'm going to push on if that is now the minimum end time it's going to be pushed up to the top of the min heap by this function that is heap q dot keep push function python takes care of that for us if this is not true so if there is no overlap i'm going to delete this here if there is no overlap uh oops sorry if there is no overlap we're going to jump into this we're going to replace the one for one we're not increasing our total amount of our total number of rooms used however if there is an overlap we're not going to jump into here we're going to need a new room and so this you know heat push we'll just push up a new item and it'll increase our total number of rooms by one and that's the reason why i'm using this i'm popping off only in the case that there's no overlap because i'm just going to replace them and use the same image replaced at times at the end of the day all we're going to do is return the size of the heap and that'll tell us how many rooms in total we need to use i'm going to run this code and see if i locked out cool we did something right so that worked and closes back down so you guys can see the code more clearly awesome so just uh just to recap on everything we did we noticed that we can compare if we sort our intervals in order from start time to end time i need at least one room all right of course if we're not giving this to this empty list i need at least one room to then check if i can use this room i need to ask hypothetically all the previous rooms all the rooms in use and say hey when are you ending i'm gonna jump into the one that ends the soonest without having to iterate through a whole list of these rooms over and over again or rather in order to avoid doing that we use a minimum heap right in python the default is when you're doing heat cue.heapify will when you're doing heat cue.heapify will when you're doing heat cue.heapify will create a min heap by the way if you wanted to create a max heap charge i'm thinking here when you push an item off the maxi this is a good trick so you want to create a max even you're adding these numbers and the minimum ones float to the top just add every number as a negative and if you add it as a negative it will still be a min heap but now when you pop numbers off if you need to use them just make them negative again so that's how you flip it around but anyways that's a side point as i was saying we create a heap and then for every single interval i'm saying if there's a room that i can use if it's potentially free if that minimum ending time is either greater than or equal to my starting time the one that i want i'm just gonna replace my time with that one so take one out put it in there's no change to our total number of rooms take one team i'll put the other one in however if they're all being used i need to add a new room and again we have an infinite number of rooms here so that's not gonna be a problem that's it for now i hope that video makes sense as always if you have any questions uh let me know down below i'm getting hungry i'm gonna go have dinner before i do that don't forget to like comment uh subscribe and share all that good stuff show all your buddies they're going to be really impressed with you because you're doing nerdy things and that's always good to help thank you friends see you guys next time peace
|
Meeting Rooms II
|
meeting-rooms-ii
|
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** 2
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 104`
* `0 <= starti < endi <= 106`
|
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied.
If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
|
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
|
Medium
|
56,252,452,1184
|
946 |
hey everybody this is Larry this is day 13th of the Lego day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem oh yeah once in a while you see me check this page and sometimes even successfully because on the upper left side you see unbox surprise click on it and you should get 10 coins Yay hopefully you also got 10 coins today uh let's check out today's problem then validate stack sequences uh seems like it is another stack problem so let's take a look it's a medium 946 hopefully unlike yesterday I don't make a silly mistake on the reading but uh given two individual ways pushed and pop each with distinct rows return truth this could have been a result of a sequence of push and pop on an initially empty stack of force otherwise okay yeah um I'm trying to think whether it always makes sense to greedily pop when we can um I guess these are unique numbers right distinct values okay so if these are distinct then you really only have one time to pop it so I think that's really the only thing right the reason is because if you don't pop it down and you're pissed pushed you push another number instead then you'll never be able to pop that number because you can't go from left to right um because like you can't pop five ever because your next number is four so it's gonna be gradient that way and I think that's really the idea uh yeah so let's set it both end same size I guess so and then basically maybe an i and a j uh and then well I is less than n with I in command maybe description a for Loop bit but yeah um so then we have a stack I forgot so we always push this number and then while uh pops up J is equal to the top of the stack and length of Stack is greater than zero of course then we stack that pop right otherwise we just return length of Stack is you go to zero because it that means that everything popped and we're all good you can maybe also just try to see uh well I've actually messed up here you need to increment by one you can also see if J is equal to the end or something like this uh but yeah should be okay get started yep pretty quick uh why do I get the wrong choice before hmm oh I think I just totally misunderstood this one then that's really weird but today I understood it pretty okay so that's all that matters for today uh yeah so where's the complexity here this is gonna be linear time Lenny uh yeah linear space because you need linear space to store a stack hmm linear time because you look at each item on pushed once and also pop once which is all of n uh times two which is also event anyway um yeah I don't think I have anything else to add to this one let me know if you have any questions you want to add to this one I'm going to call it a day I'll call it at night um really poop today uh just tired anyway but yeah stay good stay healthy it's a good mental health I'll see y'all later and take care bye
|
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 |
708 |
hey guys how's everything going this is chaser who is not good at algorithms in this video I'm going to take a look at 7:08 insert into a sort of circular 7:08 insert into a sort of circular 7:08 insert into a sort of circular linked list we're given a node from a circular linked list circular okay which is sort in ascending order 1 3 4 the function to insert a value insert vowing to lift such that it remains a solid circle list while ascending what it means there is unique right it's no there's new no duplicate the given node can be rough any reference and they may not be necessary the smallest one so the head may be any anywhere if there are multiple suitable cases for an insertion I might choose to any place inserted okay after destruction is circular this should be remain running sword ok if the list is empty I should create a new single circular list and return the reference to that single node otherwise I should return the original given node why looks like sim looks like easy looks like very easy let's start with this linked list like 1 3 4 go ahead is 3 so the first I think so if we want to insert a vow you must between some nodes right insert here or here so we can just take a look the first node we just with head and that we keep another point pointer to point to 4 and move these two pointers together so each wall moves through 3 4 1 and 1/3 right so 3 4 is through 3 4 1 and 1/3 right so 3 4 is through 3 4 1 and 1/3 right so 3 4 is the first one it's ascending 3 4 so we check if this too is in it's not because it's not we move to next one which is 3 4 1 all right it's descending so which means this is the last one right if this last one if it is smaller than 1 then we should be put here or you speaker than 4 it should be put here but 2 is not to dispute than 1 so still we will move to the next one which is 4 we check through 1 & 3 right which is 4 we check through 1 & 3 right which is 4 we check through 1 & 3 right so 2 is freaking out was 4 3 so we insert here well it's done so with two pointers we check this Wendy this one is this French so we will check until the point pointer ahead Mets the head right that's the full circle okay if we insert the value there must be some as a wrench we can put them in all right even it is to two notes like a - like a three for when you start to the - like a three for when you start to the - like a three for when you start to the first we check three for not in it and then we check for three this is the end right two is more than three so we insert it here cool but what it what do you what if there is only one known like three Wow four for one note it doesn't matter you insert before it or after it because it's only one no and it's circular so for one node we will create a node and just connect them there's no problem and if it is M if it is empty we create a node and the point ponents itself cool so we need handle special case for zero and one note case for the others who believes you look through the circular list where the two pointers right okay so the idea and those special case for then 1 0 and 1 0 1 but we don't know it is right it is know what we know but how we know it is there is only one node what cut we can check the next one is the next one itself yeah cool so ok and then if not we could use two pointers to on your to cursor okay to move through all the ranches or the spaces between nodes we have it check if it is ascending if the space okay the ranch is ascending check if insert valve for them in between if the ranch is descending then check if insert bow is smaller than smaller or bigger than bigger eager right okay let's do it so first one we need to create a note first I'll create a note read the note to insert a new node mr. Bao next is no I think we should just quit pass has a more special case if head is Lu no next it was no return note right and you've had next equals head which is the one or case we just insert it at next equals no the no next it was head and returned head now it's let's look through the ranch's let P whose head let P next equals head next right this world ends when we went when will it end well this is the last case which means P max equals head right so which one ends when P again okay so we P okay we can use do Wow right first we check it but do it and then if this one if these if this one oh no activates mmm how can we mark that piece end it this is P next this is B he next okay ap next if you just do a while we first we check if it is and then move next one right and then we can check if P is head because we move it's not head again and it was forehead okay so we I can't think I think we should use do well here okay do while P is not equal to head right yeah cool we do when you walk we check if FP if it is ascending as we said if P next equal if P next is bigger than P no it's tau is bigger than P Wow Pizza if it is ascending possible range to insert so we if the insert file is bigger than PL and insert pal swollen P next well right if this is target okay we do the insert and break right don't forget to break and finally we will return the head so we will do the insert it's really simple piece next equals to no right no next pose P next and the insertion is done we break return but so if not none of this happen you go move to next one right so P next equals P next or next P equals P is texted if it is descending then there's a case I will shoot inside here so if insert valve it is smaller than P next or insert file is bigger than piece next a piece bow as we said if this more than one or bigger than four that's odd post the be the yeah that's the same rent for two different cases okay we will do the same we insert it so he next equals new node in x equals node he knows next equals P next and break well I think we could just merge this case right I'll say okay create one insert between it pulls no okay I can you say insert actor from a target so we do what connects equals from the next right next another from the next equals target next equals next yeah so we now here we could do insert P node and here should be the same okay and I think that's done let's try to review our code before we submit the idea is simple we loop through the ranges because if you want to insert the note it must be between some wrenches and to move through the ranges we could use two cursors and keep moving these two cursors at the same pace right okay we have this special case first if this new or returning the node and which points itself else on one node we just a pen just pin it like hair next no snake's head return we're asked to return the head right there is no all credit in other words between the original node we said cool now okay sure there's a typo here and now we will loop through it we start with Pete at the head and legs these next one we well first we check it and a movie the forward because we need to stop when the P come back to head so we used to well do-while loop P when P we used to well do-while loop P when P we used to well do-while loop P when P is not helpless can't continue moving and we found two cases when the rent is ascending it might be a possible wrench to insert the node so we compare it if it is anything indeed it is causing the ranch we insert it and if we found something descending that means the ranch actually is the very beginning and the very end right so we compare if it is should be the beginning or should be the end if it is we insert and we move to the next be bows to the next one so I think it should work it's cool let's see the empty case like for one and if we won until cool I think it should be accepted yeah the problem there will be a hmm there is this miserable duplicate but man you told me that it's ascending if it is a if there if it is there might be duplicated it should be you shoot me what it's a non duplicate okay this is my mistake I should clarify this problem with the interview first well if you're using a ray it's not gonna be a problem I think I have done the video called implementing the lodash sorted index in that video I explained how we can search the first index of some duplicate ascending sorted array and the last index well it's not that difficult so for these for this duplicate problem if you're going to insert there might be duplicate so we need to change the compare here alright we will actually insert a first appearance of what before if before itself being the first index right so not right not strictly smaller than but if it's bigger than but equal if it is equal then it's cool or it's bigger than equal to it is equal to a and then if it goes to it we can still insert if it's bigger than it is whatever so neither if so we just change the ranging to inclusive right so how about this descending case of course if it's uh it's still inclusive I think yeah I think this should solve the problem right this is this man I should clarify the input cool submit still hmm we have a bug ah three four we get three zero three four but we should get three four five zero what happened we got three four five mm-hmm because Allah peas Val and five mm-hmm because Allah peas Val and five mm-hmm because Allah peas Val and he next of that we first checked three and ah yeah man the there are more cases than this right it is ascending you could check it equals two it becomes this one right if it is equal if you are equal to it there might be if it is all equal the man there might be the problem right okay I actually say if it is equal should treat as ascending yeah you should fall in this one right but yeah and yeah there is a problem we can check this but there's a problem that there might be all the same and this while loop will not find a suitable index for it right so now we say if P is equal to head if not inserted means all nodes are the same but I'm saying but not insert Val because if they're all three and we insert for which just keep looking we don't find any good any place to insert right so for this case I can insert anywhere it's fine so I will do it like insert after E and then the node this should work right hmm cool submit still what we've got one three we've got one but there's the moon really this is disaster man I lock it okay we first we search for one three okay and we found it right research tree falling this part yeah so we insert it and break ah the breakout first so we insert it again man this is not cool mmm how should I do it we start searching here if you found braked peoples here and then we check it and they dopey actually fall and at this case so nothing is found I need to differentiate these cases I think I need to how should I do it I think I need you updates the link to before we do the insertion no I should do it after that should the after or I can update do the check before the quality it was stopped when P falls dead before us here right but actually we could continue could stop this actually before when the P next well the PX is had it's actually already know it's gonna it's yeah you already know it kind of fail so the movie little backward if P next is head and we don't find anything okay we don't know them here not Q so P actually now set in their head right when we said head and it's different from start with head right because when we start at P now because for but when we go to three P actually will be set to three so we check here if P equals 2 hat then we come nothing is inserted so we insert P after P note because P we're gonna kind of be in the head this would kind of be break its gonna break and yeah I see my suit seems too good to look good hmm the console find anywhere except it well this is actually not that simple than I thought it's come more complicated and one trick is to do well the next one is checking Oh in total the basic problem is about the ascending and the unique uniqueness of the link list we're not clarified with that thing so I think which think I think we should clarify that from with the interviewer it actually makes a huge difference about how we're shooting for implemented while the basic guy doesn't change the created note we will check the special case and then do through the all the branches and check yeah if you unique we don't need to care about the equalness but for in Mount to placate one we need to check this right and there's a last case because they were might be to blink is all for now we saw three with this it's gonna be infinite loop and I'm not the node it will not be inserted so we need to insert a class well it's not that complicated after reviewing it but yeah there's a little tricks and let's try to see Oh No let's try to understand the time and space complexity for time of course we were just to look through all the notes for once right so yeah in your time space mmm nothing special so customer let's see if we can learn something from the solution I have to be honest I never saw us saw the solution page to point us yeah I think we're doing in this yeah Wow it's lon o to see head mm-hmm o to see head mm-hmm o to see head mm-hmm do while the same case three I think he use a different one different approach so he could be able to put the next like this Wow about I think my solution is pretty easy to understand well for myself maybe a little verbose but I think it looks good so that's all for this one happy helps you next time bye-bye-bye-bye okay you see you next time bye-bye
|
Insert into a Sorted Circular Linked List
|
insert-into-a-sorted-circular-linked-list
|
Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value `insertVal` into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list and may not necessarily be the smallest value in the circular list.
If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted.
If the list is empty (i.e., the given node is `null`), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the originally given node.
**Example 1:**
**Input:** head = \[3,4,1\], insertVal = 2
**Output:** \[3,4,1,2\]
**Explanation:** In the figure above, there is a sorted circular list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list. The new node should be inserted between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.
**Example 2:**
**Input:** head = \[\], insertVal = 1
**Output:** \[1\]
**Explanation:** The list is empty (given head is `null`). We create a new single circular list and return the reference to that single node.
**Example 3:**
**Input:** head = \[1\], insertVal = 0
**Output:** \[1,0\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-106 <= Node.val, insertVal <= 106`
| null | null |
Medium
| null |
218 |
Hello everyone welcome, my name is Himanshu and C.R.A.T of September Daily Challenge so and C.R.A.T of September Daily Challenge so and C.R.A.T of September Daily Challenge so come friend let's see today's question what is it so brother the name of today's problem is D skyline problem and R this van of it kind hai brother it was fun Come to this problem friend, let's see what is there, if you do n't see it here, let's go down and see you. Buildings are given whose start coordinates are given, end coordinates are given and its height is given, one is given, like this is the air of the building, so see zero van, you start koordinate, its 9 and height of the coordinate is 10 and you have the skyline. This skyline has to be made, meaning if you are watching my video from here, then see this line is done, this particular thing means the boundary has to be outlined, okay, one height has changed here, so see one idea one. The idea is that it changed here, then the height changed here, it will remain here again, it changed right, it will remain again, then it changed right, then you have to return these points where this height change is taking place. See, I understood the point. My only question is that you will have this air gun of buildings and you have understood the point of skyline to return these points and friend, let's take it on our screen and as soon as we understand how to do it, then friend, here is my skyline problem, I have a Input has been taken, listen, if you read this question, then it may happen that you have to understand it in one go and friend, this is not in this problem, it happens in many problems, so friend, I will tell them how. Listen, there is an approach which I follow, whenever you have to do this, if you are not able to understand the question, then you start forming the form corresponding to the input of my input, what will happen with it brother, two things happen with it. Firstly, you get the full form of the question and secondly, while doing the output form, you identify the approach, you understand, it is very helpful, friend, so friend, this is the input given for this question, we start doing the output form, okay. Hey, go, let's start forming the output once. Let's see how it helps. So look, I am standing here at zero, man, take me, I am starting to form from zero. You have made me a skyline, so I am starting to form from zero. If I am moving forward from zero, how far will I grow? Okay, the first building is on you, so I came on the 2nd, my height is changing on the 2nd, so brother, my height is changing, so the skyline is on you. How many? Height brother, 10 height is fine, I went ahead, where will I go next, I will go ahead on three because my new building is starting on three, so I kept walking till three, my height is changing, so my skyline will be 15 again. Caught an observation First skyline only van height change Write these observations on the side I rub this Okay, it will be fun Don't worry Okay, I came at 15 I am starting to move ahead of 15 From 15, I am starting to move ahead On which floor will I come, why on five, brother, because the next building is starting there, so I came on five, so I am bigger than 15, ahead of three, I came on five, is this on five, will any skyline come here, why not here because there is overlap It is happening, look, it is overlapping, there is no skyline for this building, there is no skyline for the green building, ok brother, I have gone ahead, where will I go next, look, here I am at 7, one thing is clear, I Came from 5 to 7, it means second, I am driving, driver on sorted When there is a change in height, I will go straight, so here is the height change, where is the height change, how much is this, 12, that's right, now I went up here, what is the next coordinate, 15, then I came to 15, then at 15, there is a height change. It went from zero to zero, then it came to 15, then the right changed, how much would it be to 10, sorry, it became 10, so I went, it kept increasing, now look here, the next building is starting from here, that means from 19 onwards. Was this building not finished in 19? Brother, if this building is not finished then this straight line will go to Puri. Till 20, till 20, the straight line will go only till 20. So I understand that when the buildings are overlapping, look, when the buildings are overlapping. Whom are you taking, look at the maximum, so I am writing the third observation here, overlap when building overlap, skyline is formed, only tallest building forms, only building with mate, that is correct, so look at the skyline, it is being formed only here. Only here the tallest building is being built, there is no problem. If we move ahead, till 20, it came down to 20, where did it come to 20? It went straight, went on and ended at the last. At 24, it is ending at 24 and here it is. Answer, this change has happened, first from here brother, start from zero, we have done it but actually it will start like this, then this point, if we take any other color, then this point has to be given, this has to be given, then right here it has changed. I have to give this one and this one, this is your answer. Is it correct? So you understood what I did. I just did the output form corresponding to the input, so what did I get to know. First of all, I liked the full question, what I had to do was that. It became clear to me from here that I had to make a skyline and look at the second, we have filled in a few approaches, that's right, now friend, I write these approaches well which we have identified, okay, I write these observations well and Then let's see what we do next. Hey, see, my friend, I taught you how to approach such problems. Now listen to one more thing, friend. Either the building will start or the building will end. That's right. You want me to know this. I need to know where my building is and why brother, so that I can remove the building that it is mine, now that is correct from my observation meaning start, there is no problem, install this thing and see the first observation whenever the height changes skyline. When the form is done, I realized that I have to sort the input and the third building overlaps, if the building overlaps, then we think maximum, what is it giving, it is giving to me, brother, make max the priority, enjoy. And the third thing we found out is that we have to divide the input into two parts, start and end, we have had fun, so come on, let's start building the solution because now we have got the data structure. Now we have got a direction how to go, so come friend, let's start building its solution. So see friend, you have raised the same question, the first thing we do is first of all we divide the input device, start and If we divide at the end then it will be done. Now listen carefully, 350 and 35 are starting, so how will we know for that, listen for that, how will we store it, we will write start, earn this left, this is this left, if it is true then it means this is start. So it means this is the end, are you understanding what I am saying, you are understanding what I am saying, okay, now apart from this, I also want it to have a responding fight of the start key, I mean only the height, so I If I have to keep a height also, then I will have to create a new class. That's right, I understand it brother, first I have to put a star, start means coordinates, no start and end even matter, then I have to tell this left time, which is told. The key is start and end. It is okay and in the last I have to put the height so that I can know the height. It can be determined through particular coordinates whether it is the start or the start. I understand why it has to be made, why it should be clear brother, why is it very important, okay? Now there is another way to do this, listen, I do n't have to make this left so that I have to make a class also, I can do it in one leg by making a class, it is definitely possible, if I understand that approach. If you don't know, then I would have made a class, it is correct, then listen, what should I do, I will make one leg, coordinates, earn height, when I start, negative, if it is positive, then I know that I have understood, if I have understood then see how it will be stored. You listen Play Store how will you earn three in three earn mines What's next mines 10 20 How did we reach here Okay ok now listen to the next thing Driver can do everything in this So much understand how will you driver I will store it in a vector I will give them the vector of mind in the foot and I will drive them. Have you understood? Now we have reached here, we have completed two steps. I hope you have understood till now. The length of the video will be very long because we are very good and You are asking very proper questions, understanding the structure, so let's go ahead, see friend, we have performed two steps and we have shorted the input, we know that we have to drive in it, we have to traverse in it, okay now let's come. If there is overlap then what do we have to take for the back side and what will be less for the back side? Because who will be given priority? If the maximum height is given priority then it is 10 height here then see it becomes zero here 10 height has changed if it is Han Bhaiya then height in the output. Group two happened on these coordinates and the height is 10th. That's right, there is no problem, it's start, brother, so brother, put this inside 3, earn, sorry, it is bigger than 15, it is definitely bigger, 15 A will go to the previous site, 10 will become 10 and 15. This is different, if there is a change in height here brother, then this is also a party, if you give it 3 then earn 15, it is correct and update it to 15 mines, what is showing is the start, so I went inside, will you be on top in this, is there no height change, brother, 15-15 If it is, then it will not be understood. brother, 15-15 If it is, then it will not be understood. brother, 15-15 If it is, then it will not be understood. How is it going? Only when are you taking it brother? It is changing, so look, if it is from 15 to 15, then I did not take it. Now listen, this building has ended, so if that building has ended, then If you make that one fly, then make that one fly, this 15 will also fly here, the 12 one here is different, now this height has changed, so put on which one, what is the change in height on 7, what is the change height, have you understood, see, on seven, here. But what is the height of 7, 12 is the right thing, here's the thing, how are we going on next, nine com, 10, brother, it is positive, it means end of D building has come, eg two kiss ko udna height. On 10, Uda Diya, what has changed here? Oh, there has been a change here. Come on first, Uda Diya, what has happened to me? What is the meaning of MP? Have you got a gap here? So what is the difference here? If it has become anti, then make it zero here. But if there were two parties then brother, this particular coordinates means it is ok on 12, there is no problem, brother, it is start, put 15 here, that means it will go to 10, then what will be the answer, then see the height has changed, the answer will come to 15 coordinates. The height changed and at 10 it is correct, there is no problem, let's go to the next level, what is this here, mines means start, this is the start, push in it, 890, is it bigger than this? No, 10 is not bigger, so hey height. It was 10 here, keep updating it was 10 on Hitech that 10 in 10 is from Han Bhaiya, nothing will happen, go ahead, 20 com train bhaiya is positive, what does it mean, it is visible, it is over bhaiya, a building is over. When it is done, show it to the building. Show this building. As soon as it was picked up, it came here. Height is different. So brother, put on which coordinates it changed. 20 What is it brother, see, it is correct. Let's go ahead on 24th, I am coming brother, it is positive and A is done and A brother, it is positive and A is done, so what should I do with it, don't end it with zero on 24th, it is right, it can be thought, let's bring its output once and see. So look friend, here is its output, look carefully, you earn time, here is 208, here is 248, here is the finish, did you understand how to build, what is this, your own, did you write your own algorithm, did we not follow some procedure and on whose basis? We have written on the basis of observation, now what has to be done, we have to implement it, so come on friend, let's implement it, so friend, now we have come to our coding screen, so let's code it, so first of all what has to be done, first of all What we have to do is separate the inputs, let's increase it a little bit. I like the lead code. Separate the inputs. Okay, so come on, let's separate the inputs. First of all, I will create a vector. I told you about the leg of this. Mind and I am naming it coordinates, okay because I am going to keep coordinates, so I will do driver in for auto i buildings, so see two ways and okay, so what will I do, if I have to push my foot, then start, if there is start coordinator, it is correct. There is no problem, go, what to do now, how to put the end coordinator and the height will remain positive, then he told me that it is the end quadrilate, okay, let's write it here, okay, ours has become so low, now what? What has to be done is short, there is no problem, what have we done after this we will make third priority, so whatever we make, priority, no problem, okay, go, friend, let's go ahead, coordinator in our coordinator. If I do n't have any problem then X comes out. What is Remove dot from particular position, friend, end usko and pkr top, it is not equal, you height, so what to do, give us group, Pushpak will become equal, back then see how we will finish I, there is no problem, now I understand, listen now, what do I have to do, answer. Let's see what is the return vector of vector in the answer, now I will do if my what pq.met becomes PK then what is this pq.met becomes PK then what is this pq.met becomes PK then what is this signifying, this is signifying that what is my height, look right here. There will be zero right here Zameer height will be zero so what does it mean in the answer what is the number two in the answer how to make the answer we have coordinates okay answer dot push back in coordinates in x and what is the height of height zero one minute Not like this, I will check the x common zero, now when will we put it and how will we check the height change and after putting this, update the previous site, equal, you will put the dot on the top of the p, so come friend, let's run from now, see what came. Our beloved everyone's beloved tiliyali, on whom did the total come, how many days, see, what is the time complexity of this, see one, this loop is going on, what is the time complexity of this loop, you are of this group, see, I am telling this in two parts, one start. And in one end, that's why it is running 2 times and in priority, the people inserted in these takes time, remove the time oblique, brother, it is done in one second, you have understood my point, now let's see what it feels like now, listen, where does it feel to be an experience? Now I can give you experience. You are understanding my point, how to think, how to move ahead. If you are understanding, then what should I do? Friend, the data structure that is in my mind is Multisite. Read a little about it. Still, let me tell you what a multisite is, it is like a multisite set, what do you do in it, duplicates are allowed in it, first of all, it is an order means it is sorted and not sent, so come friend, let's improve it. If you are using multi set then I give priority to it, comment everything till now, no problem, second solution is using multi set, very cute solution, ok, leave it friend, I have taken it, then what to copy, only you know, I only What needs to be changed there, let's create it till now, remove it, make a multi set, look, insert it, shorten it, the site is fine, there is no problem, we have to optimize this only, what do we have to do in others only? Look at how direct it is. Raise st.find, it is fun to understand the particular height. It is fun for you to listen. Now this upper line is empty, see how I will write that too, I could have written there also, what will I write here, current height. Let's go once. Okay, so sorted means here the minimum is kept, here the maximum should be in ascending order by default, like taking the maximum height in priority, where will the maximum height be found in the end, then see how the maximum height is taken, understand these things, friend, this is an interesting thing, where is this? It will point exactly at the end, I do n't want to go there, I want to go to one less, then Minus and this iterator will return, I want its value, so I will star here, point to the end which is out of index. So I added one mine so that I go to the last one and steering will return. I made iterator star so that I can get the height. So look, I have got my current time. What to do now? Now this thing has to be implemented. If previous site is not equal to current time, the code behind is the same, I have just changed the data structure so that my time complexity gets improved, so I have kept the answer as dot push back, whom will I push in the coordinate x and current height. And when I leave from here, i0 will not come for 1 minute. To whom is it pointing? It has already been submitted. I am having fun. Let's discuss its time complexity once and then see. Then see, its time is going to remain the same, okay? I have improved this here, so listen to the multi set which is there, inserts erase find, all the operations are going on in these, it is correct, how many times are they going on, 2 end times are going on, is it correct, so see, its time is you and you people. I am busy in soaking you, that's why I got accepted
|
The Skyline Problem
|
the-skyline-problem
|
A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_.
The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`:
* `lefti` is the x coordinate of the left edge of the `ith` building.
* `righti` is the x coordinate of the right edge of the `ith` building.
* `heighti` is the height of the `ith` building.
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`.
The **skyline** should be represented as a list of "key points " **sorted by their x-coordinate** in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.
**Note:** There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]`
**Example 1:**
**Input:** buildings = \[\[2,9,10\],\[3,7,15\],\[5,12,12\],\[15,20,10\],\[19,24,8\]\]
**Output:** \[\[2,10\],\[3,15\],\[7,12\],\[12,0\],\[15,10\],\[20,8\],\[24,0\]\]
**Explanation:**
Figure A shows the buildings of the input.
Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.
**Example 2:**
**Input:** buildings = \[\[0,2,3\],\[2,5,3\]\]
**Output:** \[\[0,3\],\[5,0\]\]
**Constraints:**
* `1 <= buildings.length <= 104`
* `0 <= lefti < righti <= 231 - 1`
* `1 <= heighti <= 231 - 1`
* `buildings` is sorted by `lefti` in non-decreasing order.
| null |
Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set
|
Hard
|
699
|
76 |
hey everyone today we'll be solving lead problem number 76 minimum window substring okay so in this problem we are given two strings one string is s second string is T and we have to get some substring of s which is of minimum length that is going to contain this T that is all the elements of this T is already present in this H Das let's also have a look on this paragraph given to string s and t and length M and N respectively return the minimum window substring of s such that every character of T including duplicates is included in that window and they're also saying that the answer is unique that is for that minium length we are having only one subring let's try to understand it using an example here in this example this is my string and this is my T string and I have to get any substring of it let's say if I try to generate a substring let's a d o b e c if I have a look if I zoom it out a d o b e c this substring is containing all the characters of this d a b and c is already present here it means that this is a valid uh string but this is not to be of minimum length and if I try to let's say further look for any substring of minimum smaller length let's say we calculate this check for this B A and C here b a n c here we have a b and c but length is four Which is less than this which is having six length so here if we have any substring which is of smaller length of this then we are going to consider that otherwise this is going to be our answer so here this length is minimum and this substring is containing all the letters from this T so what we have to return from this Pro uh function A B A and C this Subs we are going to return okay I hope the problem statement is clear to you that we are given s and we are given T and we have to get any substring of s that will contain all the characters of t and it should be of minimum length Okay because if we are going to consider this whole as a subring that is also going to contain all these character but we want s to be minimum length this problem statement is now clear to us and this question is a very important question of variable sliding window approach and this question has been asked in many companies almost all the ti one companies and the Facebook has been asking it several number of times for the last 6 months and as for the constraints they are saying that S&T constraints they are saying that S&T constraints they are saying that S&T contains only uppercase English letters okay and going from 1 to 10^ 5 and they okay and going from 1 to 10^ 5 and they okay and going from 1 to 10^ 5 and they are also saying that we have a full of question for you we will come on it later on so first of all we have S we have t let's say we have SS a d o a o is our T and what we have to do is we have to find substring of it so what can be your Brute Force for this our brute force can be generating all the substrings and after generating all the substrings we will check whether the t is containing is that in that substring or not so that is our simple brute force from this string we will generate all the substring and we will check every substring whether the frequency map of that substring can contain the frequency map of this T simple so for this T if I try to make a frequency map it should be AAL to 1 * or equal to 1 * this to 1 * or equal to 1 * this to 1 * or equal to 1 * this is T string map frequency map of T map okay so to make a frequency map it can be in order of M if it is of M size it is of n size let's say for generating all the substring what is the time I'm going to take if I have to generate all the substring of length one how many substring I can have n if I have to get generate all the substring of length 2 I have n minus one substring if I have to generate all the substring of length Three N minus 2 if I have to generate all the subring of length five or you can say n it is equal to 1 the string itself and how we are going to generate all the substring using sliding window not by generating the boot force of the Brute Force we will use we will be using sliding window to generate all the substring it means we are using end time for all of these uh length and how many lengths I'm having or around n so in the N sare time I'm able to get all the substring and while doing the substring I will keep on checking the map with this and as per the problem statement we are given that we can have only 26 uppercase characters and 26 lowercase characters so in total 52 so n² into order of 52 so this is going to be the time complexity of my Brute Force approach let me also quickly show you the code for that first of all what I did is captured the frequency map of T string after that what I did is I checked all the length and here we can also add do some add some kind of pruning we have to check the substrings of s and what size of substring do we have to check do we need to check one size substring no we will our substring size should be at least of T do length at least of two size because if we are going to consider if we are going to check a substring of length less than T do length that is not going to give me answer so I will be checking all the substring of length this to this and for every substring I will be checking the map if the map of the current substring can contain T dot do map that is temporary map the map of our T string if that is the case it means we have our answer not just the possible candidate for our answer we have our actual answer because we are starting from length smaller to bigger in this way if we are able to get a smaller answer we don't need to check for a bigger answer because in the problem statement we are requested that we have to get a substring of minimum length Okay so this in this is the Brute Force approach in the order of ncare time so I wrote this code I will be adding it in my description below and but this code was giving me tle I thought it would be submitted but it is giving me tle and then I have had a look on this followup question that can you figure out an algorithm you can solve it in order of M plus n time I was able to get on this solution quite easily in the first go I this approach came to my mind but later on when they asked for the approach order of M plus n time that is length of both the strings string of s and t uh that was a bit tricky so for that I try to wrote the code but while writing the code I experienced a lot of difficulties while maintaining the corner cases and once I submitted the code I had a look on the editorial and in the editorial itself there was a mess of code so that's why this problem is hard because the code is containing a lot of challenging edge cases so let's consider the same example T is a o and string is a d o a o okay and we have to get the answer first of all we need to know that uh we have to get T that is the count is equal to length of T which is two that is we want two good elements in our answer two good characters in our answer or you can say if I go if I'm going to use variables sliding window in that window I want two characters from T and apart from that let's also prepare a map a is coming one time o is also coming one time this is a frequency map now what I'm going to do is I'm going to apply our variable sliding window approach so first of all my I and J both pointer are on the first or zero index I will be in like expand expanding the sliding window we will be following two main steps we will try let's say we are here I and J we will try to expand our window until we get the count zero that is if we are expanding our window we are adding some elements if that element is also present in D it means that element if let's say I have added a to my window it means a is already present in the D now the I will be reducing the count by one that is count is the number of element I still need to add to my window so let's say here if I reach J equal to here I equal to here and I have added sufficient amount of numbers from T let's say I have added four characters here in which two characters are a and o it means the count uh count the number of characters I further need to add in is zero so it's a valid index or this is a valid length now if I have reached the count equal to zero that is our sliding Windows giving me one candidate and answer I will try to shrink it down because I want the minimum substring if I try to shrink it by one unit I will again see whether the count is zero that is I do not need any further element in my window if that is the case I will update the minimum length I'll will try to shrink it out let's say I is here and J is here and here we have only two characters which are a and o so this is my minimum length Okay so we will keep on adding elements until the count is zero and if the count is zero I will keep on reducing the element if the count is not non zero I will again try to expand it further in this way this our variable sliding window approach is going to work okay let's have a look on this approach as well let's zoom out this portion a d o a o this is my S and what is t Is AO here count is equal to 2 that is two element I have to add to my window sliding window and what is map a = to 1 sliding window and what is map a = to 1 sliding window and what is map a = to 1 or o = to 1 or o = to 1 or o = to 1 this is tmap so initially I and J was at zero so I added a to my window and after I added a that is i incremented j it that is I added a if I have added a it means I do not need 1 a I can reduce the frequency of a to zero that is these elements I need to add to my window so my current window is a and the count is one that if one more element I have to add okay if I again add D that is J is incremented to this one d is not going to give me um some value because D is not present in T So D is useless to me just keep it like this if I add J at o if I increment J and reduce the fre frequency of 4 the count of count will also be reduced from 1 to 0 it means z sorry o was a valid character and if I added o to my window my sliding window so far is a d o j is here I is here J is always one unit ahead of this element I currently added okay so here count is zero it means minimum length is three earlier it was plus infinity okay and minimum answer is a d o this is my minimum answer now what I will do is as I promised earlier uh I have reached to my specific sliding window where count is zero that is I have all the elements from T to this window now what I will do is I will try to shrink it down and I will see I whether still I'm having all the elements or not so let me increment I from here to here I have to Omit a but a is a element which is present in t so I have to increment 0 to 1 and as it is incrementing from 0 to 1 I also need to add one here that is I removed one special character that I might need in the future so here the count is not equal to zero so we are not going to capture that in this case we have to shrink of or expand our window till the count is not equal to zero so I will be expanding my J2 here and adding a to the sliding window and J is here now the window is d o a is again reduced to zero and count is also reduced to zero if you are not able to understand anything just comment down below we'll have a discussion further on so now J is here so n in the D OA DOA is of length three length is already captured so this is not a very big deal for us we'll try to like shrink it down so to shrink it down I was at D I will be at I and J is at o I will be at zero and J is at a so whether uh what I will do is whether I will see whether this o a is giving me answer or not as I omitted d i omitted d is not a valuable character for us so our temporary map charact temporary map will be intacted count is will be inacted so still J is here I is here so still my count is zero if the count is zero yeah we are going to capture the minimum length so minimum length is will be reduced from 3 to 2 minimum length is equal to J minus I because J is always one unit after my U character so two at two we are capturing O A so OA is going to be my answer so if you want to try it out further you can do it in the same way otherwise if my minimum length is equal to the size of T in that case we don't have to move further because the minimum length cannot go beyond this size so in this way we can directly return OA from our function this is going to be my answer so in this way I utilize my slide variable sliding window to answer this question now let's try to find out the way to figure out the time and space complexity for this problem so what is the time complexity here I use two variables I and J is also iterating over this array once I is also iterating over this array on array not array it is a string of size n so it is n + n a string of size n so it is n + n a string of size n so it is n + n 2 N you can say it is order of n but here we also have a t string which is of s size M and we captured the frequency map of this T string so to capture the frequency map we need order of M time so ultimately it is order of m+ of m+ of m+ n as requested in the problem statement and what is the space complexity am I using any extra space I'm using this temporary map and you already know that uh it can be your uppercase or lower case characters which is 52 so not going to contribute too much into the space so order of 52 is the space complexity so this is my uh optimized approach let me also go through the code of this approach I wrote the code uh and I was having like I was stuck for an hour around or so to like to figure out the corer cases okay let's have a look at the code let me walk you through my Corde here what I did is firstly I capture the frequency of each character in the T string and also I'm maintaining the count should be equal to size of T so in the starting count is equal to T do length and my capturing the frequency so I'm now I'm using my Loop my sliding window varable sliding window so whenever I will see that uh so first of all this is a terminating condition while I less than n or J less than n that is uh for any valid uh index of I will be allowing to come to this uh while loop now this is my terminating case if the count is zero it means that we have a valid sliding window now we'll see whether the sliding window size is sufficient or not if it is a new minimum then we are going to update that if that is not a new minimum we will try to increment I character uh whether the I character is present from T if it is present from T we will add the frequency to T and if the frequency is going from 0o to more or 0 to one if it is going from min-2 to minus one which I which we saw min-2 to minus one which I which we saw min-2 to minus one which I which we saw in the last example in that case we won't do anything if it is going from 0 to 1 or 1 to 2 we will update the count as well and then incrementing I this is the case where count is zero if count is not zero we will just expand our sliding window is from I to J so we will just try to expand our window we'll try to get one more element and we'll see whether after adding after including that one more element whether I'm getting count zero or not so if I'm getting one more element we will see whether that element is from T or not if it is from T I will be reducing my uh count variable otherwise I'm not reducing that I'm have also taken else block because there can be case when uh this y Loop is going infinitely satisfying both the conditions okay so here if we try to run the while loop from I less than G less than n there can be case that say that string is X a o and we have to get AO where J will go till the length of s okay while I was writing the code I experienced a load of uh edge cases but ultimately I ran the code and when I also check the editorials uh it was having the same the messed up code having a load of conditions and all so but the main point is that we will keep on expanding our window uh and then we will try to reduce the window if count is zero and the count is equal count what is Count here the number of element uh from this T and the sliding window length is J minus I okay so if you try to try in the code you will see that J is after one unit of the current element for let's say for x a b o the J will be at the fourth index like out of this string so in this way I have written I have not written the terminating condition and the Y Loop okay so I'm attaching this code just try to like try to code it once by your own and then uh try to get help from this code I understand that it's a very hard problem and having a load of messed up uh if else condition but yeah if you try to run on uh some sample test cases on pen and paper you will get more understanding of this dynamic or maybe you can say variable sliding window okay hope you understood the problem thank you guys if you have any doubt you can just we can have a discussion in the comment section below bye-bye
|
Minimum Window Substring
|
minimum-window-substring
|
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`.
The testcases will be generated such that the answer is **unique**.
**Example 1:**
**Input:** s = "ADOBECODEBANC ", t = "ABC "
**Output:** "BANC "
**Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t.
**Example 2:**
**Input:** s = "a ", t = "a "
**Output:** "a "
**Explanation:** The entire string s is the minimum window.
**Example 3:**
**Input:** s = "a ", t = "aa "
**Output:** " "
**Explanation:** Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
**Constraints:**
* `m == s.length`
* `n == t.length`
* `1 <= m, n <= 105`
* `s` and `t` consist of uppercase and lowercase English letters.
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
|
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach.
L ------------------------ R , Suppose this is the window that contains all characters of T
L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T
When the window is no longer valid, start expanding again using the right pointer.
|
Hash Table,String,Sliding Window
|
Hard
|
30,209,239,567,632,727
|
122 |
today we'll be solving lead code question number 122 best time to buy and sell stock to we are given an integer area of prices where prices I is the price of the stock on the I so we have to find the maximum profit we can have so as you can see in the example like 7153 64 we can see that the maximum output and the maximum profit is seven so what we are doing is that here that we are buying it on day two at Price 1 and then we are selling it on next day at Price 5 then we are getting up uh price of uh four profit then next day we are buying it on price day four that is price three then we are selling it on next day that is price of six which is giving us the profit of three now the total profit will be 4 + 3 = 7 so here total profit will be 4 + 3 = 7 so here total profit will be 4 + 3 = 7 so here we can see that we can do this question at order of end time complexity and Order of one space complexity because we don't need we just need to check where we have to buy it at the lowest price and sell it at the maximum profit so we can do it as int of profit equals to0 and then we'll iterate through the list uh and then it will be H off at the index which will be equals to one at the first index and then we'll be looking at ID x equals less than equals to prices do size then we are doing plus ID X and then we'll be looping through it and check if the prices at that ID X is if it is great greater than prices at the previous index IX - index IX - index IX - 1 and then we'll be making it as a profit plus equals prices of we'll be putting it in inside the parenthesis prices of idx uh minus prices of idx minus one and then what we'll be doing is this that we'll be returning the profit of it uh so oh okay oh my bad my be yeah as you can see we are not using any extra space so it will be order of one space and then we'll be using it as an add order of end time complexity hope you find this video helpful if you like this video please like And subscribe
|
Best Time to Buy and Sell Stock II
|
best-time-to-buy-and-sell-stock-ii
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**.
Find and return _the **maximum** profit you can achieve_.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
**Constraints:**
* `1 <= prices.length <= 3 * 104`
* `0 <= prices[i] <= 104`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
121,123,188,309,714
|
438 |
today we will solve lead code 438 and it says find all the anagrams in a string so let's understand the problem you are given a string and you are also given a pattern so what you have to do uh you have to find all the occurrences of the anagrams of this pattern so first let's list the anagrams it will be abc acb bac bca similarly cab and cba so if you sort all these anagrams you will get abc so let's see so this window we have to look in windows fixed window sizes so here cba occurs so cba is one of the anagrams of this so the best way to check whether two strings are anagrams or not sort one of these or both of these and this would be same in sorted order so cba is one such anagram and this window size will be same as the size of this next we move to here and in result you have to return the starting positions so 0 is the starting position here then we move to b so we will see three characters bae it's not a b it's not eva it's not next we will find bac again you sort it you will get abc so this is the second anagram here the index is six so you will return this so how we will find that let's see so uh it can be overlapping just one more info so if we have a b and we have to find anagrams of a b then a b is there so zero index then if you look at these two then ba is also anagram so one will also be there and so on so overlap is allowed it's not that you have seen till here next you will start from here that is not the case you have to look for all the indices so what we can do once naive wave would be that you look at this window size and see if it's anagram or not next you advance by one and again look at this complete window size and again compare and whenever any anagram is found you store that starting index and return that but you see that here we are doing some redundant calculations so let's say the window size is very large this pattern is very large it has let's say 100 characters and this is pattern and this is a string if a string is less than pattern you can return straight away you cannot find an any anagram so let's look at the case where a string is large or at least equal to pattern so this so uh pattern starting at zero you have looked at hundred characters and if you start at one and it will end at one zero one so again you will look 100 characters but you will notice that only the two characters have changed this is same as the earlier so this part we had already seen while looking from 0 to 100 this is 1 0 1 so only this character goes away and this new character comes in so you don't need to scan this complete interval so once you have a scan this 100 intervals we can have a map so all these letters are english letters or small letters so we have an array from 0 till 25 here we will store the count of all the characters in the pattern so in this character let's say a occurs five times b occurred two times c occurs zero times and so on so we do this once beforehand even before starting the search we cares we can call it characters in p and when we do it once when we start from 0 whenever i find a so what does this denote p cash this is the count of all the characters from a to z in the pattern so if a occurs five times that means in any window i need to have five a's not more not less so this is a kind of required or needed so i need five characters five is i need two b's so what we will do so i start iterating this string so if i find a i will decrement its count whatever character it's let's say it's c so i will make it -1 so -1 so -1 so this means i have surplus of c similarly if i find a somewhere i will decrement its count so it will become four so that means four more a's are required this is required or needed and once we have reached still 100 that means i have scanned this window size which is same as this window size and then we have to check that p care should become 0 for all the elements that means no required no more character required or nothing extra also so negative will denote surplus positive will denote deficiency 0 will denote it's perfectly in the same amount which is required that let's say it's length is p or m and string length is n so what we will do for zeroth index it will take m time since it we will scan all the characters and once we have scanned we have just this peak here which is of size 26 it's fixed we will scan again and see if all the characters are 0 or not if everything is 0 that means this is a valid window so initially start index was 0 so we insert it into result so next what we will do we will start from here and whatever was this character so when we had added this character we had decremented so now we are getting we are not including this so just increment that reverse so for this character go to that position and increment by one and for the newly inserted character decrement y1 maybe it's here so this is for the last character this is for the first character you will get a new p care array which will again denote the requirement or needed again scan it and see if all are 0 or not if it's 0 then you insert that index as well and go to next step again uh do plus 1 for this and minus 1 for this and keep checking on so what will be the time for starting position is zero this is a start index it takes m time for one it will take order one time just two operations plus one minus one and then we will scan this 26 size array so we can call it 26 for 226 and what can be the last starting position so window size has to be exactly this w so if it's its length is m let's keep it m so m positions left of end so it will end here so if this length is n then n minus m plus minus 1 which we will see with an example so max the start position can go till n minus m so it will go till n minus m and again 26 so let's add all of these we have n minus m times 26 plus m so it's 26 n minus 26 m uh plus m or 25 m so it's order n plus m but m has to be less than or equal to n if it's more we will never find any pattern if a string is less so it's effectively order n so it will be linear time then there will be one more optimization which we will do so here for each starting position we are scanning this entire length of 26. we can get away with that in the first step we can keep track of a mismatch count so we have this peak array or requirement array of size 26 so first time we scan it whenever we find any index not equal to one we increment its count so mismatch count will be incremented so this way we get a count of how many characters are contributing to mismatch let's say it is five now what we have to do this character goes away and this character comes in rest of the window remains same let's call it c1 c2 so what we will do e care c1 has to be subtracted or rather added when we find any character we subtract it that is we decrement the requirement by one now its requirement will be incremented and here again p care c2 minus so we will only check for these two characters the one which goes away from the new window we have shifted the start position from here to here the next so this character is no more part of this character is part of it this is the key thing that's why i'm emphasizing here rest is unchanged the counts for rest are unchanged so here increment it here decrement it whenever we find any character we decrement its count since we said that it denotes requirement or how many more characters are needed to balance it so now we will check that if the updated value of this is 0 that means earlier it was non-zero is 0 that means earlier it was non-zero is 0 that means earlier it was non-zero that means it was unbalanced and we would have counted it in mismatch but this is no longer part of this window so decrement the mismatch count in this case if it has become balanced now but we will check that if it was earlier minus 1 that means it was earlier unbalanced we have seen this case but if it has become unbalanced now earlier it was balanced that means its count will now be one if it was earlier balanced that is earlier its count was zero now we have incremented it so now it should be one so we will check it if the new count is 0 we decrement the mismatch count if the new count is 1 we increment the mismatch count similarly here if it's now balanced then we decrement the mismatch count for this character it was earlier unbalanced and if it's unbalanced now or if it's balanced now earlier it was unbalanced so we decrement it so just try it once think it carefully to be clear so this is the logic so let's run through it here so in this window what will be the peak here p care will have for a it will be one b it will be one c it will be one others it will be zero this will be of length twenty six so we come here for c we decrement to 0 then we come to b if we decrement it whenever we find any character we decrement it then we find a so we decrement it now the peak here is completely zero we have seen three characters which is the window size so we check if peak error is all zero or not it's all zero so we add zero to the result next we shift the window here so what we will do we will just uh increment the count of c so this c will become one rest will remain same and the new one is e so d e its count we will make it minus one so we just change for the first and last character the new character that comes in the window and the old character that goes away we don't change anything else and now again we see that there are two mismatches this is non-zero this is non-zero so we this is non-zero this is non-zero so we this is non-zero this is non-zero so we will not insert it next we will come here a e b this one so here uh b goes away so we increment the count of b so b becomes one and b comes in so its count is now decremented so it remains zero so still two mismatches so we will not insert it next a is there this goes away a goes away it comes in no change if we do this again we will get the same thing now next we insert b so e goes away so this will become we will add plus 1 so it will become 0 and b comes in so it will become minus 1 again 2 mismatches so we will not insert it next is a and this b goes away so this b becomes 0 again and a becomes -1 -1 -1 again mismatches 1 and 2 mismatches next this a goes away and c comes in so what will happen a goes away so we'll increment it by 1 so it will become 0 c comes in so we decrement it by 1 so 1 minus 1 becomes 0 and we compare again everything is 0 so this is a valid anagram so we add to it next we will continue and we will not find it for the next one so for simplicity i was just looking all the zeros but this mismatch count will work as well so let's code it in c process then java and python so this is the same explanation so let's first write the unoptimized code where we will keep scan through all the 26 characters so this is the base case when the pattern is itself more than larger than the string so this is the fixed size array or vector you can use array also here each initialize with zero initially then for care c in pattern uh plus equal to 1 so this keeps track of the count of all the characters in pattern or we call it requirements so this will denote how many more characters are required then start index will be zero so this is the window size which will be a p dot length so whenever we find any character we decrement its requirement five requirements were there for some character we got one so one less requirement and then bool match equal to true and we will use this bool for int pc in p case if pc not equal to 0 then we have found a mismatch so match equal to false and break so when i said that i will scan 25 characters each time that was not entirely true if we find a mismatch early then we return from there itself and if match that is no mismatch occurred then result dot push back start this was the starting index and irrespective of whether it was match or not we will increment start so this was one time thing next we will do it for others from second till n minus m start less than equal to s dot length minus p dot length so let's what are the indices of the two characters it will be uh s start minus one that is previous character that went away minus a and the second index is p dot length minus 1 so this is the last character so p cares idx 1 this character goes away so it incremented by one and this character came in so it decreases by one and then we repeat this logic but this time in a loop so we reset match to true and scan through this pcare and finally we will return result we will add that optimization of mismatch account soon let's try it first if it works so this works for this case let's submit and the solution is accepted in c plus now we will do the optimization so here it will remain same till here it should be same start is same from here we will make the change so instead of bool we will keep a mismatch which will denote mismatch count and we don't break it we go to land so now this mismatch count have number of mismatches if it's zero we insert it and then increment it this loop remains same this remains same and let's add a few checks here we will not need this loop now so we are saving these this loop mismatch count will change only due to first and last character so once we insert it we check if p cares idx 1 is equal to 1 that is it was earlier balanced so it was earlier balanced and we had we have removed it so it's on balance now its count has become one now mismatch count plus equal to one so if its count is one that means earlier its count was zero and uh the mismatch count was not considering it as a mismatch since its count was zero but now its count has become one so its a fresh mismatch so its count should increment by one if some character was earlier also mismatched lets say its count was five now it has become six so earlier also it was mismatch now also its a mismatch so mismatch count will not change but here it has become from match to mismatch so we increment it else if p cares idx1 is equal to 0 that means earlier it was mismatched now it's matched so minus one this time same logic and we will repeat it here we are subtracting so if it was balanced earlier that is 0 it will become minus 1 then we increment its mismatch count and if it becomes 0 then we decrement its mismatch count and again the same logic so let's see if it works so let's try 0 6 and this solution is also accepted so we have got rid of this repeated loop for those 26 characters next we will copy it in write it in java this optimize solution so again just for this time complexity analysis so here we were adding just this 2626 so we can add some two comparisons instead of 26 so these will be all constant time earlier also it was constant time since 26 is constant but it should in general improve things although there may not be significant difference but there can be difference depending on test cases so the solution is accepted in java as well now we will repeat the same thing in python 3. this word is to get the sky value of a character invalid centrics so let's submit and the solution is accepted in python as well
|
Find All Anagrams in a String
|
find-all-anagrams-in-a-string
|
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "cbaebabacd ", p = "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is "cba ", which is an anagram of "abc ".
The substring with start index = 6 is "bac ", which is an anagram of "abc ".
**Example 2:**
**Input:** s = "abab ", p = "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is "ab ", which is an anagram of "ab ".
The substring with start index = 1 is "ba ", which is an anagram of "ab ".
The substring with start index = 2 is "ab ", which is an anagram of "ab ".
**Constraints:**
* `1 <= s.length, p.length <= 3 * 104`
* `s` and `p` consist of lowercase English letters.
| null |
Hash Table,String,Sliding Window
|
Medium
|
242,567
|
989 |
in left to right order that means if they are given an integer called num as one three to one then its array form will be one commodity that is in left to right order so given this num which is in Array form and integer K we have to return the array form of integer num plus k so let's stay a number of which is in other formulas and K will be equal to one then the output should be 123 Plus 1. so that will give you 124 and the other form of this will be one comma 2 comma four this is what we need to return so how do we solve this problem so let me just erase all these things yeah I'll take an example that can handle all the test cases so yeah that will be let's say a given integer is of 979 and 86. it's okay and this is the number which is in rfo are you integer for so we have to do this operation right so if you see the problem so if we see the problem what we need to do exactly is that some of the unit place is it so this is nothing but 979 right so sum of the then this will be added to resultant array and the remaining basic order is present that will be nothing but carry to the next one so it will carry here so the next sum will be 7 plus 8 plus this carry so sum plus k and also next element in the num array so 7 plus 8 plus 1 so that will result to 16. so in the 16 also you take only the unit place so and it's extra widget will be carry that carried by it to the next sum so that is it will go here so in the next sum you know the K integer is exhausted both 8 and 3 have added and we have left only with the num integer 9 and the carry so nine plus one will give you 10. so in this 10 we add only 0 to the resultant and one will be careful so you don't have any integers left now both in Num and the K so thus we just need to add the Carino so adding carry to the result either I'll give you one comma zero comma X comma 2. 79 plus 83 to give us we add these two so that will be too well then one carry then eight plus eight sixteen then one carry then we'll give you one carry on more carry one so whatever addition operation performance is that we are representing to this program code so we will add each unique places it and whatever carries we get we add that to the next in the titration so now you may get to know why I have taken this uh example because if I take a simple example 123 comma 4 then this won't handle cases of carry how to handle with the carry R and here you're getting uh an extra number even after both online care exhausted this carry as well so all these cases to handle I have taken this example now you shall see the logic of the program how to solve this so again let's see so this is 9 comma seven comma 9. then we have k equal to 83. so like IBN integer quantity variable pointing to the end of the array column and we have K and one more variable we will have a carry so carry equal to zero initiative so as I said we have to first do the summation right taking place of both last integer of the num and then in place of this so why I greater than equal to 0 why Theta equal to 0 because we have zeroth index value as well or K greater than 0 K is greater than zero means if any if what is the normal integer length is lesser than k then k will be more than it will have the remaining values even after adding them and values static K greater than zero or can be greater than zero condition so in such case also we need to add two cells so any of these three conditions becomes true so at first I greater than equal to zero with blue check so initially will have in sum equal to zero that is something but carry why am I writing sum equal to carry because in the example issue you can see nine plus three if you do in a case I will give it to L and you add 2 only to the output array whereas this one will be added to the next sum that will be carry so the next citation this sum should be equal to carry by that time so that's why we initialize some equal to carry so yeah we will we need a result entire record it's of type arraylist so this is the resultant that is now if I is greater than or equal to 0 if I is bigger than equal we have to add this to the sum so sum equal to whatever carry is present that should be there Plus particular minimum of I so carrying Financial is zero if I take in this case carry will be initially zero so sum will be called sum equal to zero plus unofficial so next after this I should be decremented now so I equal to minus so I become 1. initially I was 3. us2 y equal to 2 that is 0 1 2 3 X so we handle this number now we have taken the unit place from the number you have to take unit digits from the K integer as well so how do we take that so now if K is greater than zero so if we take 89 how to fix this unit is it's nothing but k modulus 10 right so 83 modulus 10 will be nothing but remainder 3. so yep sum equal to whatever sum we got so sum was initially num value whichever sum plus so this sum will contain carry and num integer present so num element plus carry if present that sum will be there then some place this particular unit value that is K modulus type so once this is done now only the remaining disability in the cable because 3 is added on it so how to fetch the remaining digits that is 83 by 10 will give you a portion Plus 8. so this is one case between so now we have added the carry fine initially we added the carry because how much initial is to carry itself then we added the your element in the number in this case then we added the element in the K8 integer also yeah we added the number indicate integer as well so all these are done now we have the sum like 979 and 83 right so nine and three we have added so nine percent nothing but 12. related to our last answer as a sum equal to Alpha but in this table you need only 2 to be added to the resultant array so again how to get this ultimate modulus operation so some modulus 2 L modulus 3 will give you 12. so result on ADD off some modulus 2. foreign so 12 by 10 will give you one so sum right there I'll give you next I guess you will become so by the next I guess is equal to 1. so it will pointing to this 7 then kis value 8 we have got so I equal to 1 that is having the value 7 a is equal to a then sum will be initialized to carry so carry will be 1 this time because we have got this one carry from the previous one so initially sum equal to carry one then you have to check if I greater than equal to 0 so this greater than equal to 0 and you add seven to the sum so sum will be one plus seven it will be eight some will become eight so next we have to add this element also to the sum so since only one element is present eight modulus 10 will give you 8 itself that is itself is it so eight percent that will give you 60. so that will give you 0. so K becomes 0 by now next time equal to 16 you have and here you need to add over 6 to the resultant and one will be the capital mixer so 6 will be added some more vegetable so some modulus 10 sorry then one will be added by Sum by cat as in the next title in this case k will be equal to 0 and I also equal to 0 then sum will be initialize to carry something with one again we have got one lesson carry into sum 16. so in this case you check whether I is greater than equal to 0 yes it is 1 plus 9 will get two ten so don't take into consideration next Once you have semicoloted here you have to check for the year place that will add it to the output array so that will done by some modulus 10 so 10 modulus n will give you zero so zero impact the output array and the remaining digit will be carrier again so now carry equal to 1 you have so again you check for the condition whether I is greater than or equal to zero because I minus means will happen so I will be minus 1 by this time K is of course not greater than zero so even these two conditions are not satisfied only carry is greater than zero the same carry one we have so that will be added address to the resulting curve will give you one now carry will be 1 by 10 that is zero so all the conditions are satisfied all the condition is so we will call this arraylist of time integer name result equal to new error list then in carry equal to 0 then in um I equal to last element in Array num dot length minus 1. so here this is sufficient now y is greater than equal to 0 or k greater than 0 or carry whatever you have that is greater than 0 then first some may be initialized to carry So In Sum equal to carry reason I have told here right here we have said yeah nine plus three well so 2 will be added to result another but one should get a cap so sum will be cat because this one will be added to the next sum here the sum equal to carry so once you do some equal to now check for if I greater than or equal to 0 first condition then you have to add that to a particular element to the sum so sum that's equals to sum of I sum equal to sum plus sum of I so then decrement the I value because it's pointing at the end of the array so after this again check for carrying condition if K is greater than 0 then we have to catch the unit or digits so multiple sum plus equals to a modulus 10 so this will give you this is k1 Plus 10. this is K modulus 10 okay so k equal to keep it yeah so after this uh yeah carriers also added to the sum and I'm also added to the sum okay also added to this one so all are added to this once all are added to the cell now you have to compute add some to the resulting okay so result dot add off so in this case also sum will be continuing totally to this it's too well right so two only need to add it to the array so how to fetch this again some model is still foreign plus 83 12 6 1 0 6 3 yeah the resultant error will contain first two we decided to result another then six is added to visit another zero standardization but we need output reverse of this so we do collections don't reversal particular result so collections or reverse of reason we will submit this isn't successfully submitted if you have any doubts please drop it in the comment section we'll come up with another video in the next section and please subscribe to each other and keep learning thank you
|
Add to Array-Form of Integer
|
largest-component-size-by-common-factor
|
The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104`
| null |
Array,Math,Union Find
|
Hard
|
2276
|
5 |
in this video we'll go over lead code question number five longest palindromic substring given a string we have to return the longest substring that is also a palindrome is a sequence that reads the same backwards as it does forwards for example if our string was hello then we would return LL since LL read backwards is still LL and there is no other longer substring that is a palindrome now one way to do this would be to calculate the length of every possible substring so first we'd find all substrings starting with the letter H including the full word itself then we'd find all substrings starting with E and we'd continue this until every substring has been found this runs in O of n Square time then we'd have to check every substring to see if it's a palindrome since palindromes read the same both forwards and backwards we know that they have to be mirrored around the center so one way to check would be to start at the center of each substring and work our way outwards checking out each step to see if the characters match for example to check the substring Lo the middle two characters match but when we move outwards we see that the characters are different so Lo is not a palindrome now each one of these checks runs in O of end time and we'd have to do that for every single substring which took o of N squared time to generate so in total The Brute Force algorithm ends up running in O of NQ time now we can improve this by eliminating some redundant steps here's the idea let's say we wanted to find the longest palindromic substring of a b c d e d c f a but only considering substrings that have e as the center character well if we know that the letter e by itself is a palindrome then when we test DED we don't need to start from the middle again we can only check the outer characters the D's and now that we know that DED is a palindrome when checking the substring c d e d c again instead of starting from the middle all over again we can just check the outer characters now when we check the next set of characters we see that they're different that means that this substring is not a palindrome so any other longer substrings won't be palindromes either so we can actually just stop here and we don't need to check any more characters in The Brute Force solution we would have done the O of n palindrome check over and over again for every single substring with e as its Center but what we've realized here is that we can actually check all substrings with the same Center in a single pass with the potential to exit early so now the question is how many different centers can a string have well if the substring length is odd then any of the characters could be the center and if the substring length is even then the center could lie between any two characters if the length of the substring is n then there's a total of two n minus one centers which is O of n so if visiting each Center is O of N and each palindrome check is also o of n then that means that the overall algorithm will now run in O of n Square time instead of O of n Cube time now let's look at the code and see how we can do this in Python let's say a b is our string first let's define a helper function called expand that will take in two indices that represent the center of the substring and will expand outwards to find the longest palindrome from that Center we'll come back to this later when we use it for now let's create a variable that will hold our final answer and call it result and we'll initialize it to the empty string then we'll start the loop to check every Center using the variable I so now let's call the expand function and pass in the I variable twice meaning that both the left and right indices in expand will start at the same index 0. then we'll check for three things before expanding outwards first we want to make sure that we haven't gone out of bounds so we'll check that the left index isn't less than zero and that the right index is less than the length of the string those are true so now we'll check if the characters at the left and right indices are the same right now they point to the same character a so this is true that means that the substring a is a palindrome and we can now expand outwards to check the next set of characters we'll do this by decrementing L and incrementing r then we'll check again but now we see that L is negative one so it's out of bounds that means that we're done checking all substrings from the center and we can now return the longest one that was found we'll do this by slicing the string between the left and right bounds not including the bounds themselves so we'll slice from one index past L up until R since python string slicing includes the starting index but excludes the ending index so we end up returning just the letter A now we've returned back to the main function and sub 1 is a now we'll compare sub 1 to our result variable if the length of the substring we just found is greater than the length of result like it is here then we'll update result to be Sub 1. in other words the result variable always holds the longest substring encountered so far we're not done yet with this Loop though because we now need to check for the case that the substring length is even and the center lies between the first two characters so we'll call expand again but this time pass in I and I plus 1 so the center is between 0 and 1. then we'll do the same thing both indices are inbounds but the characters are not the same a is not equal to B so we'll just exit and when we slice the string we end up slicing from index 1 to 1 but remember excluding index one so this actually ends up returning the empty string since there was no palindromic substring to be found so now sub 2 is the empty string which is not longer than the substring a so we keep a as the result and move on to the next iteration now let's find the longest substring starting from index one B is equal to B so we'll expand outwards and check the next set of characters a is also equal to a so now we know that a b a is a palindrome so let's keep going now we've seen that we've gone out of bounds on the left side so let's go ahead and return the substring between the left and right bounds so now sub 1 is Aba the length of sub 1 is 3 and the length of result is only one so let's update result so that it's now a b a then we'll try the next Center between index 1 and 2. B does not equal a so we just return immediately again with the empty string and skip the if block and move on now let's try index two again a by itself is a valid substring but the next set of characters don't match so we'll just return a which isn't longer than ABA so let's move on then we try index 2 and 3. both characters match so let's expand the substring B is equal to B so now we're at b a b and let's keep going now we've finally gone out of bounds so we'll return the substring baab and we see that its length is 4 which beats our current result so we'll update result to be b a b now the rest of the iterations are pretty much the same so I'll speed this up a bit a by itself is a palindrome but not a b so we return a which is shorter than b a b next a b is not a palindrome so we'll just move on B is a palindrome and we can't expand out any further so we'll return B which again is too short for our last check we can see that the right index is already out of bounds to begin with so we'll just exit immediately with the empty string we've now checked every single Center and found the longest palindromic substring overall so we can just return the result which is b a b and we're done now for the sake of completeness I will mention that it is possible to solve this in linear time using something called maniker's algorithm but it is pretty complicated and I don't think any reasonable person would expect you to come up with this in a short interview session but if you're interested you can go ahead and check that out
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
1,773 |
okay let's talk about counts item matching rule so we are given a row key and rule value so for this key is color and value is server and you are giving type color name right so you are going to find out the color blue server go around and then if the value equal to the row value and you return for this simple type right the first is type and the value is from so one two so the number of the phone will be equal to two so you can use the mythical uh map to store the key so map so we are storing string right integer map and then i will say type become zero so that would be the first then color become one and then become two now we need an answer right and the index will be when we do through the list of lists of string right we need index which is uh row key why because rookie uh the key rule key is the index of color so we just have to loop through the string of a list of string so i would suggest item and items so if items.get so if items.get so if items.get index and then when we compute the stream will user equal right and rule value if this equal then we increment our result and then we return a result so the idea is pretty much simple this is list of lists of string right we get the index if the index is zero then we get a zero index for every list of string then to check that strings are uh strong are equal enough for the for this example from computer phone right we get the index which is zero values from the check are they match if they are you just return uh you just increment and you return all right let's talk about timing space so for the time you're doping every single list of strings so it's open and then space that you use the map and you could just hardcore it so in and then if you see type is the index will be zero color one name two so i'm just copy and paste and choose to let you see the different answer so there will be your heart call it so rootkey.equal and then you call it so rootkey.equal and then you call it so rootkey.equal and then you have index one and is equal to index one and is equal to index one and is equal to and the default is zero because you don't want to do a street if statement so type column name right and i just do the same thing and there will be this uh send result and the timing space is still the same there was time all the time looking through entire single element inside of this and i think that would be it i hope you get it
|
Count Items Matching a Rule
|
percentage-of-users-attended-a-contest
|
You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.
The `ith` item is said to match the rule if **one** of the following is true:
* `ruleKey == "type "` and `ruleValue == typei`.
* `ruleKey == "color "` and `ruleValue == colori`.
* `ruleKey == "name "` and `ruleValue == namei`.
Return _the number of items that match the given rule_.
**Example 1:**
**Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "lenovo "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "color ", ruleValue = "silver "
**Output:** 1
**Explanation:** There is only one item matching the given rule, which is \[ "computer ", "silver ", "lenovo "\].
**Example 2:**
**Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "phone "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "type ", ruleValue = "phone "
**Output:** 2
**Explanation:** There are only two items matching the given rule, which are \[ "phone ", "blue ", "pixel "\] and \[ "phone ", "gold ", "iphone "\]. Note that the item \[ "computer ", "silver ", "phone "\] does not match.
**Constraints:**
* `1 <= items.length <= 104`
* `1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10`
* `ruleKey` is equal to either `"type "`, `"color "`, or `"name "`.
* All strings consist only of lowercase letters.
| null |
Database
|
Easy
|
1338
|
1,313 |
hey what's going on guys it's ilya bella here i recorded stuff on youtube chat description for all my information i do all legal problems make sure you um subscribe to the channel give me a big thumbs up to support it and this is called the compress run length encoded list we are given a list numbers of integers representing the list compressed with run length encoding consider each adjacent pair of elements frequency value which is num set the position of two multiplied by i nums at the position of two multiplied by i plus one with i which is greater than or equal to zero for each such pair there are this frequency elements with value val concatenated in a sub-list value val concatenated in a sub-list value val concatenated in a sub-list concatenate all the sub-list from left concatenate all the sub-list from left concatenate all the sub-list from left to right to generate the decompressed list return the decompressed list for example we got these nums right here one two three four and we return this output because the first pair which is one and two means we have frequency which is one and value which is two uh so we generate the rate two the second pair which is three and four means we have frequency which is three and value which is four and we generate four and four at the end that concatenation we get two and four which is two four and four right here we got frequency we got value frequency and value and we return one three and three the length of this array is even and is greater than or equal to 2 and is less than or equal to 100 numbers at the position of i is greater than or equal to 1 and is less than or equal to 100 um go for it first we need to find out the length of the result array um we are looking through these um even indices of that nums i select the nums dot length i plus equal to then we say lane plus equal nums the position of i then we got this length we can construct this new array result new int length and we create uh the variable which is start index is equal to zero then we again are looking through these uh even positions indices of that numbs length i plus um equal to and at each iteration we call the method field and what we do that we feel this result start from the position of start index up to start index plus nums at the position of i with the value at the position of nums um at i plus one and also we obtain the start index plus equal nums at the position of the frequency right finally we return this result um that's the whole problem let's run this code there we go let's submit first try um good so what do we got this um array for example nums and you know the right indices that's zero based in java we got zero one two and three then we start looping through this uh array we start at the position of zero right here and we got length which is zero initially then when we are here we got one so we got one we go here then we got three so we say 3 plus 1 which is 4 right and we are done we out of that loop then we can strike this result this array uh which is you know we got the length of that array four zero one two three and four means that we got this four elements and um we start index is equal to zero initially and we start looping through these nums again we start from zero repetition of zero so we call this method arrays.fill i we call this method arrays.fill i we call this method arrays.fill i fill this result start from the position of index start index which is zero and we feel up to start index plus nums at the position of i means uh the position of you know we got one so we say here we insert um i plus one that is two right we got two here then we go here and before that of course before that we need to update the start index uh two one right the one and then we go here and we can see that uh start index is equal to one then that means that we start feeling filling up these cells at this position start from this position and we say up to one plus the position of three at the position of two we got three so one plus three which is four um we filled this three fill up these three cells with the value at the position of i plus one which is two plus one which is three we got 4 right we got 4 and 4 right here that's it finally we return the final answer thank you guys for watching leave your comments below i want to know what you think follow me on social medias i do all lit code problems uh follow me on instagram on the snapchat and i wish you all the best thank you bye
|
Decompress Run-Length Encoded List
|
count-ways-to-build-rooms-in-an-ant-colony
|
We are given a list `nums` of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements `[freq, val] = [nums[2*i], nums[2*i+1]]` (with `i >= 0`). For each such pair, there are `freq` elements with value `val` concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.
Return the decompressed list.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[2,4,4,4\]
**Explanation:** The first pair \[1,2\] means we have freq = 1 and val = 2 so we generate the array \[2\].
The second pair \[3,4\] means we have freq = 3 and val = 4 so we generate \[4,4,4\].
At the end the concatenation \[2\] + \[4,4,4\] is \[2,4,4,4\].
**Example 2:**
**Input:** nums = \[1,1,2,3\]
**Output:** \[1,3,3\]
**Constraints:**
* `2 <= nums.length <= 100`
* `nums.length % 2 == 0`
* `1 <= nums[i] <= 100`
|
Use dynamic programming. Let dp[i] be the number of ways to solve the problem for the subtree of node i. Imagine you are trying to fill an array with the order of traversal, dp[i] equals the multiplications of the number of ways to distribute the subtrees of the children of i on the array using combinatorics, multiplied bu their dp values.
|
Math,Dynamic Programming,Tree,Graph,Topological Sort,Combinatorics
|
Hard
| null |
1,786 |
hello welcome today let try to solve L code problem 178 six number of restricted parts from first to last no so let's first understand this question and then I'm going to solve it by the D TR algorithm with the yeah I'm going to use the D TR algorithm with the dynamic programming yeah because otherwise if I yeah after using the DAT algorithm if I use the BFS I going to have a Time limited exited yeah so let me first explain this problem so we are getting a number of Nod so from no one to no n and we are also giving the addes and for the blue color it is a just means the shortest distance from this one to five for example it is four the shorted from not two to not five it is a two yeah but we want to find the decreasing distance so for example from not one to not five what is the decreasing distance it means it is a 4 1 0 this is 4 to Z and can we find another one uh yeah let's check another one 1 2 3 5 so it is a 4 2 1 Z I mean the distance would always be in inreasing order and for the nod it is 1 2 3 5 so how many are there so in total there are three why because we are giving like this one the distance to last no X so this is the sest distance and here we have another condition so this zi should always be more than the distance to last no zi + one so this means this is not no zi + one so this means this is not no zi + one so this means this is not one this is the distance is four should always be more than the not two so the distance from not two to last n it is a two the four would always be more than two would always be more than zero so in total there are three for this example yeah now let me first try to write the do Al algorithm because basically I'm going to calculate the distance so this blue colors are not giv I'm going to calculate this blue colors so I'm going to start from n five to not one but basically I going to transer from not zero to n minus one because this is easy for calculation at least for me so I'm going to prepare a Glo would be a default D and inside it will be list and now I'm going to check the graph so for u w in at this now T minus one so the append V minus one with the w yeah because I'm going to start from not zero not one so for g v excuse me uh do append with u minus one with the w and here I've already prepared the graph the existenc list now I'm going to yeah prepare the dist R so the dist R would be infinite time n and this minus one because I'm going to start from the last not would be starting from zero and then I'm going to prepare the PQ would be yeah just the empty array and inside it would be a tle uh inside I'm going to prepare the distance first so from the last no the distance is zero the last node is n minus one so this means just this and not for the priority C and I'm also going to prepare this modular because the result will be modular this value now I'm going to use the BFS basically dat trust algorithm to solve it so while PQ I'm going to pop out the yeah let me use the Let Me Maybe I use uh yeah which variable let me uh yeah I going to use W it is a weight so w and U I'm going to use this not U would be equal to Hip Hop uh with this PQ and now I'm going to text the neighbors so for neighbor and cost so weight and cost are the same but basically I'm going to use this cost to say yeah because it's for neighbors for neighbor and cost in G with the nod so the ND is just you yeah I will always put the weight at the first place because for PR priority Q I'm going to check this and weight first and always check the shortest distance yeah now I prepared for the neighbors and cost I'm going to prepare a cost so this cost would be the previous cost W plus the current cost it is my neighbor to the nod to this no you yeah so for this neighbor I'm going to use the V just two no I'm going to use a v so the cost would be W + C yeah now v so the cost would be W + C yeah now v so the cost would be W + C yeah now I'm going to check this cost if my current cost is less than the distance so the distance inside it would be a v yeah because it is a distance for this no way and this current no is also the distance to this no way this means the last no to no way maybe the no way is just no two and if it is a soter so I'm going to update it so if the cost is the soter so the this V would be equal to cost and uh yeah priority Q should be p uh no with a cost and a no yeah it should be the cost and the no so the current no it's neighbor is V yeah so this is the D algorithm that means just to return a value zero it doesn't matter because I'm going to check if this is right or not yeah let me just print out the this to check what the distance array looks like first yeah it doesn't matter yeah because I don't prepare for that I just to check the distance array as you can see this is the distance right so this is a zero for not five and for not four it is a six and this is also six to not three it is one to not two it is a two to not one it is four it means it's right yeah at least the that algorithm is right I get a right distance array yeah now the second step is I'm going to use the DP yeah uh DP is really hard to write I'm going to use the top do approach basically it is a DFS plus memorization so I'm going to start from this not one to other no for example from no one to no two if it is a decreasing so this is four this is two the distance it is a decreasing I'm going to attack how many parts from no two to this no five to the last no so there's one part there are two parts because this is one 5 to two and 5 to 3 to two there are two parts yeah so how many distance from not five to not three there's only one pass how many pass there's only one pass just from not five to not three so in total it going to be three yeah so let me prepare the DFS so for the DFS uh let me yeah the DFS inside it would be a nod this nod will be starting from the yeah we'll be starting from another uh last uh first no so it going to be uh zero because I'm always use the N zero to n minus one it's not starting from not one yeah you can also use not one it always depended on your habits of solving this kind of a graph problem yeah now I'm going to check this nod if the nod is the last no in minus one so I'm going to return a one so this means I find one pass yeah because to the first no to the last nod if I can go to the last no it means at least I can find a pass yeah so this is the as cases because from sub nod from the start node to last node if I can go from one to five it means at least there is a pass so I can return a one now I'm going to prepare a result so for uh let me use a neighbor for neighbor in for neighbor and weight in G with this nod so the result would plus all its neighbors so for example for this not one it would plus its neighbors yeah so the neighbor would be yeah let me yeah what is it neighbors it is a DFS with neighbors yeah but this is right I think this is not right uh finally I need to return the result because I didn't check if the distance is shorter basically if the distance is sorter I going to plus this DFS with neighbor otherwise it would be too much yeah let me just run it if not = to nus one maximum recursion deps not = to nus one maximum recursion deps not = to nus one maximum recursion deps exceeded in comparison yeah this means there is infinite loop I didn't consider the distance would be shorter and shorter if I didn't consider that basically it would be an infinite Loop it will go it will never add so I needed to check it how should I plus this DFS with neighbor I need to check the distance first yeah so if the uh distance uh with the neighbor so my current no is the no yeah if distance neighbor is less than the distance of my current no so for example this is the current nod is one the distance is four so if this distance is two so I'm not going to go to this not yeah if it is less than result would plus DFS now let me run it to tck now as you can see it seems works yeah now let me just run it uh I'm sorry I'm going to submit it to check what going to happen first yeah I know there are two things I need to add but at moment yeah if I didn't do that I going to make a lot of mistakes first of all I going to make a Time limited mistake let's talk I can go to 52 because this designed this kind of testing case will never let you pass so this means I have to use a c because after using C the time complexity for the DFS it is just o e plus v e is the number of edges V is the number of vertices and for the that algorithm it is basically e * log V so algorithm it is basically e * log V so algorithm it is basically e * log V so the time complexity will be unlog in after I used the cast yeah now let me run it and submit it to check what going to happen there will be still a mistake yeah because I didn't consider the mod yeah so this is why we are practicing we need to consider a lot of things yeah uh as you can see for this testing case 69 and the number is too big so this means I need a modular after modular the mod I think I need I can pass for all the testing cases let me just try it again as you can see it passed and it's pretty fast thank you for watching
|
Number of Restricted Paths From First to Last Node
|
count-the-number-of-consistent-strings
|
There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2, ..., zk]` such that `z0 = start` and `zk = end` and there is an edge between `zi` and `zi+1` where `0 <= i <= k-1`.
The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A **restricted path** is a path that also satisfies that `distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`.
Return _the number of restricted paths from node_ `1` _to node_ `n`. Since that number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2,3\],\[1,3,3\],\[2,3,1\],\[1,4,2\],\[5,2,2\],\[3,5,1\],\[5,4,10\]\]
**Output:** 3
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
**Example 2:**
**Input:** n = 7, edges = \[\[1,3,1\],\[4,1,2\],\[7,3,4\],\[2,5,3\],\[5,6,1\],\[6,7,2\],\[7,5,3\],\[2,6,4\]\]
**Output:** 1
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The only restricted path is 1 --> 3 --> 7.
**Constraints:**
* `1 <= n <= 2 * 104`
* `n - 1 <= edges.length <= 4 * 104`
* `edges[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= weighti <= 105`
* There is at most one edge between any two nodes.
* There is at least one path between any two nodes.
|
A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force
|
Array,Hash Table,String,Bit Manipulation
|
Easy
| null |
929 |
hello welcome to my channel i'm here to do my 100 lego challenge and today we have the code 929 unique email addresses so for this question the description is really long but in summary you will receive a string array of emails in here and then each email is like a string but in that string we need to process few things so before look at this one the address looks like this and before that i have local name and this is domain name in the local name we'll have this character and this character the dot and the plus sign so for the dot we ignore it and for the plus sign we will ignore anything after plus size including the plus sign so here's example we have test dot email because this is a local name so we'll ignore this character and the plus sign anything after or including the plus sign will be ignored so it turns out for the local name will look like this and anything after local name which is the domain name after the add sign will be remain inside that translation so in here this will translate translated to this string and in here the same after we take out ignore this one ignore the dot and also ignore plus sign and this until here the translation looks like this so these two have the same translation but the second one i mean the last one in here we translate to here because the domain name is different so now we have two translation a unique email address as an output so the amount of that unique your email address will be two so we output two uh the idea of this question is we set first have a set headset that keep track of all the unique um email address and we just look through this one and translate every single thing and then put those to the hash set and after you look through the whole original array and take a look at that hashtag and see houses how many unique email addresses in there and then you just return the size of that set now so let's take a look at the code so first we have a set of string just call it set you need to look through every email inside emails array so because we need to translate every single email so we start with a string builder so we now we have one email to process and we have a string builder so for every character in that email now for example we have this right now for this character we look through every character in this string for every string we can call character c equal to email so now we have the character c that we're looking at individually after that we have edge cases we need to care if c is equal to just dot we can just continue we can ignore it so if c is equal to um plus sign what we can do is now if we see this one here we can just move the pointer until we find the add we can move the counter c is not equal to um at and we can make c equal to uh email dot chart at now here is plus i we need to increment uh i by 1 first and then we set that c become next character and then now see so we have current after that we can put the x sign we can put anything after add sign inside that string builder oh let's see email substring now we add this pointer now right now so we just add a substring of this starting from here to the end of the string inside the string builder um substring of i think yes i after adding the rest of it inside the translation which is stream builder and we can set that at us no not yet so we can break this for loop yeah this is if this is plus sign so another case is c plus equal to x sine if that is the case we just basically add everything after that the same as here just copy it from about also break it out from that for loop now if we don't have anything it if this currency is not dot not plus not at then we just simply add put that current character inside that string builder which is c so now the for loop is good and also hold on now this is for that one email after the email we rebuild the string builder and what we can do is put that into the set current dot 2 string so for this for loop is already finished and put everything inside a set now we return set dot size so it will capture how many unique email we have cool submit it yeah that's it for this question all right let's just be really straightforward and just make sure there's some the syntax is familiar enough so i cancel some space in here so make it look a little bit better yeah that's it for this question if you have any concern please comment below and i will see you in the next video bye
|
Unique Email Addresses
|
groups-of-special-equivalent-strings
|
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**.
* For example, `"[email protected] "` and `"[email protected] "` forward to the same email address.
If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**.
* For example, `"[email protected] "` will be forwarded to `"[email protected] "`.
It is possible to use both of these rules at the same time.
Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_.
**Example 1:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 2
**Explanation:** "[email protected] " and "[email protected] " actually receive mails.
**Example 2:**
**Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\]
**Output:** 3
**Constraints:**
* `1 <= emails.length <= 100`
* `1 <= emails[i].length <= 100`
* `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`.
* Each `emails[i]` contains exactly one `'@'` character.
* All local and domain names are non-empty.
* Local names do not start with a `'+'` character.
* Domain names end with the `".com "` suffix.
| null |
Array,Hash Table,String
|
Medium
| null |
46 |
hey what's up guys in this video we're going to walk through this nicole for our number 46 permutations so we are giving a real numbers of distinct integers and we need to return all the possible permutations and uh we can return the answer in any order so take a look at this example one two three and uh one permutation would be one two three just itself second one will be one three two and the third one is the two three one so the two comes first and then one comes second and three comes after and uh the number of possible permutations n factorial uh n being the number of elements for example uh for this case in here we have three elements uh the number of possible computation will be three factorial that is being three times two times one because the first spot we have three choices after we have chosen the number for the first spot and then we have uh a minus one choice for the second spot and then m minus two for the third spot again in this case would be we have three choices in the first spot two choice in the two sides in the second spot and one choice in for the third spot so 3 times 2 times 1 in this case would be 2 factorial and 1 factorial now this question was very popular it was asked by these big names and it has more than almost 7000 likes as of july 2021 so we will solve this question by using a recursive function just like any other recursive function first we have we need to have a termination condition where if the given list the length of the given list is only has one element and then we will terminate the recursion function and then we will append the result to the answer list which we will return at the end of the function so for the index from 0 all the way to the length of the given list and then we make a copy of the given list first we pop off the i element from the copy list and then we catch that by using the alm and then we call recursively called the function itself by inputting the copy which is one element last and then we return also a permutation so let me walk you through an example for example uh this is the starting point so in this case num is equal to one two three i'm just walking to this example right here and then we also inputting a empty list the length of the so in it we call the precursor function the length of the so now the given list is one two three term as an empty list the length of the given list is not equal to 1 so we go to this for loop here for i in a range from 0 to the length of the given list in this case it's three so zero one and two and zero is the starting point and then we make a copy of this given list right now it's one two three we pop off the i element right now i being zero so a number will be one and then we call the recursor copy which being in this case is two and three because we pop off the first element so while now we are left with two and three and perm in the first case it was empty list plus a list that containing that number just being popped off which is one so we inputting 2 3 and 1 to the recursive function back to here now the length of the given list is not equal to one because it has two elements being two and three in it and then we throw this two and three to this for loop i at the beginning equal to zero and copy this list to be a copy a number is a copy dot pop off the first element in this case is 2 so a num is 2. and copy is equal to 3 because the first element being popped off from this list so in this case this copy is equal to a list containing a number of three and perm plus a num again is two perm is from here which is one from the prior call function so and then after we concatenate the two lists will be uh one concatenate the list that contains a num which is two so we're inputting one and two as the perm in the next call and then the given this right now is three so this condition is met because the given list right now is a list containing a single digit which has a length of one and then we append the perm which is one and two and a given list right now is a single d it's a list containing a single digit so we concatenate that so basically we'll be concatenating a list of one two and three so that's the first run for the permutation and it will do the same thing for this one the next one etc until we run all the possible permutations let's run that and it works looks pretty efficient in terms of the time complexity is big o of n times n factorial so n being we are calling this function n times sorry we are calling this function n factorial time and each of this function called i mean the time complexity for each one of this function is big o of n because the perm i mean when the given list it has only one element we call this guy it has n elements in it and then we are appending it to the answer list the size of this term plot concatenate before given list the size of that is big of n that's why it takes a big of and run time to append to the answer list and the recursive function is being called n factorial time which is exactly the number for possible permutation we have to call that many times to generate that many permutations so for space complexity is n factorial because the answer needs to contain n factorial number of elements and also this copy list if it has in total n factorial copies because this function being called n factorial times each time when it's called a copy is made and it's a copy the element in each copy is reduced to the one when it's been recursively called so essentially space complexity of this coffee variable it has n factorial copies if that makes sense that's so much for this solution i hope you like it if you do please like this video and consider subscribe to the channel that will be a huge encouragement to me thank you so much for watching this video hopefully i will see you in the next one thank you bye
|
Permutations
|
permutations
|
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**.
| null |
Array,Backtracking
|
Medium
|
31,47,60,77
|
1,721 |
hey everyone today we are going to solve the radical questions shopping nodes in a linked list so you are given a head of any linked list and integer K return the head of a link to this after swapping the value of case node from the beginning and the case node from ending so let's see the example so you are given one two three four five and k equal to so that's why we have to slap this node and then so how to put this should be one four three two five yeah very simplification so let me explain how to solve this question before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so let me explain with this example one two three four five and the k equal to and to solve this question first of all create a dummy pointer and initialize with head so now dummy points are pointing one and then first of all we move dummy pointer onto K minus 1. so now k equal to so just to move one time so dummy pointer is now two and then after that um so we want to move dummy pointer um more later so that's why um so 2 is a yeah one of a like a Target node right because k equal to so that's why I copy this dummy pointer to let's say um first pointer and then after that I create another pointer let's say a second pointer and the inside with head and then um next we want remove dummy pointer and the second pointer until dummy dot next is null that means here so let's move so dummy Point uh move next and the second Point move next dummy pointer move next second Point uh move next and the dummy pointer move next and the second Point download next is no so we stop so now um second point that is pointing uh um one of Target nodes right because uh 4 is a second note from the tail so now first point the pointing to and the second Point uh pointing pull so yeah this program so important thing is that we don't actually we don't have to swap the node just uh um swap values so just a swap values um two and four and then so these should be four this should be two then we have to return the like entire wrist so head is still pointing one so that's why in this case we should return head yeah so that is a basic idea to solve this question so with that being said let's get into the code okay so let's write a code first of all I create uh so this dummy node so dummy equal head and first of all um as I explained earlier I move dummy node onto K minus 1. so for underscore engines and K minus one and then dummy equal tummy and put next and then after that so I want to keep this target node so I copy dummy pointer to fast pointer so fast he called tally and then next I created second pointer so second point in size to his head and then um iterates through until dummy dot next is new so why dummy talk to next is exist and move dummy pointer next so dummy dot next also second equals second dot next and then after that um so now this first pointer and this second pointer pointing uh Target nodes so all we have to do is just swap values so fast dot bar and the second dot bar equals second dot bar in the first top bar so be careful so this is a uh like a python way so I think uh if you write like this um you will get the error or not there wrong answer because uh so if you write down like a like this so first of all uh second a first value is updated with second value and then so this first value is equal to Second value so that's why we can't swap so that's why um I swap two values in one line like this and then after that just return head yeah so let me submit it looks good and a very efficient algorithm beat 99 percent so time complexity of this solution should be Oda of n where n is the number of nodes in the linked list so this is because the code iterates through the link to this twice once to find the first node and to be swapped and once to find the second node to be swapped both situations have a linear time so that's why time complexity should be order over n and that space complexity of this code is o1 because I use the constant amount of extra space so the space usage does not depend on the size of input link to list so that's why yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Swapping Nodes in a Linked List
|
maximum-profit-of-operating-a-centennial-wheel
|
You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100`
|
Think simulation Note that the number of turns will never be more than 50 / 4 * n
|
Array,Simulation
|
Medium
| null |
1,734 |
That general Hello everyone my name is Anmol and today we are going to discuss and tomorrow question 170 record job notification question tomorrow that come in contact tomorrow means 250 hours ago he has a little question this which is the operation of this question 1720 record edit ok so this The question is how much is that cigarette blade in the morning that we are given the percentage of life by giving orange science and it is written that in such a situation it is not necessary that mother and can be given training camp what is this question but this if it has a pocket we are this question There are nine compulsory in it is written in such a way that chop about hotel and famous is the first question, then in that point question, you have kept the phase element, we have to tell America and do it, we tell it any property, face, used oil is also a record seat, if I am the second one. Demolition global then enjoy difficult visual see it joins inverter criminals then simply difficult use and learn time that can remove that a that irfan why but * elements is irfan why but * elements is irfan why but * elements is not whimsical but fatal tomato's it chief bane tank som dispute in that Require a property on two elements The Amazing property then there is nothing to be done in it Time possible Tractor Pushkar Back element and which is my reviews element Singh told me that this is my Hindu elements Then this element which is this is the period of these two elements Security I have a job of basically a herbal, I kept on increasing my knowledge like this and kept on adding to this group and this group, it will remain similar for the people of this group, Vinyavali Net is automatically the net, I have generated sex between Brad and Rinku Rathore. In the Laker Diet Shiv video, I and my work is done, now we see some people stuck in this question, if we pay a little attention then we will find that we have Vasundhara's question in this question in which N is anything. It is possible and this is not the biggest batsman specific record, we have festivals, they are science magazines because that message is useful to me, it is logical isn't it, so we have to recover and how will you do so, she is matching very sweetly in that. What I am going to show you is very good, that is, it is a project, I know that again I know one thing and not this and if someone will come to Rs 2700, you understand that I had to cover this dam and not that thing which we have cleared our exam. What we need to do is that our element is the first and foremost documentation. If we read the question carefully, it is clearly written in it that when and in it, whatever we mean by them, we have to do that for such and such, we have to decode it, but we have motivation, they mean one sediment in it. It is arranged at any time, you have only one orgasm, this is life, this is us, but I am seriously, if we somehow have a fuss element, then all my work will be done, right? What do I do to you if I look at the chords? Hmm, note that this means that it means that we have to know that because their inverter or their ginger is bare, it means that they are dead audio elements, I have seen them with them, once I know, I took some time. My hence we have to have any further education in this means that it will be of individual front side by becoming an index which is element can be taken to America means acidity secondary mental and will be senior Marathi I will have period of office element and subject is insecure is on s is basically age due to which It will be away from them and one will be ours. Five six class three four ka 120 for of is logical in this I have accepted that my album play problem is meaning 1234 5 to 7 minutes click on se tu agar main one se nikal in tak pura ka If I add it and I cover it up, I only mean the birth celebration of the remind volume and people know, I will take the second one, then I will get a flop education, I will get a professional, I will repeat the spoon of Baroda. I have to remind me for the meeting, this one has to be folded, night, nothing for me, basically. Corresponding Element Gifting Me Easy Fruits Guide to Updates How to Remove You I Took the Whole and One Two Three Four Five Six Seven All Competition I Took This Also Wheat Porridge Africa Took This Too Light You enjoy and see, the only element is this and sharing because all these are cancer and will weave 232. This will give control. Use it. You can eat the video early in the morning and this text message of a dam and a child, I will give it a total, hence this is the website. This will be the answer to this, such good points, I have completed all the less, I take them out and in one bomb I take out others, otherwise this is a family function, because if you send me, I will break away from here, then I will follow, then it is absolutely smooth. Students got these. By doing Odisha, I basically have to record all this in the account of Jehovah once, I have turned on the recording automatically, I have completed it, so I just did not get any more of it, if saving this means that whatever is my element is of If from this statement, because it is the total of square comma forever and automatically my answer will come No, did you do it, let me explain it a little, Chaitra, there is no association in this, so I have sent a lettuce message to him, consider them as enterprises. I took it back and completed it till the end, if I took this entire cord, okay, after that I took this electronic item size, if this account of mine, this option, development, will express all these elements, in this, from my two to the center, all of them. After repeating and tying it across, Sonia, do not repeat, it is right, it means that in the said minute, my butt got cancer, save my this, save my life, right, so this is my first element, so I got my first, after that, you are here. When the account statement comes, its question is found to be a simple match. Do nothing. Simple, the previous meaning of doing this. Regarding the rank warrant, I have asked who is that city and who will continue to lead. I understand once again in this Surya Sudhar notification that I took the whole one and entered it and I took the feet and entered it, the previous song got cancer again, the message one element was left on the tongue, only the central one, so the payment came to me, I did the same basically, I took the invite to the most K should I keep generating the next element Twitter Kushwaha was at that time president get it done if I am doing it there is confusion with the plant in it I have meanwhile maybe he well it means nothing Mez Siddhi Revenue nothing in your serial numbers 1234 serial numbers Have you typed questions from statistics, you did not say anything on the contrary, you will like it if Tiger can address it, OK, index and have added it.
|
Decode XORed Permutation
|
bank-account-summary-ii
|
There is an integer array `perm` that is a permutation of the first `n` positive integers, where `n` is always **odd**.
It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = perm[i] XOR perm[i + 1]`. For example, if `perm = [1,3,2]`, then `encoded = [2,1]`.
Given the `encoded` array, return _the original array_ `perm`. It is guaranteed that the answer exists and is unique.
**Example 1:**
**Input:** encoded = \[3,1\]
**Output:** \[1,2,3\]
**Explanation:** If perm = \[1,2,3\], then encoded = \[1 XOR 2,2 XOR 3\] = \[3,1\]
**Example 2:**
**Input:** encoded = \[6,5,4,6\]
**Output:** \[2,4,1,5,3\]
**Constraints:**
* `3 <= n < 105`
* `n` is odd.
* `encoded.length == n - 1`
| null |
Database
|
Easy
| null |
269 |
hello friends today less though alien dictionary problem there is a new alien language which uses alerts he alphabet however the odor among letters are long to you receive a list of non empty words from the dictionary where words are sorted lexicographically by the rules of this new language derive the order of letters in this language let's see this example if we are given these five words we will return w RTF what does that mean let's see let's first think about in a normal dictionary how do we decide the order of words easy T under the ad imagine if this to add words what is the order of these two words in normal order we know a CD is before the ad because a comes first as NZ so this word should come first before this word so how do we decide which world der comes first we know that we will compare the first different chart Turk that means even if after this a we have Z but after this D we have a it doesn't matter we just need that you know the first different characters of these two words exactly same thing so in this alien dictionary we will also decide the order of these two words by the first different characters in these two words for these two words we know that he comes from comes before F because w RT and w RF these two characters are the first are different characters so far these two words we can know that he is before F and for these two words we know W comes before E because this word comes before this word and there are these two characters are the first kept different characters so W is before E and for these two words we know s before T and for these two words we know E is before R so we get this fault relation and finally we can generate as a Odori which is w e t f so this is odor in the alien dictionary so actually the whole point is try to get the relation of two words and just compare the first different characters okay so H so basically how to represent the odor or the relationship of two characters actually we can use a graph to represent the relationship if a is before P we can use an H start from a and pointing to be to represent this relationship actually this is a directed H and now we know we can use graph but how do we get the final order actually this is the topological sorting if you have familiar with this you know this definition a topological order is a possible if and only if the graph have of no directedness circles actually in this problem we may not have a valid order like this to order means Z comes before X and this to order means X comes before Z so there we cannot make it so we just return empty streets it's there is something in there topological sorting that means actually they have a cycle so we cannot generate an ordering so the next thing is just gets a topological sort of all letters to generate the final result wrap up first is to build a graph using the given words and their secondly to do the topological sorting try to generate the final result okay if you not familiar with the term logic so you can refer my previous video and now we assume you are familiar with topological sorting and now we will write the code well importance in the topological sorting we will need in degree a red in this problem we only have the lowercase letters so we know the size is 26 and we are given the words that's a string array but we needed to build a graph so we can use the agent adjacency list so here's a map the key is a character a sit here and the value is a set of characters there means point is neighbor notes actually the key is points to the set of characters this represents a directed graph a new hash map we are first to do the build graph function and finally we will return a BFS actually is a table logic salt is a graph and they're in degree ok let's write the beaut graph function map - and character serious G and the string - and character serious G and the string - and character serious G and the string words we also will pass this in degree for every string for every word in the words we are first as this character into the map so for every chart in the world q char array will put if absent C and the new hash set then we will try to catch the in degree of each character actually the node in the graph so if I start from one eyelashes or stolen I press + we can only get older by at press + we can only get older by at press + we can only get older by at least two words so we need the two words the first word is the words I minus 1 and the second word is the words I and for these two words we can only you know there we will use the minimum length of these two words so the lens will be the mass minimum first dollars and the second dollars we'll see whether they have the different characters jealous and SJ plus if first search our actor J not equal to second to chart at J we know the outer node will be the first chart editor J and there will be in node chart after shape we'll see whether we have added this relation to the graph if g-get out do not contend this in we g-get out do not contend this in we g-get out do not contend this in we should dirt at the intruder outer set and the at the same time in degree in - and the at the same time in degree in - and the at the same time in degree in - a should increment by one this is because the you know the ASCII code in the lower case they have 26 characters and the we use the offset to represent each characters you know the if a means zero and the bewail means one they are offset to represent their characters so we - ace ASCII code okay so if they once we - ace ASCII code okay so if they once we - ace ASCII code okay so if they once we have a different character we will break because we do not need that you compare the next the following characters okay this is a bit of graph part we fill these parameters G and the words and the in degree now let's write the BFS part actually the table logic sorting BFS we pass this graph and in degree we are try to generate the string so we will use a string builder we know that total charts because we may not generate a valid ordering so we'll compare their size G size right is the total nodes in the graph we will use a cute there will be cute thanks list and the we will add other notes that they are in degree as zero so for charsi in their Chi set if in degree C minus a equal to 0 SP will append this C and the Q of the see so we already add other notes and helps in degree 0 then we do the standard the BFS if the queue is not empty we get to that you know the neighbor node so that means you know the current node will be a cube hope this fatigue gets their current node not equal to not they have never note that means and did you get their curve does size greater than zero no okay we can just continue if we get curl equal to na or we get Curtis are equal to zero it continued because they may do not they may have no neighbor notes in case of the non pointer arrow in the for charm neighbor oh this G get a current note we should their increment this in degree by one so there will be neighbor - a - - one so there will be neighbor - a - - one so there will be neighbor - a - - and is currently the in degree of the neighbor - is zero that means we can neighbor - is zero that means we can neighbor - is zero that means we can offer that to the Q so Q will offer this neighbor and the S be appended this neighbor funny we will see whether this SP Dolan's equal tutor as well as equal to the total charge if we go to tortures we can valid ordering otherwise we just return empty string okay what's the care yeah is it here sorry here hmm string what a diamond told her chars oh sorry Q Street wrong answer what does have me hmm let's check what's wrong the coriander this is a graph right so let's build a graph but if they have to seen you have said to chart right no it's correct so the words mmm first a second tell me first yes correct for not equal to say Oh charlie zero nobody called you out oh sorry this is a second thank you for watching see you next time
|
Alien Dictionary
|
alien-dictionary
|
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language.
Return _a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules._ If there is no solution, return `" "`_._ If there are multiple solutions, return _**any of them**_.
**Example 1:**
**Input:** words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\]
**Output:** "wertf "
**Example 2:**
**Input:** words = \[ "z ", "x "\]
**Output:** "zx "
**Example 3:**
**Input:** words = \[ "z ", "x ", "z "\]
**Output:** " "
**Explanation:** The order is invalid, so return ` " "`.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of only lowercase English letters.
| null |
Array,String,Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Hard
|
210
|
14 |
foreign number 14 which is longest common prefix this is write a function to find the longest common prefix string amongst an array of strings if there is no common prefix return an empty string so we'll have an array of strings with flower flow and flight and no return flow and they went with dog race car and it returns an empty string um because there is no common prefix among the input strings Okay so I have a couple different ideas in a way that we can do this we can do checking each letter so we can start off with f and then we'll check if there's an F in each and then we can also and then from there we'll go we'll add another one FL and then we'll check each and then Flo and we'll check each and then if there isn't a match on all of them then we just return the FL and another way is we'll start off with the whole string and then we'll compare it and if there's a match then we'll remove the last letter and then we'll keep going and if there's any match then we'll remove the other one and then we'll keep going until there is a match and then we'll return that so that's kind of the way that I'm thinking of doing it to make it a little bit more simpler whoa sort the array from the length of each string so then we can so we'll start off with like the smaller so then we can remove less so let's do a sorted array TRS dot sort and then we're going to sort it from the shortest length to the longest and then we'll have a prefix starting off with the first string in the array and then we're going to do a for Loop here but we're going to start off with the second one in the race since we've already had the first one here in the prefix and it's going to be the length of the array and then we're going to have a while loop with starting off with one here with the second one in the array basically and index of prefix and I'll explain the index of in a bit so as long as it doesn't equal zero then we can enter this Loop and continue going and then we'll have prefix equals so if enter this Loop that means that we're going to remove letters because there's no Cloud it's not common prefix so we're gonna use slice here nine minus one and then when it X is it then we return the prefix here okay so let's explain index of let me and also we can run it here so we can make sure it's sorted let's do that and check it see there we go oops we'll have that here checking it okay so we'll have here we'll have sorted array equals that and okay so the index of this is the way it works so when we have so let's say we have flower dot index of the prefix let's say the prefix FL um if it matches anything in the array it's going to return a zero and if there isn't a match it's going to return negative one at least for this example here now let's say we have fls instead of right for the prefix here it's going to return a negative one because it doesn't match at all there's no match there so but if it's just FL there's a match even if it's just F there's a match it'll equals zero and see let's say we have ER and the prefix ER is going to return 0 1 2 3 4 it's going to return four because that's where the match starts from for okay so let's do this we have zero if it does exist and negative one if it doesn't exist so we'll have sorted array I which is one so zero one flower and then right here we'll have flow because that's a prefix so flow is in flower so we it's zero that means we don't enter the while loop now I equals one here but now we're going to two so two flight it's flight here so then we change that to flight now it's flow in flight that equals negative one then because it doesn't exist in flight so then we remove so we enter the while loop and then we remove one and then we check it again f l o is not in flight so then we enter the while loop and then we remove another one and we check it again f l is in flight so that equals zero because it does exist so then now we don't enter the while loop so now we increase now we go to the for Loop and but that's the last one you know there's only three one zero one two so that's the end of the array so now that means we return the prefix which is just FL and this should be right let's just erase this and let's remove the console log as well and let's run it this should be right perfect and let's submit it perfect
|
Longest Common Prefix
|
longest-common-prefix
|
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string `" "`.
**Example 1:**
**Input:** strs = \[ "flower ", "flow ", "flight "\]
**Output:** "fl "
**Example 2:**
**Input:** strs = \[ "dog ", "racecar ", "car "\]
**Output:** " "
**Explanation:** There is no common prefix among the input strings.
**Constraints:**
* `1 <= strs.length <= 200`
* `0 <= strs[i].length <= 200`
* `strs[i]` consists of only lowercase English letters.
| null |
String
|
Easy
| null |
1,944 |
hi friends welcome back today we are going to solve lead code problem 1944 number of visible people in a queue before we go through the description and the examples i just want to mention that my channel focuses on helping people who are preparing for coding interviews as well as java interviews uh this channel has a lot of solved examples explained in details with java code and those are like hand-picked pro code and those are like hand-picked pro code and those are like hand-picked pro hand-picked problems asked by many big hand-picked problems asked by many big hand-picked problems asked by many big tech companies like amazon google facebook microsoft and many other big companies those problems include variety of like different varieties such as dynamic programming binary search binary tree related problems linked list related interview questions string related interview questions as well as you know graph related questions bfs dfs so all those varieties are covered so please subscribe to the channel and keep watching this video and so now we can go through the uh description of this problem and we will look at the examples and how we can solve this problem this is one of the hard problems on lead code so there are n people standing in a queue and they are number from 0 to n minus 1 in left to right order you are given an array heights of distinct integers where heights of i represent height of the eighth person so a person can see another person to their right in the queue if everybody in between is shorter than both of them more formally the eighth person can see the jth person if i is less than j and mean of heights of i comma heights of j is less than max of heights of i plus 1 till j minus 1 right so what that means basically is um so for example this person right this guy can see all people between this guy and this guy right because they are all like a smaller right smaller but this guy is obscured but uh that's what they are saying basically for example this guy can see if you compare this guy and this guy right two guys then he can see this middle also like because he's smaller than this one right so that's what they mean basically by that statement so return array answer of length n where answer i is number of people the i person can see to the right side in the queue right so let's take this example over here uh and we can discuss you know like how we are going to solve this problem so basically uh what the problem is saying is uh let's you can just imagine like a real life scenario right you are standing on line and if let's say there are couple of people between you and there is one very tall person right so you can see uh other people which are between you and that tall person right so uh like that basically right so let's take this example so it will be more clear actually so let's say we are this guy is looking on the right side right so he can see this person right this person he can see this person also and he can see this person so three people he can see he cannot see this person because he is obviously obscured by this person right and this person also he cannot see because he is obscured by this person this is taller so he cannot see this so we have to put three here right because three people he can see on the right side correct so similarly if you take into like if you take this guy he can see on the right side only one person he can see right this person he can see this person right because other persons he gets obscured because of this person right and he's shorter so he cannot see other people now if you look at this person if he is looking on the right side he will see this person right one he will see this person to he this person will get obscured right so two persons he will see right so we have to put two here so that is the basic idea so this person can only see one person and this last person can only see he cannot see anything right because right side it's nobody is there so you will put we will put 0 there basically right so that is what the problem is saying that we have to find out for each person in the array basically how many people he will be able to see on his right side so that is what the problem is so let's look into how we can solve this problem let me back yeah so we can use like monotonically uh increasing stack increasing in the sense is we are looking from top to bottom in the stack right so it becomes like a monotonically increasing so how this uh monotonically increasing stack can help us solving this problem so let's go with this example and first try to understand this so the implementation become very easy after that so let's say first person let's take this first person so we will just put that into the stack right 10 so our basic idea is if you are looking stack from top to bottom it should be always in the increasing order right so now we will go and we will take six right six is the next person so we will add it six into the stack so once we add six now this one is monotonically increasing right from top to bottom so we are fine so in that case we will see who is the immediate next of six right 10 is immediate next so that guy can see six right so we will put one there so we will put one for 10 right okay now after that it will come right so we will just put 8 here into the stack and now we will start looking it now this is not monotonically increasing because 6 is smaller than 8 right so in that case we have to remove 6 from the stack so we will remove 6 out of the stack and we have to at the same time increment 1 for 6 because 6 is able to see 8 right because he is immediate so we will put 1 for 6 here and after 6 is gone 10 can also like see 8 right in that case so we have to increment 1 for 10 actually right so 10 will become 2 now right because 10 can see 2 as you can see here also right he can see these both these things he can see so we will put two here now we are done with eight right so now we will go and we will put five right after eight five comes so now the stack is monotonically increasing right because 6 is not there now so 5 8 and 10 is there basically right so it is monotonically increasing so we are good we don't have to worry we have to increment 8 by 1 right because 8 is immediate next to 5 so he can see 5 basically right so we will increment 8 by 1 so 8 will be 1 now after 5 is done we will put 11 here right so now we are putting 11 here now as you can see after we put 11 if you see from top to bottom now the stack is not monotonically increase increasing right because these elements are smaller than 11 so we have to take out those elements from the stack basically and when we are taking out we have to also increment their count also right so 5 will go out we will increment count for 5 so 5 becomes 1 8 will go out of the stack we will increment count for 8 so now 1 so 1 to 2 it will become right so it will become 2 and 10 we will remove 10 also because 10 is smaller than 11 and count for 10 will increment by 1 so now count will become 3 right so this is what happens after we put 11 now only 11 will be there in into the stack right and um so if you look until this point right i am just drawing this for a second so we are at this point right so as you can see now this guy he can see three correct so this guy can see one so it is also correct right this guy can see these two basically so this is also correct too and this guy five can see one so this guy can see one right so he can see one uh five can see one right so this is how the solution works actually so now we have already processed 11 now we have to go forward and we will process 9 so we will add 9 into the stack once we put 9 into the stack then the stack is monotonically increasing if you look at from top to bottom right top to bottom it is increasing so we have to just update 11 and we have to increment 11 by 1 so we will put 1 here for 11 and after that 9 means he once we take out nine basically there are no ah on the right side right for the nine this guy last guy so we have to put zero there basically so if you look at the output so same output we are getting first three then one then two then one right three one then two then one then zero right so this is how the monotonically increasing stack will help us basically to solve this problem right so let's uh you know look at the implementation so when we are like removing this for example when we added 11 right we removed five then we removed it and we removed 10 so we always keep increasing right and the logic behind that is when we remove five is immediate so it will be increased by one right once five is gone then it can see eleven so we have to keep incrementing that also for that eleven right and ten can also see 11. so we have to keep incrementing for that basically so that is what the logic is basically right so let's look at the implementation uh for this problem so we are just first creating a array result which is the integer array we have to return that right at the end so after that we will just create a stack actually here right and stack will it will hold array right and array will hold integer height comma index right so height of the person and then the index of the person it will hold and after that we are going to you know look through all the heights that's given to us here so what first we will read height of i which is height we will read and we will first do a while loop right so while we are seeing something on the stack which is less than the current height right we have to pop it out of the stack so that's what we are popping out and we are incrementing the value for that popped out elements index right so this will give us the index and we will increment that value of that index here right because previously shorter can see taller person right so previously shorter people can see the taller person for example in this case of 11 right this shorter person can see the taller person he can see the taller person this one we already have removed right so we are not talking about this but this other people can see the taller person right so that's why we have to pop out all the uh all the people who are like uh basically shorter right means who are less than height this height of current person and after that is done if stack is not empty we have to make sure that the immediate next we are incrementing right previous dollar can see the means previous person can see the next person correct so whenever we are there always previous person can see next person right so for ex for example this is uh if we are talking about this like uh um so previous can see next person right so whenever like if you are we are looking at this person then we have to increment count for this person right because he can always see this person on the right side so that's what we are doing basically here and then after that is done we will push the current height and its index onto the stack right current height and index for example in this case of 11 we will put 11 and its index here right so when we pull when we pop out this element from stack we get the index basically right so that's what so we have to get the index here like this we are getting right and we are incrementing the indexes value here right so we can go to result array and with the index and we can increment the value for that index right here also when we are picking the stack we are getting the index of that uh element right of that hi a person and then we are going into the result array and then we are incrementing its value here right so that is what the logic is basically uh to solve number of visible people in a cube problem by using a monotonically increasing stack so let's go through the example that is given to us let's just make sure this works so this should give us um right so three two three one two one zero right so which are correct let's just run all the examples that's given to us so the second example also is correct 4 1 0 so we are confident about our solution we can submit this one so our solution got accepted by lead code so um this is the way you can solve the number of visible people in a queue problem right and there is a similar problem like this that you instead of people you will be given buildings right and you are you have to find out if you are standing on the top of a building how many buildings you can see on the right side right so that kind of question also comes so that's a it's similar logic you know same you can use like a monotonically increasing order of the stack to solve that problem also so any these kind of problems where you have to find out like on your right side how many uh something you can see you can solve these kind of problems using monotonically increasing stack so this one we are calling monotonically increasing because we are seeing from the top to bottom direction right top to bottom if you are saying if you are talking from bottom to top direction then the same uh terminology becomes monotonically decreasing right so it depends on which direction you are looking right so um so that is the way you can solve this problem if you haven't already subscribed to my channel please subscribe to my channel now my channel focuses on helping people who are preparing for coding interviews as well as java phone interviews or in-person as java phone interviews or in-person as java phone interviews or in-person interviews and it has uh if you haven't already checked my playlist for lead code and lean code solutions please check it now it has over 100 solved problems uh asked by many big companies like amazon apple google facebook microsoft and many others and it consists of a variety of problems like dynamic programming uh linked list related problems uh string related interview questions uh breadth first search depth first search like bfs dfs right graph related problem tree related problems are there so please go through it will definitely help you also if you like this video please hit like and subscribe it your subscription is really important to us because that is the way the video can reach to more people they can also watch these videos while they are preparing for their interviews and get helped by the watching the videos thanks for watching the video
|
Number of Visible People in a Queue
|
truncate-sentence
|
There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is **shorter** than both of them. More formally, the `ith` person can see the `jth` person if `i < j` and `min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1])`.
Return _an array_ `answer` _of length_ `n` _where_ `answer[i]` _is the **number of people** the_ `ith` _person can **see** to their right in the queue_.
**Example 1:**
**Input:** heights = \[10,6,8,5,11,9\]
**Output:** \[3,1,2,1,1,0\]
**Explanation:**
Person 0 can see person 1, 2, and 4.
Person 1 can see person 2.
Person 2 can see person 3 and 4.
Person 3 can see person 4.
Person 4 can see person 5.
Person 5 can see no one since nobody is to the right of them.
**Example 2:**
**Input:** heights = \[5,1,2,3,10\]
**Output:** \[4,1,1,1,0\]
**Constraints:**
* `n == heights.length`
* `1 <= n <= 105`
* `1 <= heights[i] <= 105`
* All the values of `heights` are **unique**.
|
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
|
Array,String
|
Easy
| null |
64 |
hey guys uma here and welcome to another one in today's video we're going to be going through lead code problem number 64. minimum path sum let's jump into it as i've said in all of my previous videos the first step to solving any programming problem lead code or whatever is to read and understand the problem statements i've taken a screenshot of the problem statement here from leak code and let's jump into it the problem statement states that given an m by n grid filled with non-negative numbers non-negative numbers non-negative numbers find a path from the top left to the bottom right which minimizes the sum of all numbers given along its path note you can only move either down or right at any given point in time they also give an example here where the grid goes like this is a 2d representation of the grid but they also have an image here which is pretty good for us to understand the output is 7 the explanation because from the top left which is here to the bottom right which is here the minimum path goes from one to three to one so that's what they basically said here now it is worth understanding what the problem is asking for right the input is a grid and the output is seven here they give an explanation given the path but you know they're just trying to help us understand what the solution is so now that we've read the question the first thing we have to think about is um okay let's just say what's going through your mind this is one step that a lot of people often forget during programming interviews say what is going on in your mind right say your thought process you're there you and the interviewer there to solve the problem together right you're gauging how you think it's not just about you coming up with a solution they want to hear how you come up with the solution and i know the proper answer to the question but when i saw this question the first time the first thing that came to my mind is a greedy algorithm is an algorithm that takes the best choice given all the options it has at any given point in an algorithm so let's give an example using a greedy algorithm it would start from one right which is the top right corner obviously now from one we can either go to three or we can go to one a greedy algorithm would have chosen one right because um we're trying to minimize the sum to we get down here and if we're trying to minimize then ideally we should go one because one is smaller than three but right off the gates that doesn't work because we can see clearly here in our solution that the minimum answer goes through three so if at any point in time we're picking the minimum between our two options right when we have to go down or when we have to go right if at any point in time we're choosing the minimum in those two options then that wouldn't work right um quite frankly clearly that wouldn't work so at this step i would backtrack right i tried thinking about a greedy algorithm it didn't work clearly i stated why didn't work i would then backtrack and say okay um what's one other way that i could use to solve this problem and quite frankly brute force right as a matter of fact some people would say you should have thought about the brute force method before even thinking about a greedy algorithm but i don't think it matters um if you have a proper way or if you have an optimal way to solve a problem before you think about um the brute force then that helps right you may have thought about the brute force but either way just say your thought process right now i'm speaking to you well i'm speaking to a camera but this is how i would talk to an interviewer right i'm telling you everything i think so um we tried to read the algorithm approach to try to solve you know the most optimal way it didn't work now i'm going to step back and say without using any fancy algorithms that are blind what is one way i can try to solve this problem brute force so at any point in time we can either choose to go to the right or we can go down right now that we're three we can either choose to go to the right or we can go down again from one we can choose to go to the right or we can go down if we draw this out as a tree it'll look something like this one three well from one we can go to five or we can go to four so what that would look like would be five or four from three we can go to one or we can go to the same five so this would come down here like this and we would have this going to one from one we can go down or well from one we can only go down so from here we would go to another one here from five here we can go this way or we can go this way so we would have five going to this one and five go into another two now from four we can only go to two so it would go this way to two um from two we can only go to one here and from one we can only go to one here so this is two on the one here then we will come here this may be a bit hard to understand over the lives but um try to draw it right basically what we did was is a two at any point in time we can go down or we can go right we can either go down or we can go right and if we use that to abstract the 2d array we can come up with a graph like this which basically means um we can then come up with an algorithm right which basically says um start from the roots here which is one then pick a path right go down this way maybe this way we get to three then from three we can either go two choices again and at the end of the day any path we choose to go down is going to end up at one we can then add the sum of all the numbers that we encounter through any of our multiple paths and it'll eventually come back up to one it may be hard to visualize but this is actually a common recursive problem so i would suggest you go through it there's multiple problems that have the same structure i would suggest you go through it but that would be the brute force method right start from here um you can either go this way you can go this way well choose to go this way from here you can go this way essentially you're exploring all the paths down through the tree and when you come back you find the minimum of the both of them right so if the minimum of everything down here through a specific path is smaller than this one then you will go with this one let's take a look at what that algorithm looks like quickly let's take a look at the solution for the brute force algorithm i've pulled it up here if we look here at any point in time during the if first if statements um if we're at the beginning of the grid we return the maximum value right the next if statement basically states that if we're at the end of the grid then we return our um the grid value right which is basically this last one here then the final statement says if at any point in time we're not at the beginning or the end we return that value so of the spot that we're in then we calculate the minimum between if we go down or sorry if we go right or if we go down it may be kind of hard to understand until you draw it down but what would happen here would be um we would start with one right from one well we have two options right we can either we will return the value of what happens if we go one which is um here plus the minimum of if we go down to one here or if we go to three here which is basically calculating going down one and going down three now in the recursive function it'll call itself right so what happened is we would now go i plus one which is three right three would now do the exact same thing and calculate the minimum so it'll go all the way down then percolate all the way back up until we return the minimum between the both of them okay this is the brute force algorithm obviously the time complexity of this would be um 2 to the m plus n why simply because at any point in time where we have two decisions to make right we can either go down or we can go left and if you if we draw it um the way we did here in the case of a tree um here we can go this way or we can go this way here we can go this way at any node we can go two ways right the maximum we can go is two nodes and two ways and the number of nodes are m plus n that's why it's big o of two to the m plus n this clearly isn't the most optimal way to do it so let's try to figure out um the most optimal way to do it the proper way to do it is dynamic programming um the thing about dynamic programming that i don't like is a lot of times when you see the solution they just give the solution right to you and you mean it's not it may not be intuitive for you to come up with that solution during an interview or something but i bet you and i guarantee you the only way for you to be comfortable with it is to practice more and more problems the way of solving this problem using dynamic programming is very similar to the way of solving a bunch of other problems during dynamic programming and at first it may be weird to kind of understand or visualize but once you stick to it and you kind of um go with the flow right it won't make sense the first time but then when you start when you continue seeing it when you see multiple problems and you practice it the pattern will start to emerge and you see it so let's take a look at what that would look like right here i'm gonna remove this guy here and i'm also gonna delete this picture here um clear this here okay dynamic programming basically breaks down a problem into smaller problems so let's take a look at what that would look like in the context of this question let's say we had a 2d array that's a 2x2 array right so let's take this sub array here right here let's stick this up already right here that would look something like this five one two one let's ask ourselves the same question what would be the minimum path sum to go from five which is the top left corner to the bottom right corner knowing that each node we can only go at each node we can only go down or right well that would look like this well we can either go from five to one then from one to two or we can go from five to two and then from two to one here either way let's kind of calculate what would happen from each node right so say we have another array here and we have the number one right from one here how can we um from one here what are the number of ways we can get to number one well we can only come from up here or we can come from the left here that those are the only two ways we can get to one right so if we come from the left here right what would that path be right so let's what would the sum of that path be let's think about it this way if we come from here right and we're going this way the cost of going to one from two would be two plus one so it would have three here right so meaning if we were to come to one from this way we would have to add the cost of where we came from which is two then two plus one would be equal to three now if we're to come from the top here which is from one the cost of doing that would be one plus one which is two right so now at this point in time we've broken down the problem into what would happen if we come from either the top here all the way down here or here now we've seen that as two now because we're starting from five right five has two ways it can come to one right as opposed to two that had only one way which was here and one had only one way which is here well five has two ways five can come from here then go down here or you can come from here and go down here right so let's think about what that process would look like if five has two options right at any point in time it wants to choose the minimum that's the key part here the minimum right which minimizes the sum so what's the minimum between three and two well the minimum between three and two is seven wow so what's the minimum between three and two is two so what would happen is rather than coming from here and going here knowing that it would be five plus two seven plus one eighths so this whole pattern would be eight we would rather go from here which would be five plus one six plus one seven so we'll choose seven the second one we chose seven is that we've already calculated that if we to get to one from here it'll cost us two and to get to one from here it'll cost us three well our number is constant right so we want to choose the minimum between both of them well so it would be five plus two which is seven and that's why we came up with seven so you realize that if we keep doing this right at any point in time we're choosing the minimum between the two paths that we have well if you have only one path then we have to choose that path but if we have two paths then we have to choose the minimum let's go ahead and basically redo this whole 2d array in a dynamic programming method so what would happen would be would start from 1 here now if we are here right and we want to get to one we know it'll cost us three because two plus one is three so it would have three similarly if we're at four and we want to get to one right it'll cost us four plus two plus one which is seven but we've already calculated that from here right so we'll just do four right we will do four plus whatever it costs two to get to one i'm going to repeat that again to get to one from four all we have to do is say okay well we want to start from four plus whatever it cost two to get to one because that's the only path that we have which is four plus three which is 7. now we're going to come up here to the next row here right now let's see how much does it cost 1 to get to 1 from up here well it only has one way you could go right it can only go down so the answer is two now we'll come back up here in word five here right now five has two options as we stated earlier right you can either choose to go this way then this way or you can choose to go this way then this way now all we have to do is say okay what's the minimum between these two paths right between this one and we've already calculated them as two and three so five would basically choose the minimum between here and here which is seven to make sure that's correct we can again look at it this way five plus one six plus one seven or five plus two seven plus one eight right so we know that at any point in time from here to get to here the minimum we can do is seven because we already calculated it broken it down into smaller problems now let's go back here we're now at one right well from one we wanna go to here right we can either go this way or go this way right so how much does it cost five to go to one well we've already calculated that as seven how much does it cost um four to go to one it's the same seven so at this point in time it really doesn't make sense sorry so at this point in time it doesn't make any difference right so it'll still be eight regardless right now we'll come back up here right so how much does it cost um how much does it cost one to get here well one can only go down right it can go to the right anymore so we'll see how much did it cost this guy to get here it's two so in this case it'll be plus our value right because we're trying to get here so how much did it cost you here to get here plus whatever i have which would be three now we're here right um how much does it cost three to get here well for three to get you can either go this way or you can go this way right how much does it cost you to get here well it cost me three to get here plus myself three right or how much does it cost you to get here well it cost these guys seven to get here right so we're going to pick the minimum between three and seven between here and here right three and seven here and here plus three would be six right so the minimum between here and here is seven and here right seven and three so we'll pick three plus the minimum which is three which would be six now we're here right um at this point in time right as we're here we can either go this way or we can go this way and we've calculated how much it'll cost to go from here all the way down to here using all the multiple paths that it has or from here to go all the way down to here using all the multiple paths that it'll have well we know if we go through here it'll cost six or we know if we go through here it'll cost eight we're picking the minimum at each time so we'll pick six plus one that would be seven and that's it that's basically the solution of the problem using dynamic programming so we'll basically have to either we can build it and then we can build this in a new array or we can build it in the same existing array there's also another way to do it with one array you can go ahead and take a look at that method yourself if you find it more intuitive that helps but this um this method definitely works another way to think about it is we're building from the bottom up right um back to back swe made a really cool video explaining that process right you know you can either go from the top down or from the bottom up in this case we're going from the bottom up right we're starting from here and figuring out okay how much will it come from here similar thing how much will it come from here right since we've broken it down into smaller problems we're going down we're going back up with each step again it may be confusing right now i guarantee you when i first saw this thing it took me a while to get used to it took me some time to figure out how to even come up with this but the idea is to break down the problem into smaller problem right that's why i started with let's just take this sub array right we can either start from here go up here right to go to here we can only come from here again so there's practice it visualize it try to solve more problems that have um that have this type of scenario right dynamic programming the multiple problems like this so that's the way to solve this problem let's jump into the code okay now that we're back to the code this is how it looks um you can use java or python whatever language you're comfortable with solving um i'm going to use java so if you remember in our solution the first thing we need to do is create a two-dimensional array right is create a two-dimensional array right is create a two-dimensional array right the array that would help us break down the problem into smaller chunks right so we do that by basically initializing the new array so ins i'm going to use the same syntax in the solution just because if you want to go through it's basically the exact same thing so in dp dynamic programming array is equal to new int in java you have to initialize the array with the length and the width so grade of the gray dot length and you know grid first column okay now that we've initialized the grid so the new grid this grid right here that'll store our solution the next thing we need to do is start doing a for loop right if you remember from the solution that we have here we started from the bottom right corner again set it from the bottom right corner so whatever iteration we want to do we want to start from the bottom right corner as well so we'll go in and know what starter folder right so for and i is equal to grid dot length minus one right um grade.length minus one right um grade.length minus one right um grade.length basically gives us the number of rows now we want to do grid.length one now we want to do grid.length one now we want to do grid.length one because we are using zero indexing right so we want to start from the last row right so there's zero one two three zero one two sorry right so there's three but one to start from two we to start from the bottom row the last row we would want to go um from there we want to keep going while i is greater than or equal to zero and we want to keep we want to reduce i negative right so the next thing we want to do is so for the last element there right the next thing we want to do is we want to get the last column as well so for end j it's equals to grid at zero the length minus one while j is greater than or equals to zero as well j negative okay so the first step that we want to fill if you remember the first thing we did while filling out our array was to start from the bottom row right we start from the last element then we want to keep going this way so let me show that on the screen here so the first thing we did was we started from the last row then we went this way to fill them went this way to fail then we went up then we went this way so we want to start from here and go this way right so the first thing we want to do is we want to check if we are at the bottom row and the way to do that is we check if i so if our current row is the last one right so how we do that is we do that with a simple if statement if i is equals to grid dot length well if i is equal to great dot length minus one right now if we're at the last row and we also want to make sure that we are not changing the last element right the last element in the grid is right here right so we want to make sure we're the last row but we're not the last element meaning that if we're the last row but j is not equals to um the last column as well because if we're the if i and j is equals to the last and last then that basically means we're at the end here and we don't want to mess with that number right we don't want to change that so to do that would make sure we're at the last row but we are not at the last column so if and j is not equals to grade of zero the length minus one dot length minus one right so if this is the case it means we are somewhere down here right if that's the case it means we're somewhere down here which means that we simply want to say um if we're here we want to simply get what is in front of us and add it to our current value to get 3. so if we're at two we want to get what is in front of two which is one and add it to our current value and we get three right here then if we're at four we want to get what is in front of four which is two and add it to our current value um sorry which is three from our dynamic programming array and add it to our current value and get seven so what that would look like would be dynamic programming array of i and j is equals to the grid of inj so would be our current grid plus one in front of us right so it'll be dp dynamic programming of i and j plus one so again let me try to explain that on the ipad as well so for this is our dp array let me just write that down here this is dp array and this is grid so what we're doing here is saying at any point in time as we're looping through um our grid if we are at the last row here then gets dp of i and j so get this item here um get that index and say grade of that item plus one in front of it that's how we break down the problem into smaller ones right so that's what that would happen here now the other option is if we're at the last column as well right if we're the last column we can only get what is directly below us so we have to write the condition for that as well so if um else if j is equal to equals to grade and i is not equals to is not equal to minus one then we simply want to say dp of ij is equals to get whatever is one below it so it's going to be grid of i comma j plus grid of one row below so i plus one right so it starts from zero one two so i plus one and j now we're at the point where we've we basically handled the two extreme cases right so this row and this row right so we basically handled the last row and the last column now at any point in time if it's not the last one the rest left column if we're in the middle right we want to basically take the best option between what we will get if we go right which is which we've already calculated and what we'll get it will go down right so that's basically what we're gonna do next right so we're gonna say um else if we're not at the last row so if j is not equals to grade i'm just going to copy this here right so if we're not at the last um column and we are not at the last row this is the last row then basically what we want to do is want to say the array that we're creating at i and j is equal to the grid at i and j plus the minimum right so math dot mean of the array of the dp array so the dynamic programming array of the values right so if we're here again back to the ipad if we're here right we want to take the minimum if we're trying to calculate the value for here we want to take the minimum between here and to get here we're basically going to add the column by one and to get here we're basically going to add the row by one so we'll say dynamic programming of i plus one j and dynamic programming of j plus one i let me just make sure to look to make sure this is correct yes and then finally if um finally what's happening is and then finally what would happen would be um so we're not we basically have the first case here stating that if we are at the last row but we're not at the last column and if we're at the last column and we're not at the last row so this is basically helping us not to change the value here right in a new dynamic programming array so essentially what we've done here is we've tried to fill in every value for our dynamic programming array except where we're the last row and the last column so if we're at that place then we simply want to get the if we're the last row and the last column which is basically our destination we want to get the value of the destination and input it into our dynamic programming array so what that would look like is we would simply say well the last case would be um i j is equals to grid of i and j um yeah that's pretty much it then finally if you remember from our array here the answer would be the final value right the answer would be grade of zero right so we simply return um dynamic programming of zero dynamic programming array of zero and this should be it um we can go through it again one more time right we're filling in a new array that should have the results right that basically has the smaller problem broken down into um the bigger problem we're basically filling in a new array that has the bigger problem broken down into smaller chunks so that what that would look like would be start from the beginning if we're at the last row and not the last column then basically take one in front and add to it and if we're at the last column but not the last row then basically just take one from the bottom and add to it otherwise take the minimum between the two points of if you go down or if you go right otherwise just take the value and this would actually be the first case right because we're at the point where i is equals to the last one and j is equals to the last one so it'll actually fill in the last value which is zeros um which is um the bottom right case first and then it'll then build it backwards so let's run this and see what that would look like okay syntax errors pattern me i'm used to programming in python and python doesn't really care about um colons it's been a while since i've done this in java so there seems to be a problem with our logic let's basically try to debug it so um i figured out what the original problem was we were making i made a mistake here it should be dynamic programming of i plus one j and i and j plus one the first index is always the row but i made a mistake and swap those two and i tried it and i got another error here it's still not giving us the right answer so um i'm gonna take a while and debug it again and let's see so um this is another reason why you should go through your code again i found a problem so when we're creating a new dp array we want to get you know we want to initialize the value of the dp array with um the grade value and the place from our dp array not the grid again so they should say dynamic programming array of one so if we are the last column and we are um are we not the last row we simply want to get the value from below the dynamic programming array and add it to a current value to get the new one and so that should currently work and that works if we submit it that basically works so yeah that's basically the problem it's a tricky one it also i think lead code also says it's an it's a medium problem which i can understand why it's a dynamic it's a classic dynamic programming problem and the only way you can get better problems like this is to solve them they may not come intuitively so what i'm saying is it may not be as easy as it may not be easy for you to recognize them at first but once you basically keep solving them you describe you basically see a pattern in the problem and it automatically becomes easy intuitive and intuitive thanks for watching and catch you on the next one
|
Minimum Path Sum
|
minimum-path-sum
|
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
**Note:** You can only move either down or right at any point in time.
**Example 1:**
**Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\]
**Output:** 7
**Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum.
**Example 2:**
**Input:** grid = \[\[1,2,3\],\[4,5,6\]\]
**Output:** 12
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `0 <= grid[i][j] <= 100`
| null |
Array,Dynamic Programming,Matrix
|
Medium
|
62,174,741,2067,2192
|
253 |
Which care for Ajay? Good morning everyone and good evening good afternoon from distance. You are watching this, okay, you will get 100 paise for a few days in this video of Kaliyuga, today we will do Ajay Kushwaha in the meeting room, we will approach him from the country for money because Meet one will be Chronicle of Rajasthan and rank if not then let's start playing one. This is the simple question. If you can understand it then ok. Next we will keep it in the fridge. There is something to be memorized here. If we do this then Titans Always Fight ok. So, first of all, let us understand that here in the input, we saw that we will have a lot of meetings, skating shoes, so check the past, if I am a college Madras person, he has a lot of meetings all over the country, then a business man. There are a lot of meetings. Okay, so there will be a lot of meetings. Cigarettes will be the starting point and the only thing in their life is that we have to tell you that you will read the comment to advocate the room for those meetings. Ask for money. Let's say that you are doing business. Yes, now you are okay with a lot of meetings, so how many rooms will you read to advocate, to finalize those meetings, you have MS Word, there are a lot of buttons in this system, always here, prevention, give a stationery, think that they want, okay, then take a devotee and explain. I am playing portion were the latest report chapter arrangement that this meeting was ordered so we have all these bay given powder and full 5 meeting is okay and this is their information beans don't start science pendant so first of all So tell us from whose permission we will get, if we hang an effigy, then it is okay. I have all the starting point and second column in size and points in the first column 138 0216 selection process meeting time 10 medium to settings pay tomorrow meeting 4 new wedding five That Simon Commission is only this problem, first come first time date is fixed, so in this way we can break it, further we can provide computers, okay, this application of Sense follows the format, so we always have to think about the input that the input is of computers. Let me remind you that from this point you will clear all this preparation, assembling, preparation in five meetings. You will have to subscribe, so I did it in 2012, this above part will be clear. Now if you understand from this, I will do exactly five observations on this question. I want to see, okay friend, how will the computer get the answer in three minutes? How many meetings do I need? According to this input, what else should come, so to understand that thing, first of all I say that. If there is any person who can tell us in which order the voting bills will be passed, so that you can go and see, this one is unknown, how a meeting is held with a mind, that is, at what time will it end, one meeting is one minute and this one is The meeting server is being started, it is being started on the line, then it is written in the last section, if you are involved in the sunshine, then some satsang has been formed. I am saying that first of all, you have to hand over all the settings of the time to define an order. I will do it, if I post the meeting according to the star, rough, okay, you do Bigg Boss carefully, here I am driving you a little bit towards myself and he said, the last six are difficult to understand and subscribe on coupons pay time. So regarding that, from sex seven to eight to tender notice writer, now in the hectare we have done the sadhu registrar, we are just repeatedly saying which meeting will start first, which meeting will I put near him because the meeting started after that, inside this I would have to find that inside our Dow asset, there will be no comparison with its religions, so a little benefits, okay, now let me ask, how can I make a solution in JUST, I see the first meeting is starting from one to one, okay, one thing. And you got to schedule every meeting, the fetus locator will not come, okay, so definitely see this, there is a request from such a punch that now China meeting is starting, just in between, I should loot it, hello wait, then latest updates. I have created only one room which is bad because inside it I said that it will start at ₹1 because inside it I said that it will start at ₹1 because inside it I said that it will start at ₹1 and end at 3. Keep it in a special meeting like I said that this is the room located, this is the rule, from the end to the head, next time. I have from Baikunthpur to Six So Look, now I do n't have any feeling, what will you have, if you want to extend it in the opposite direction, let's move on to exploiting WhatsApp, okay if you do n't explain it then we will see where my old form is. If someone is left vacant, I will give this meeting the definition of metro. If there is any meeting form shown at this time, whoever explains and advocates from the meeting room is in full use, then I said, ok friend, this fort. I am a cake different and will have to create okay this and just and reference co me 151 this to roam then loot I booked someone in this then take it six times inside okay now this information comes third meeting that and third meeting is car decoration One by one, they are even checked, it will be submitted, it will end on S, so now we want to do conservation, we will see in which room the meeting has ended, so from now on, look at this Raj Yoga, a room in one and raw two both. Only meeting minutes have passed, now it will be the turn of this seven and 80777 platform time, your seven has already been consumed, so at that time this meeting is unnecessary because sex was worn and Yagya Bhoomi would be empty and the tongue would also have been eaten because rule six juice. I will stay together in that expert period job meeting time, if there is a war, then I get seven or eight placed in the room in either of them because border design fighter means only by doing meeting scheduler, it means now this one is going to book seven. From till Cricket, when will I get Room 1812 vacant? Woman, if she gets fruit, then I will get water from their bathroom. Next meeting is coming after today. From Eight to Tank Waste Fakir, I saw that when it is 854 on Vanshj time, then you are seeing this. Or add human also because it was over on the team and you also eat the room so if we have that we can adopt any moment only if I do that meeting stadium means in which room do we update it in which one If you are able to keep it rejected, then it doesn't matter the meeting, then let's check post. I put water in the peanuts and added that in the last throat, I said, go to hell, your meeting can also be held. Okay, now see, the next meeting is with mines. Let's check the fitting, these are the people who go for a lot of money, the forest is not empty, you ignore the room, the mantra of the room is deep, the guava is running hidden in it, for this function, medicine before the time, don't disturb me, till the time, this is ₹ 1 point is the room so till the time, this is ₹ 1 point is the room so till the time, this is ₹ 1 point is the room so dawat stanley room is empty Vishwash got up but was finishing so I have heard the girls and stomach place 963 meeting here ok now this recipe if you thought a little carefully and heard a little you must have Sa absorbed edifice of being always comes and people who observe you all meeting spears gone ok now whenever there was a meeting we wrote far away in that all these meetings can end so the question was telling only the meeting schedules that we What is the minimum number of rooms needed to update these meetings? What will be the answer to this? It was two. Okay, I just gave bread that day. Work can be done in the meeting. I will not give you peace even in the bedroom. Okay, so the next day you will find the deceased. You will get your interview, you will get the status of the interviewer, you will get control, what is the minimum ransom you can work on, the points on which you should pay attention, bar association can come out but face that whenever no one is meeting Indian, I speak, whenever someone you meeting, we Let's see Raghu Dixit is a garlic from total problems, either one question is that I have not found any previous meeting room cream, I have not found all the previous meeting rooms in this file, so for this, I will have to create a new meeting. I including time out previous quick reassign rooms which were arm pinpoint I confused saharsa in all new meeting room that a new meeting room has been signed visible on 1s ok nerve 231 no meeting comes then it could be that there is no previous assignment The room which is there is priyabhanshu be okay so any which alarms side any admin off but e once the entry system is compatible with the basis of job hua hai off computer in this new meeting is quantity please situated scientist was looted that chicken so friends Yadav friend, will you come to the room or from any 12345 number which is now free, you will be famous in it, okay, once the ad is in the fort, now we are also inches, so I trapped the interviewer, okay, look at it in this way, now apart from this, friends. How will we make updates time to clear Madhav, now let's start writing this, okay loot, keep this thing in mind, the thing in this and which turn off all is 24 but standard unit proof like 10 zodiac signs came in between that we have. Both of them are empty, then it's okay, no meeting is tight, so now this new relationship has come to the meeting that there is some print rotation that I have to do the meeting in this form, he only has to do the meeting, this meeting should be straight, in the mosque form. Yes, it does n't matter, so any harm, your profile is fine, now we will do it in this that the information I have written here will be used on this in the in the in the most advance meaning it will be a bit relative that I saw that its compatibility is completely taken care of. In the format, I have asked the speed of the phone only once, from there it is 123, time consumption, lead milk, faco two, sex 0123 40 amazing, first of all, select it and on the basis of The 108 send on the basis of that star time what happened to it that we jogging man will go after this meeting who means like I plate first meeting is over first means just which meeting is starting after the meeting inside it is back side Have to do this magic and family decide which meeting will start, you will have to watch every meeting, this is the shortest meeting starting time, after this, which side of the meeting will happen, you will have to search for friends for that, friend, after this, which one is bigger than that, the smallest difficult time. After this, decide which meeting will be set and then you will have to search. After this, the smallest mark is time, then search again and again. In the operation of the description box, instead of this, you can clear it in advance to search. If there is a puncture, we will set it as the starting time, then we will get that all the meetings will be spread easily, why will we be able to see which meeting is starting before the first, this is also the mantra, then only when. Starting point events for this the starting point 600 interesting points 106 2012 450 fix to work in a little fold way I will do it like this sir us what have we done MP3 ginger symptoms name steadims ok his life is long different is different starting type people See, now we are going to use 15 words in this, which I have used in some video. Okay, so if you have seen the video of my first camp lectures on social, then you will understand this thing in it, their punishment is someone unfamiliar. If you keep it, then it is a commissioner, that means you will have to make an appointment in the old video, here and there you will find the link in the description, so nothing to worry, according to the court, if you see it once, then you will be in the water in front of you, like we have, make me smart and travel. Why do I make a starting point presentation in the office? Okay friend, if you want alarm in SEBI mutual, you can write bird game of primitive then last year higher better able to present not this information but just for intelligent comparison, now set according to this topic. Have to do 90 lip-smacking side 90 lip-smacking side 90 lip-smacking side that now is the time Rock Band Service MP3 Birth in our pass Passed minimum balance zero with starting time in the interview I will come again to the lions A letter This message is completed When the bus is sent message that Paramhansa raw1 Pusht any two interviews Go to the office in the job. When I say that every person who is there has to be identified, then at any time you have to compare these towers, give coffee special, okay, then I did not fall down. I will get soft hata along with the starting time in increasing order. Now after this, what will be the charges in Jail WhatsApp? Look at the first meeting. I am starting this first meeting with the mind that I will have to provide a room for this. Punjab Below, it is not from Hansapuram side, so I sent it in Lightroom. Okay, but when a meeting comes, the six problem with it is that how will you know that the Phulari meeting is over, will all the groups go and check? Do you think that this is cosmetic or as if the hands have become very big, there is no meeting in this, I have already smoked a cigarette in the meeting showroom, so what can I praise? You will come and see that the meeting is over here, the meeting is over on the channel, that doing this is a bit much. It will take a bit of a post because of what we can do now we can do that we have a we will finish these thanks will use that told me which meeting room is the last one like I create a little bit first edition of what I try to say that the primary fuel is one letter which works as a Prime Minister, I will do the same at a time Mahatma Subscribe There can definitely be something else which only he does a lot in a party whenever someone like 1010 was created initially to my friend This trap was empty, I was not signing even a single meeting, so what did I do inside it, not only the bomb, I sent three in it means that I have Chrome, whoever roasts it, I found the closeness of this dynasty in Science and Factory on Friday. Let's maintain the side, why is it awkward, according to the minimum, there is further family data inside here, so I will just give the minimum here, experiment, read the letter post in your back, Hello friends, why don't you tell that even now the meeting has been formed first of all, now the main Time will be free, it is on the skin, so now let's know how to use it, many verification tabs, first meeting, now comes the turn of one, next meeting, collection and curve bittu is getting blasted, okay and the section is us, so if I want to set the PIN that my When did the meeting room become vacant? Only party Modi has found the prime that your meeting is lost in three seconds. If in three seconds and third army after meeting him at home then he will start me on the highest to waste second and it means I have a new opposition. You have to sign in a new form, it means water on top of the barrel, its end point is newly appointed and sign on this side Shravan main to apni do bluetooth setting meeting hai tu se sex prank etc aayegi we will come only six end points like I this I Said that the festival is on minimum 340 or there is a fight between it is always on my mode and Samsung On8, most of the meetings go on juice start condition, I saw that it is the minimum of Prime Tube, about this I am only in it. Friday has been kept, tell me your setting, okay, and friends answer that we have minimum, so I tell both of them that why does Friday keep any element on the pic first, you are jointing it is ours. Minimum pending time Muthappan The time at which a room is vacant first That seventh comes meaning Next video Delete 0826 Which meeting has to be done Which meeting room is not empty sacks So checked Brand name Reason for fast Any media group Empty radish Third In a second, Vaibhav should be seven and eight. The meeting was going on. What can I do there? What will I do? Will I send this three on Friday? Okay, that means now the vaginal meeting is over. Inside the room, I bought ₹ 70 liquid is over. Inside the room, I bought ₹ 70 liquid is over. Inside the room, I bought ₹ 70 liquid and liquid from chain. I am able to keep the end time of when the All India meeting will end, on Friday. Thank you friends, thank you all from Westland, this hand which nuvvu will be half empty by that time, so I have taken some steps to the minimum, at least one page number 66. Now that Lord. Vishnu's incarnation is that if any room was vacant, first of all we would have eaten it, then it would have been removed, which room would be free in the sex kevada essence process, inside it, only the buttons are getting finished, directly and depending on the opposition of the writings. Do means do front recovery decree do from one to one again did you see when our meeting room is getting free and tells if there are six then what did I do in place of a six Punjab meeting service on six the meeting of the end of six pack there But I institute the next meeting because the system was there, now it is covered, so its end time will be taken for prime, I am fine and this test is less crowded, maximum two forms in one house, ₹2, meeting is going on, so ₹2, meeting is going on, so ₹2, meeting is going on, so who will be first? There will be a meeting with end tagged meat inside it uses the property, any free food just does n't matter, so friends that I do n't know which blood on free mode, she tells at what time the show Next one meeting will be over, he will use the same to know whether we have rooms, gym, crowd or not, he comes from such a tree with this, then the team, now the starting time is 9:00 on Friday because I will watch it on TV. The time is 9:00 on Friday because I will watch it on TV. The time is 9:00 on Friday because I will watch it on TV. The upper lip time is just the cloth that there is an additional 9 inches meaning that this meeting will have ended before it expands so I get it done Prawn is willing and there was a meeting ending at 198 lead there in my mind From to shooting was done on schedule and Prime Kunwar 115 is that now to hide a part to teach a little silver, that law is understood, I have another meeting tuner card application, friends, its the soil of all this, just a meeting is posted and that starts. Your fee would have been from no to 1653 My acting I leaked the text to the media Now look, a meeting is starting at nine Both meetings are over for you There is a lot that I will be free It is ₹1 on time That I will team them But 100 will be the is ₹1 on time That I will team them But 100 will be the is ₹1 on time That I will team them But 100 will be the minimum button of ₹ 10 for both of them, then it means that the minimum button of ₹ 10 for both of them, then it means that the minimum button of ₹ 10 for both of them, then it means that the first meeting will be free, the first one will be free for us, it will be tan free, here the meeting is not an essay but the science part is not less but it means that I have to start this meeting one more time. Nehru will have to be made. To make Nehru means to make a doorman. I took the teacher from that point and implemented it and on Friday I am able to keep the trained one. Notice towards taking 56001 entry that tomorrow my front is on this side. That tells how much anger I have. Why if you think wide then why such sexual intercourse was such a meeting was found which need some other meeting in some other room you can type your means there is 1 rosary and about that 15 comes primary fuel if I was any meeting Whose time is after my end time, when is the first meeting over, after that you were asked to practice and you had to keep him, which means that if I get acidity, whose time will be given, in this, the time of both of them is less than the minimum one time, which means that I will have to create a new look, my work is to be mixed, so I insulted her on Friday, because the size is left, it is my meeting, at that point reminding me how many meetings I need, I write it once and show it. Again and will do their cleartrip, now a little gap is left that this agree but it and since the fuel will sign in again, first of all, priority, what kind of work, time degrees, Kabir listen, recruitment's mother pride school, internship, find cigarette, then this is below in a little. From lemon foot tune that I Indian take friend's to make message tell side and science means times means it is like this means a cup of any of my room ka comeback now any of my disease is olive okay why crime is point minimum So we don't need to handle and we don't need to handle all the Twin Towers meaning short intervals with sexual intervals that Holmes's list is a [ a [ a that tenu sa the state on loot if our party missed In size pictures, it means that any meeting has been scheduled till now. Okay, so this is the side pictures here, then let me help, I am the first meeting call planes, permitted to start, let's start, I said, you are Rayudu's interval. But put two of his that everything goes on in English, any interval comes in his first index, I sign in the halt, acid point to that, time will definitely go by doing the test, friends, this front and then skate first and what is the effect on him, his entry fans sign in four. Years that if the size of the parties were zero then it is okay, now I have to decide that if no one comes to the meeting then secondly we will have to create a new form of Ayush Yadav that by smiling he will be taken off account so it lasts for time. What does Priority Q Khan Peeth always tell us that which fever has the least time back? First of all, we have to eat rice. If the room is empty, before this, my new key, Tim Cook Salary Enterer, is starting. Both. The side pick goes that when is my room vacant, okay tests and time less, my room will become vacant, not before the room becomes vacant, if the meeting starts, then we argue in its nature that a new form will have to be created for that because Before any meeting is empty, he leaves, because I have to be with him, so I am tight because inside Advani is now his father Ubal's friend, thank you that fulfilling the responsibility of A Pandu means that Nehru is creating 123. If these trouble due to introduce mustan time end will be them after big display after room is empty invest and is yours why do I candy why I remove some of the meeting and as soon as my new building comes up I die in local Off Scientific Auditory Touch I don't say that the old meeting is over, next the said statement from create is fine, that's why I say old woman has been occupied husband my wife's notification is fine, now in the last one feels 500 proud isn't that also send on It happens that how many booms do I have formed a crowd of its size, try it for once and if you do n't subscribe, then there is some mistake, loot is silent, why respected, good, sorry, function increase, subscribe, this application on Friday, in this way. Okay, so it's got entertainment meter, Mauj Bittu intervals. Okay, this thick and woman to death over these towers, this front earring. Okay, so let's see a circular. Let's run two alarm sets and see submitting for one time. 16 times. Why am I suffering from gas once? Write the problem on it. Okay and again - I will do it only Write the problem on it. Okay and again - I will do it only Write the problem on it. Okay and again - I will do it only then it is important to help. There are many things which you should tell me that should be known before doing so like how to do the airport or how to use the tube. Why is there crime and reminder of ok so a remote's subscription link saaf ko saree songs youtube ling se meri yoni kate that you will get the option so that Alwar's strike is fried, first of all you have rested your entire body. If my world is not starting then I say ok then if the edit becomes soft according to against time then I have the option, why what will happen after 183, U and six will come there and immediately I join it 15.16, after that the turn comes. Is 6006 15.16, after that the turn comes. Is 6006 15.16, after that the turn comes. Is 6006 After this I said check point you create and won two seats A side effect means because I request in this way all the updates will be in one structures and their union and will be placed on the back A gift find that this What is the point, we all will start reading it, first we did an internal audit, it is fine, I saw that the writing size is empty, so remember this front, I have placed it at the entry point of my interview, either for the President or till now. Minimum so please okay, the meaning of doing one needle, I will read a new look inside it that my 131 meeting is by clicking on it that now next time see this renewal and on one side the size of the customers is at zero balance that now to decide. Regarding this meeting, it will be held in the old room, but we will have to give time, so done, right till now, our first one, when is it free, what is the minimum balance time, three free is more or not. The meeting is his time 1004 after this to three do response after means this one which is the interval is Vrindavan it will be cleared before its end means I will have to create it in a new form so got the height done on my friend and its end Have testicles, the significance of adopting this on Friday is only that we need salt from age to sex, I have stopped that now look ahead paper snake stand comes from seventh to end tagged what is the minimum of primary fuel free means how long the room It will be empty, first of all, we will be empty Lokayat on these, by following anyone, it is cutting increasing intervals throughout, it is not bigger than 737, meaning that I will be empty till the time it comes to double and we will be empty then. This one will not go in this, I don't need a meeting room, I type that the old one actually bends to remove the Taurus, why is it tight, why am I okay, that means I am not here, this one, I have freed them off here. I signed it and added it to my friend again. He tweeted it to the interviewer. His end time would have been junior first that I was here within this month from intake to Delhi meeting and got admitted to the studio and the room was vacant. Being vacant means leaving on Friday and signing a new meeting inside the same room. It means I replaced it on Friday with the development of life and these were 68 comments. It means that now if any room is vacant, the song will be the first to be vacant on the set. A mixing bowl goes from 1 to 1000, it is possible that the room which has been made pregnant is less empty, any of those empty six packs which Noida has started with seven wickets in the over means that there is no need to create Nehru which is your minimum. Help, the six pack that was vacant on me, remove it, then remove the minimum balance. Particular country means this room has become vacant. Now I have added you earlier also, 540, I have made its end points pregnant, I am here. Not one British kids latest now petrol tank meaning one is empty one has become popular one has become one on the other hand in local train both have got cat ok now look new a meeting of the name is not - laker a meeting of the name is not - laker a meeting of the name is not - laker team is hello friends good topic our minimum What is it is not big, it is tight from the center of zero to this line, whatever is not meeting is on the straight line and when will my phone go free now, but I do not need to create a new look MS Word thread started mission on friday means to remove my measurement comes out first of all without useless he you removed rival i have added these gooseberries he removed a meeting ignite statement resides now inside that day Finished mike is Nazar's party verification while some tips are tossed by the other team. Its end points will be done only by the team. I have invested from the line and then the volume is at minimum. Now while doing this, I submit and I have reached how much foundation of Russia has been laid. If the size of the front prevents it, then I will simply return it after 32 days, it is good, it is fine, how to reach the pure combined pollution, let us understand the festival of the most balance, how to implement it, because the foundation was laid, because once we had to remove this. Okay, for once we used to talk about complexity in this way that if I talk only about the object, then first of all the speech, now inside this we have one for all these meetings. I have to create a new form, I may have to create a new form for everyone's meeting, that means on Friday, when it may happen that I have to set it to minimum for every meeting, then friend thank you, what can be the maximum size and And that means the number of meetings, then I want my meeting video. Okay, so apart from the space, talk about the space complexity, the extra space that you will feel, send the access, that is the ID, because the shooting will be there because you have used the same energy for the interview. On the rain, you will look stupid and the first that when you talk about the meaning of those people, in all the meetings and keep writing of the year, you may have to create the rules of all the media, then everyone's edition in Friday. Let's talk about time, if you have to make any addition in the priority queue, what should I talk about, then it will be made for all the videos now and if you have made all the previous versions, it means that you will have to adopt them all on Friday the 22nd. This element is of co and permanent commission. Login Okay, according to that if prank you are going to run then its time goes tense and login Vivo fuel square feet how many elements are there which will be presented away by the idiot in time complexity and vent end New Zealand Express first in creatures this issue this first everyone's meetings are something like this why not from mind to ₹ 5 meeting why not from mind to ₹ 5 meeting why not from mind to ₹ 5 meeting then seeing him sex was third meeting from to for and ponting and only from and to 376 loot in Everyone's rules have to be created. Guest, I speak from the beginning. From this and 700 to Inter Amazon, pipe limiting is assigned. For the second meeting, I have to remind either about that six because right now positive energy we are its middling or again. But I will have to remind, then there is a strict one by taking part in No room is vacant and you will have to sign with force that if there is no room vacant then doing Nehru Madam Nehru for every meeting means Right You Can Work, these four tips will be entered. If the movie is kept at 600 points then it means I will give ancient science, it will depend on how many meetings I have, but in this I am talking about first class branding, enter your element, if you have done the elements and then it would be time to add an element. If it is brinjal then it will be time to read Animals that now it is Ainul Haq and Commission's speed to you in this sentence stupid fuel and time and again how are you able to understand this thing that impress camera is there in it, okay so one Please subscribe for the bar, it is not difficult, it is easy, it is inactive, you will find their links in the description, please submit any suggestions, any complexity is any good, if I can think of an optimized toe approach than this, then please do the body right. Suggestions are always welcome constructive criticism s welcome previous song do this for a moment i next video problems sign that at
|
Meeting Rooms II
|
meeting-rooms-ii
|
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** 2
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 104`
* `0 <= starti < endi <= 106`
|
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied.
If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
|
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
|
Medium
|
56,252,452,1184
|
1,637 |
hey everybody this is larry this is me going over q2 of the recent bi-weekly contest of the recent bi-weekly contest of the recent bi-weekly contest 38 from the code uh write this vertical area between two points containing no points so this one actually it took me about two minutes to solve during the contest most of it i was just confused about the vertical part of it and i think they definitely put some emphasis on that during the example and that's why i took a little bit more time because i don't know why they draw all the way on top because when you look at the output it just cares about adjacent points and we don't care about the height at all so that means that we can throw away and i just wanted to make sure when i was reading the problem i'll get the x and the y's right because sometimes you mix them and sometimes i mix them so basically yeah after doing that you realize that the problem comes down to just looking at you know you could forward the height so you can squish them together compress them into just the x dimension of each point and then looking at adjacent values after you sort them because after you sort them it's going to be next to each other i also check whether we care about like the leftmost point or something like that but we don't so basically that's basically what i did as i said i took only the x component of the points i sorted them i put them in a p array so this is just a list of the numbers on the number line and you have to get the max of the adjacent um values and that's basically what i did absolutely i it actually technically should just be y minus x and you don't need the absolute value but i was trying to speed code this so i was just like i already typed this it's fine so then i um use this zip thing which allowed me to look at two adjacent numbers after it's sorted and then for each two of those i get the absolute i subtract adjacent values and i get the max out that list that's pretty much it uh and this is going to be and again because they're sorting pretty straightforward and technically you um technically you could do this you know one extra space i didn't because of some pythonic trick but you know i leave it up to you at home to observe uh that's all i have you can watch me stop this live during the contest now you oops uh yeah thanks for watching thanks for hanging out let me know what you think about this explanation um doing a little bit live so yeah hit the like button to subscribe and join me on discord and i will see y'all next uh problem bye
|
Widest Vertical Area Between Two Points Containing No Points
|
string-compression-ii
|
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width.
Note that points **on the edge** of a vertical area **are not** considered included in the area.
**Example 1:**
**Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\]
**Output:** 1
**Explanation:** Both the red and the blue area are optimal.
**Example 2:**
**Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\]
**Output:** 3
**Constraints:**
* `n == points.length`
* `2 <= n <= 105`
* `points[i].length == 2`
* `0 <= xi, yi <= 109`
|
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
|
String,Dynamic Programming
|
Hard
| null |
739 |
So hai gas welcome tu code off so our next question is daily temperature so I was checking the daily challenge recently gas and I got a question in which the strike is very good he is getting this question from our previous question Speed is quite related. Previous, we had Speed is quite related. Previous, we had Speed is quite related. Previous, we had asked a question. Next greater element on the right. Next letter Railway on the right. We had asked a question. This question is an application of the same. Basically the same question is being asked here and I keep saying this. That question of gas is happening in many questions. Let's see what the question is. The question we have is something like this, we have a wait, given are of inteasers, given and arrears of intesers, temperature representative. D Daily Temperature Return Okay, so see what is there in this question, as if we have been given an interior, we have to check it, like today's temperature is 3 4 5 6 7 0. The temperature is 73 degrees Celsius. What do we need to know that when did the warmer day come after 73, that means how many days did we have to wait for the day to come in a war, then how many days will we have to wait for it to come, then it is 73 degree Celsius and tomorrow which It is 74 degrees Celsius, it is showing here, so how many days did we have to wait, one day, what is it here, one is gone, okay, similarly look here, it is 74, after 74 I am giving once, when is it coming 75 °c How many days did we have to wait for one day? Now 75 °c How many days did we have to wait for one day? Now 75 °c How many days did we have to wait for one day? Now look here, understand here, the question will be cleared very well. Look here, it is 75 degrees Celsius. What is the point in the question that how many days will we have to wait? Give it in one go. Till then see when will there be a day hotter than this? What day will be hotter than this? Is it 71? Is it not 69? Is it not 72? Is it 76? So how many days did you have to wait? 76? Is it 76? So how many days did you have to wait? One, two, three, four. If you had to wait for four days, then it will come here. 4 So these are some questions date min what do we have to do a wait error is given and what is the temperature of temperatures what do we have to do one hey we have to make a hey what do we have to put in it like today late today x Degree Celsius, then after me, means in the days after today, when will the government give more than today, we have to calculate that day, how many days later it will be and put it in a Hey, see this from the previous question. How is gas related? How is this related to the previous question? Look, what is this? 73 is 73, so write the next greater element on D. Next letter helmet, write it on D, what will come? If you go 74 A, then look at the difference between these two. That I do the indexing here, first of all I do the indexing, so zero one three four five six seven is the temperature given for the day, then after 73, look down the right side of 73, what is the next element on the right side, which is 74. So if you take the difference of the indices of these two then what will be 1 - 0 between this van then what will be 1 - 0 between this van then what will be 1 - 0 between this van and this I here understand that 75 degrees Celsius is this connected element which is 76 so 75 and 76 are the index here is 6. - 2 will A go, 4 index here is 6. - 2 will A go, 4 index here is 6. - 2 will A go, 4 A will go, so what is there here, see how simple a question it is, what has to be done, here we do not have to find anything, the next letter element on D right has to be found and the difference of the indices of those two. You have to store it in your result end diary, so date it is a simple question gas, so I thought that you guys should solve it, you guys try it first, you guys take the first try, pause the video and you guys try to solve it, nothing. We have to do this from the previous question, it will be done from tu to here, just in the previous question we are storing the values, in this question we will have to store the index because in this we are reducing the index because 75 is the next element. 76 But we do not mean by 76 what do we mean by the index of 76 we mean the index of 76 and if you do six mines of 75 then it will go to four A so here we will store 4 as question end The approach of answer solution will also be clear to you guys, try to solve the questions for the first time, if you don't succeed then continue the video and watch it. Okay, now watch the gas. Now see what to do, it is simple, what to do, we are the previous ones. What are we doing in the question? What are we storing the are element in? What will we do this time? We will store it in the stack, we will store the index, from there we will travel right and left. Okay, so 73 is the most. First let's create an answer, we will create it and lastly we will store zero because look here, we have seen that if a temperature is not found repeatedly to the right of it, then what to store, zero has to be stored, see if there. Is this no feature? Give the possible answer of I = 0. Okay, so we have put zero I = 0. Okay, so we have put zero I = 0. Okay, so we have put zero in the previous question. What are we doing when we are inputting the mines? So this is a simple difference. Now see, we have gone to 76. Okay, what will we do before going to pay 76, we will post this in our stock, so here I show the index, I also show that element, but in the store, we will do fantasy. What am I showing here for simplicity? I am also showing the elements. Okay, we have reached 76. Our flow is done. If we are in any particular element, we will bob through the stacks until we find an element bigger than that at the top of the stack. So by then we will be on top. So 76 is an element bigger than 76, so it is not there. If it is 73, then what will happen to it? Its next element will also become zero. Okay, and as we go, we will push 76, so once I write the index here. I am 01234 567 so 6 is its index and that element is 76. Okay and we have reached 72. If we have reached 72 then the element is smaller than 72. It is not 76. It is in the top starting from 76 so it will not be able to make it to the top. The answer to this will be 706. Look at this, what is its index? Six mines, what do we do? What is the index of the current element? So here we will pay A and we will make it 69. Will you be able to do 72? Will you not be able to do it? If you are not able to do so then the index of 69 is 4 and the one which is on the top of the stack is five minus four which in this van will go here also, okay and we will also push it, in this type we will push 4 and 69. Okay, now we have reached 71, it will pop 69, it will pop 61, from here, 69 is smaller than this, so it will pop here, but it will not be able to pop 72. He will not be able to sin 72, so what is its index? Five is five, its index is three and the index of the current element is three, so five minus three will go to a here, okay and then we will do this, so here a Will go 3 index end 71 sorry 71 whatever that element is now we have reached 75 but look here it will be very clear here pop from the strike at 75 pop for how long until an element bigger than 75 is found at the top So it's yours, brother, popped it, okay, got 76, so 76, which is 75, its index is six, okay, the current element is 6 - 2, which is four, so here a will is 6 - 2, which is four, so here a will is 6 - 2, which is four, so here a will go, 4 and we will push 75. So you are its index and 75 is its value. Okay now we have reached 74. We have reached 74. He will not be able to do anything. Sorry, he will not be able to pop. 2 - 1 witch is this van so here a not be able to pop. 2 - 1 witch is this van so here a not be able to pop. 2 - 1 witch is this van so here a van will go like this, similarly here. It will also be very simple floor tha gas and I hope it will be clear to you if you have seen the previous video then it must be very easy for you because what was the previous video? Next helmet on the right so that simple. Question here, we will make it a gas, so we will make one with the answer and here we will take it as in the previous question because there will be a bigger element to the right of it, thus here we were asked to put zero. If so, will we put zero or will we put n - 1? In the previous question or will we put n - 1? In the previous question or will we put n - 1? In the previous question we were pushing elements but in this question we are putting index because there is no less number of elements in this question. For this, we have to store the difference, so this is a loop, inside this we will put as long as the size of which type is given greater, it is zero and whatever is ours is given greater, equals is here, keep in mind that gas is here. Do n't simply do a stag dot pick because we are storing it from the index in the stack, so there is a stag dot pick, this will happen here and what to do here then pop it, till then pop it if By the time we come out of this loop, if our strike size becomes zero then what to do? Store the zero in answer of i. What to store the zero in adervise answer of i, then this will be done. Inter Will take it, then submit it and then let's talk about it. Have you forgotten to push its timing? Here we have a stack. As we go, we make flowers in this type and make the elements happy. And here we make happiness in the strike. Did n't do the element because wrong answer was coming. Now I thought it will give the right answer too. So let's check. Now it is right. Let's do it. Now I think it will be submitted. That was the problem. You don't even do anything during the strike. If the complete discussion is clear to you then you will find it in the description. Look, in this I was discussing how I was discussing a little bit in this. You guys can refer to the previous video. Hope complete session, you guys, the question has been cleared and many more questions are also being faced by him. Next greater element on the right, he is being faced with this question and many more questions, so in the upcoming video we will see those questions also. You must have been thinking so much for this video, the complete discussion of gas and I hope it has become clear to you, how to do resting. If you liked the video, please like the video and subscribe to the channel so that you can get any latest notification
|
Daily Temperatures
|
daily-temperatures
|
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
**Example 1:**
**Input:** temperatures = \[73,74,75,71,69,72,76,73\]
**Output:** \[1,1,4,2,1,1,0,0\]
**Example 2:**
**Input:** temperatures = \[30,40,50,60\]
**Output:** \[1,1,1,0\]
**Example 3:**
**Input:** temperatures = \[30,60,90\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= temperatures.length <= 105`
* `30 <= temperatures[i] <= 100`
|
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
|
Array,Stack,Monotonic Stack
|
Medium
|
496,937
|
867 |
That Aapke Ajay Ko Hua Hai Hello Everyone Welcome to New Video English Video By Going To Discuss Another Problem But 6 Transport Subscribe Problem Thursday Return Transport Amused and Stitching Matric passed that wars happened other if Subscribe - Verb - - Verb - - Verb - 05 - 0 And if we see till this last breath, if we have to take its transport, then what have we had to do about it, which subscribe to my channel, subscribe to it, will subscribe to it, so if subscribe to it and its Place of - - - - Here, subscribe to it and its Place of - - - - Here, subscribe to it and its Place of - - - - Here, here, this is our that will come here and this - which is that will come here and this - which is that will come here and this - which is made here - will come here, Hey Eleven, whatever was, happened made here - will come here, Hey Eleven, whatever was, happened made here - will come here, Hey Eleven, whatever was, happened here, what we were writing, road, in this disease, now school. We will change the center meaning - we will see the lineage - 151 meaning - we will see the lineage - 151 meaning - we will see the lineage - 151 - 76 - 76 - 76 and we are changing the inter. Okay, so one, if we see that the youth, then if we take the example of 2389, 125 6 that our matriculation, now what do we have to do, if we make its transport simple, it will go soon and Problem will happen first subscribe so now our dance pregnant side change first 2389 subscribe this our subscribe our transport then this will have to be subscribed if we subscribe if that subscribe to pankra sam i.e. we subscribe to pankra sam i.e. we subscribe to pankra sam i.e. we will make an answer matrix what size is that yogi and Processes that if we make a new matriculation, then our answer will be our newspaper, look what it will become like, what should we do, Shyam Laddu who came from the villages is also the number off of our last one and a big village is to Liuji channel, now what should we do inside it. Inside this, we will carefully, if you please subscribe, we have done 2000, if we subscribe, then you can see it here, if we appoint, subscribe, then we will cut it, then these two villages, if you subscribe, then inside this. From our side, this will become ours, which is our life, what happened to the metric-metric fennel, this is our just simple solution, what happened to the metric-metric fennel, this is our just simple solution, what happened to the metric-metric fennel, this is our just simple solution, as soon as the following ends, we will get our transport matrix, we will return it, we will cut it to ourselves, if subscribe means this now. Subscribe to this channel, now there is one more subscribe in it, this is our 2015 Thursday, what is God's compulsion, what is ₹ 10, Thursday, what is God's compulsion, what is ₹ 10, Thursday, what is God's compulsion, what is ₹ 10, here the neck will come, our answer is 0120, the subscription will definitely increase, then at our place, if we see that our Ghee Here 20 2012 - 2012 - 2012 - Subscribe to our channel So the time complexity of is Sperm Omega of And here what is ours N Ours is the number of elements because the time of death has happened and this is the number of elements of which you can subscribe Number of elements, both of us will be our time contact or will be Omega of N. Here we will know what is the number of elements, so let's move on to quote like this on liter, so you have done this on your Twitter, first of all we will see the solution and its Later we will see that if we talk about plus solution then let us subscribe so let's clear it first and which is our N is intensive that instead of this trick shots Amatrix will go to the college of 80 Okay and A matrix till 80 If this is done then here we have to take the cross end metric and transport, then we will have to create its just opposite i.e. Android send metric opposite i.e. Android send metric opposite i.e. Android send metric which we have now simply created our Aaj Tak plus inside this we will update a village J0J0 so subscribe our this is our Yog Na as if this will eliminate both of them, let's simply submit it and see what is our result. First of all, we were for the test case, for fastest, which was passed successfully. We submit it and see the result. Some guy, let's see, the festival is clearly on top and Java Trench has been given to Koirala here, so we will have to run our look from the train till now, it is just light which was there or else Amit ji and the icon will have to be changed, it is a simple applet now. If you look at this, now our submission will be successful and you can see our subscribe and subscribe subscription. Okay, we have come and we have C+plus Okay, we have come and we have C+plus Okay, we have come and we have C+plus summation on our C+plus submission but summation on our C+plus submission but summation on our C+plus submission but we will see that we have not changed much. First of all, what did we do? We have made a matrix, find out its size, that is, how many numbers are there in its number of days and for that we have used this function, then we will get it from the intermediate side, okay, after doing the matrix for its numbers, there will be a subscribe button, after that, first of all we have calculated its size. What we have is here, I had the number of columns in here and after that, what we have is its size, so we have here and inside that, we ran another group James till more than 20 meaning the number of roses, the number outside and Olympian and What we did inside this is that we subscribed to our answer and as soon as we finish these people, we get ours and we can use that difference to tear apart the pain that other than that, the lens function works there. Here is our example of this function, if we subscribe to it Radhe-Radhe result will be Radhe-Radhe result will be given, its result is our subscription appointed subscribe, you must have understood both the solutions, apart from this, if we want to use more questions, then subscribe to our channel, if your Anyone can comment in the comment section below. Thank you for watching
|
Transpose Matrix
|
new-21-game
|
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`.
The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\]
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\]\]
**Output:** \[\[1,4\],\[2,5\],\[3,6\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 1000`
* `1 <= m * n <= 105`
* `-109 <= matrix[i][j] <= 109`
| null |
Math,Dynamic Programming,Sliding Window,Probability and Statistics
|
Medium
| null |
981 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem time based key value store and this is one of my favorite problems honestly on all of late code because there's not a lot of fancy tricks involved you can really logically uh you know dig your way through this problem so you can go ahead and read through this description if you want but i'm going to go ahead and jump straight into the explanation because i think this is best understood by actually going through an example so our whole objective here is to design a key value store so it's kind of like a hash map we're gonna have some key value and then we're gonna have a value associated with that key but we're actually not just gonna have a single value we're gonna have a list of values uh so plural so it'll be a list and in that list we're gonna have a pair of values so it's not just gonna be a single value each value is gonna have a time stamp associated with it so for an example we can have a key value of let's say foo and we would have a list of values associated with that and one of the values the pair of values right because we're going to have a value and then a time so the value let's say is going to be bar it's a string in this case and the time stamp associated with it let's just say in this case the example it's going to be integer so let's just say it's 1 in this case and then we could have a second value right associated with it as well and that will have its own timestamp as well right so basically it's going to be a list of values the and the values themselves are going to be pairs a value and then a timestamp associated with that so it's not super complicated but the main operations that we're going to support are actually pretty simple just two operations actually three if you count the constructor so yes we're going to have a you know constructor because it's an object that we're designing a class and the two operations we want to support on this key value store are going to be set and get which is pretty straightforward that's what we would expect so let's just go through this example and i think the problem will actually make a lot of sense to you so the first operation we have is a set operation the key is going to be the first value foo the value is going to be bar and the time stamp associated with it is going to be 1. so let's put the first value here it's going to be bar and the time associated with it is just one and now we get the second operation get what are we getting we're getting the key uh associated with foo and the second parameter in our get operation is actually going to be the time stamp so when we do a get operation normally on a hashmap we just need a key but in this case we need two values the key and the timestamp right because we know that for a single key it's not enough to identify a value right because there could be multiple values over here we need the time stamp to identify the actual value in this case we were given a key value of foo and we were given a timestamp of one right you can see up above yeah it's one and by the way in case i didn't mention we're actually going to be implementing this entire key value store with a hash map so you know the keys are just going to be normal hash map keys and the value in this hash map is going to be a list of values with you know this schema right this the list of values are going to be pairs so when we use the key in the hashmap we're going to get a list of values right in this case this list only has one pair of values bar is that value and remember we were given a timestamp of one so in this list we're gonna basically iterate through the list to find the pair that has a timestamp of one in this case we did find it right it does exist so then we can take this and uh the thing i think we're returning is just the value itself so we can return bar and you can see up above that's what they ended up returning for this operation so we did our first get operation that's great now let's do our second get operation in this case we're given this pair we're given the key is going to be foo so right we can go to the same list and the timestamp is actually three in this case but if you scan through the entire list that we have here you can see that none of these have a timestamp of three associated with them so what does that mean are we just gonna return null in this case no because remember what we're doing here we're designing a key value store based on time so we set this value at time one now it's time three so the way this problem wants us to handle the timing is basically if you don't find an exact match in our key value store then just return the most recent one so in this case we're doing the time is three right just return the most recent one and by recent they mean the closest value to three that's less than three so for example there's only a single value here right so in this case we only have a single one and the time with that is one so of course one is going to be the closest to three but what if instead we had something like four is close to three but it's greater than three so that's not allowed we wanna find the closest timestamp that's less than three now if we had multiple if we had another bar here or some other value and the time associated with that is two then in that case uh which of these two would we want to return we would want to return this one even though the value is the exact same but we'd want to return this one because it has a closer time to the three but in this case we only had a single value so we're just going to return bar again and you can see in the explanation and the output that is the correct value so we return bar in this case okay so just cleaning up what we've already done so far but now we're at a second set operation the values associated with this set are well the key is foo so same you know slot we're gonna go over here and the value in this case is bar two pretty simple and the time associated with it is four so that's the timestamp uh bar two and the time is four and by the way the set operation that we're doing is always going to be a constant time operation big o of one right because the you know so finding the key is an o of one operation because we're using a hash map and then uh you know this list of values is gonna be a list and every time we add a value to this list we're always going to add it to the end of the list so we can do that in big o of one time so not too bad but where things get tricky uh now that we're done with the second set operation where things get tricky is when we get to the get operation so now we're at another get operation the key is foo and the time stamp is four so we're going to go to the same slot here and then now that we actually have more values you're probably getting at what the bottleneck is so in this case the timestamp is 4. so we want to look in this list we want to look for an exact match and if we can't find an exact match we want to find the closest value that's less than 4. and how exactly are we going to be doing that if we just do a linear scan through the array worst case it's going to be linear time now that's really not that bad but the question is can we do any better well obviously very few algorithms are better than big o of n one of the algorithms that's better than big o of n is binary search which we know runs in log n time that's definitely an improvement over big o of n but that would require that our values are sorted but what exactly do these values have to be sorted by do they have to be sorted by the value or by the time stamp well since we're searching for an exact match with the time stamp these have to be sorted by the timestamp so again not too bad what are we supposed to do though are we supposed to sort this every single time we want to do a get operation that's not going to make things any better because if we have to sort the time complexity is not going to be log n and it's not even going to be n either it's going to be n log n so that's not an improvement at all and so this is the part where we kind of have to be smart let's go down and read the problem carefully if you scroll all the way down and read the fine print you can see that all the time stamps every time we set a value the timestamp is going to be in increasing order strictly in increasing order so how does this help us well basically it means if we have a list here and every time we set a value we just add it to the end of the list then the list is actually going to be sorted by the timestamp by default so it's already in sorted order so that's why we don't have to sort it again we actually can just run a binary search that's really good for us but what if you know what if you didn't really read the fine print well the way this problem is set up i think it's kind of intuitive that if you are in a real interview the best question would be to ask every time we set a value is it you know is the timestamp gonna be in ascending order because you know the way a set operation would work in real life is you would use the current time that you know the current time that you're setting the value and you know as most of us know time really just flows in one direction so it makes sense that these you know the list that we're setting would already be in sorted order but again that's kind of why i like this question because even if you don't read the fine print you might think to yourself are the set operations going to be in sorted order and that would be a really good question to ask in a real interview so in this case we would want to run binary search which would be login time so that just means that the get operation worst case is going to be a log in operation and by the way if we're looking for the key value 4 we know that it exists so this is what we would end up returning we would return bar 2 and you can see that's exactly what they did return in the output so we're done with another operation let's cross this out and let's do our last operation the get operation in this case the key is foo so again over here and the time stamp is five so again we're gonna run binary search right we're looking for an exact match of five and if we can't find the five what's the closest thing that we can get that's less than five well in this case it's four so the value of that is bar two so again we'd return bar two so that's kind of what i wanted to cover with this problem of course we just had a single key but you know this problem wouldn't be much different if we had a second key or you know multiple keys so i think we can actually go into the code now and see how we can implement this binary search solution okay so now let's get into the code and so you can see that they already gave us like a class and a few functions that we're going to define so the only thing we really need to do in the constructor is just initialize our store like i mentioned it's just going to be a pretty simple hash map where the key value is going to end up being a string and the value of the hashmap is going to be a list of lists so a list of pairs really but what we're actually going to be using to implement that pair is going to be yes a another sub list and the values of that sub-list are going to represent the sub-list are going to represent the sub-list are going to represent the value itself which is going to be a string and the second is going to be the time stamp uh and yeah just uh kind of condense this uh basically we're gonna have a key that key is gonna be mapped to a list of pairs okay so now let's get into the set operation because it's a little bit more simple than the get operation the way i'm going to do this is first just check so of course we're inserting something based on this key value based on this key and based on this value based on this timestamp so this is going to be that pair of value timestamp and this is just going to be the key of the hashmap first of all we want to know does this key even exist in our store and if it doesn't exist in our store the first thing we want to do is just you know insert it into the store and you know set it to let's say an empty list so put this key and just set it to an empty list you probably don't need to do this line we could just use a default dictionary if we really wanted to but i don't want to abuse python too much because i think sometimes it makes things too easy and this would kind of be i assume this is what you would want to do if you were doing this in java or c plus or something like that yeah so after we have uh you know we know that for sure we have an empty list there then all we want to do is to that list append a value to it right append to the end of the list uh a pair of values the value itself and the timestamp associated with it and that's really it right the set operation is pretty straightforward in this case but the get operation is where things are going to get a little bit tricky so first i'm just going to initialize the result initially it's just going to be an empty string and the reason i'm doing this is because if this key doesn't even exist in the store itself then this is what they want us to return they just want us to return an empty string that's why i'm initializing it this way and the next thing we want to do is actually check what that list of values actually is so let's go to our store and run the get operation reason i'm using the get is because if we find a match it'll return that list if it doesn't find a match with this key by default we can tell it to just return an empty list yeah so this is our list of values and now is when we actually want to run the binary search and then after we run the binary search we're going to end up returning whatever the result happens to be as you may know binary search has usually two pointers a left and right pointer i have solved a variety of binary search problems on this channel i even have a binary search playlist if you want to practice uh but yeah so let's set the left and let's get the length of the array minus one is going to be our right pointer and basically while the left pointer hasn't crossed the right pointer we are going to run the binary search actually should be equal if we want to make sure to get the last value but yeah so we have a left and right pointer and usually we want to look at the middle value so we can just take left plus right divide it by two in python integer division you need two uh slashes to do that otherwise it does decimal division and then we just want to know did we find the result or not well if we found it let's check in our values at index m and we know this is going to be a pair of values we want to look at the time stamp which is the second value up above right you can see even in the comments we said that the second value is the timestamp so we can go to index 1. if this is equal to the timestamp that we're searching for which was an input parameter to this function called timestamp actually instead of an exact match let's first check if it's less than the timestamp less than or even equal to the timestamp because in that case we know that it's a valid value because remember the else case from this is completely different than this one right if it's equal to the timestamp or less than the timestamp that's completely fine but if it's greater than the timestamp that value is not allowed so we are going to be handling these two cases a little bit differently so with most binary search if we know that this is less than the timestamp what would we want to do we would want to say the way we want to update the pointer is to set left equal to mid plus 1 because we want to search to the right portion if it was less than the result but before we do that even we want to say the result so far at this point right since this is a valid value and this is the closest value we have seen so far we are going to set the result equal to values uh you know basically the value at index m and then you know this is going to be index 0. right because this is the closest we have seen so far that's how this binary search is going to work this is the closest we've seen so far now let's go to the next iteration of the loop and then see if we got any closer to the result but the else case is going to be whoops the else case is going to be the opposite here all we're going to do is update the pointer if the value was too big it was greater than the timestamp which is what the else case is we would want to update the right pointer set it to mid minus one and then you know that's just how we're going to be searching but we're not going to assign the result here because this is an invalid value we cannot assign it to the result technically this isn't as optimized as it could be because you know in this uh equals in the first case if we even find the exact match to the time stamp we're not even returning right we're still continuing the binary search which is kind of sub optimal but it doesn't change the overall time complexity it's still login and in this case i kind of prefer the concise code so i'm going to leave it as it is because we are actually done with the function after you know this binary search is over we're going to go ahead and return the result whether it's an empty string or whether we actually found the correct value you know the closest value to that timestamp that's the entire code let's run it to make sure that it works and as you can see on the left yes it does work and it's pretty efficient probably could be a little bit more efficient if we actually returned when we find the value but that's okay i hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
|
Time Based Key-Value Store
|
delete-columns-to-make-sorted
|
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the `TimeMap` class:
* `TimeMap()` Initializes the object of the data structure.
* `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`.
* `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `" "`.
**Example 1:**
**Input**
\[ "TimeMap ", "set ", "get ", "get ", "set ", "get ", "get "\]
\[\[\], \[ "foo ", "bar ", 1\], \[ "foo ", 1\], \[ "foo ", 3\], \[ "foo ", "bar2 ", 4\], \[ "foo ", 4\], \[ "foo ", 5\]\]
**Output**
\[null, null, "bar ", "bar ", null, "bar2 ", "bar2 "\]
**Explanation**
TimeMap timeMap = new TimeMap();
timeMap.set( "foo ", "bar ", 1); // store the key "foo " and value "bar " along with timestamp = 1.
timeMap.get( "foo ", 1); // return "bar "
timeMap.get( "foo ", 3); // return "bar ", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar ".
timeMap.set( "foo ", "bar2 ", 4); // store the key "foo " and value "bar2 " along with timestamp = 4.
timeMap.get( "foo ", 4); // return "bar2 "
timeMap.get( "foo ", 5); // return "bar2 "
**Constraints:**
* `1 <= key.length, value.length <= 100`
* `key` and `value` consist of lowercase English letters and digits.
* `1 <= timestamp <= 107`
* All the timestamps `timestamp` of `set` are strictly increasing.
* At most `2 * 105` calls will be made to `set` and `get`.
| null |
Array,String
|
Easy
| null |
271 |
in this video we're going to take a look at a legal problem called uncode and decode strings so design an algorithm to uncode a list of strings to a string the decode string is sent over the network and is decoded back to the original list of strings so you can see here on the right we have a class of code uh right so in this case you can see we have a uncode and decode uh function this uncode function and codes to take this list of string and we want to convert to a single string and this single string will also uh being passed into the input for decode function right and then we want to convert that back to a in this case a list of strings right so in this case you can see here uh we have our example right so basically you can see you're not allowed to solve the problem using any serialized methods and we want to implement the encode and decode methods so you can see here we have our dummy input so this is our list of strings right so you can see we have hello and world uh inside our list and then in this case this will pat this will convert it right so machine one you can see we'll create an instance of this uh string right you can see and then this the this message will then be getting uncoded and then you can see we also create an instance of this decoder and then what we do is we decode the string right so we create a basically two separate instance and then we basically calls different functions so this first one it calls the uncoded and then we create another instance of this we called the decoder passing in the uh you know the uncoded string right so in this case uh you can see here we're basically returning the same list that is passed it in the unencoded function right and you can see here if this is a empty string right we have a list of empty string then we also want to return a list of empty string right so in this case you can see here we're guaranteed to have at least um one string in our list and then you can see here is what is the length of the our list string is between 1 200 and then for each string is has a length between 0 to 200 right so the basically the string consists any possible characters out of uh 256 valid axi characters okay so the goal is to want to basically uh write a generalized algorithm to work on any possible set of characters so let's try to think about how we can be able to solve this problem because since now we know the constraints right so in this case um what we can do is that maybe you may you might be thinking well why don't we why can't we just convert this to a let's say this is our string right or let's say this is our input so let's say this is our input right and then what we can do maybe is we can basically just convert it into one string right for our output for our uncode function maybe we can just say so uncode output maybe we can just say hello world right in this case what we can do is that in our decode right decode input it takes this string right which is this string right here but the thing is we need to know how can we be able to separate right we how do we know that this is one string and this is another string right so maybe what we can do is maybe we can use some kind of like a delimiter or maybe a separator maybe a space or maybe there is a maybe the this symbol right or maybe a asymbol or maybe a comma right to separate it but the thing is that you can see here in our constraints that each character in our string could contain right could contains any possible characters out of 256 valid axis characters right so comma include one right and then you can't we can't really generate any unique characters right so in this case what we can do is we have to think about how we can be able to separate them right into that so that we know that this is one word and this is one word so that when it when the decode input takes the string we know where to separate um these characters strings into a list right because the output for this uncode function right sorry the decode function the output should return this thing right so in this case what we can do is that let's say if somehow that our uncode output right the our uncou our or our decode input knows exactly um you know how many characters right or maybe because since we cannot put a delimiter or some kind of separator to separate it what if we somewhere in our string that it tells how many characters we have for our first string right in our list how many characters we have in our second string in our list for example maybe the first string has like for example five characters and then for the second string it has also five characters so then what we can do is that we can basically iterate the first character we know that zero to index four this is our first string and then we're starting from index five all the way iterate five times that's our next five k or maybe that's our next uh you know that's five characters which forms another string right so what we can do is that maybe for each and every single string the start of our string right when we pass it in the list into the decode output right all we can do instead is maybe we can use some kind of the delimiter right so before the this first string right the first string hello all we can do is that we can basically say the hello has a size of five right so that we know exactly how many times we have to iterate through and then we also need a delimiter because let's say if there's a situation where there's already a comma right so we need to know where to stop right because there could also be a number here so in this case this number right here is part of this string right maybe there's a two in front of h right so in this case what we need to do is that we know that there's this is basically five represents that there are five characters in our string right so what we need to do is that we need to basically have a delimiter right so in this case let's make a delimiter like a hash symbol right now let's try to do a walkthrough right so you can see here we're starting from the first character right so this is our decoded function input right so you can see here on the left is basically how many characters uh we have to add on to right how many characters for the first string and this is how many characters for the second string right and we have a hash symbol to separate or kind of like a delimiter uh that separates how many characters we have and the actual string right so you can see we're starting from the first character and then what we do for step one is that we try to find the number of characters right in this case what we do is we iterate in this case this is a five it's not a hash symbol so we move our pointer one to the right and then we know that this is a hash symbol so that what we have traversed so far or we have integrate so far we convert that into integer in this case the number of characters right number of characters is basically five right so what we have to do now is we move on move our pointer one to the right and what we basically do is we basically iterate five times right so hello h-e-l-l-o that's five characters so h-e-l-l-o that's five characters so h-e-l-l-o that's five characters so h-e-l-l-o and then once we iterate five h-e-l-l-o and then once we iterate five h-e-l-l-o and then once we iterate five character five times uh we add what we have on our you know current stream builder right we add h at e l at o and add it on to our results right so we have our hello onto our result and then what we do is we start here and then what we do is we know that this is a five right so what we do is we move on to the next character in this case it's a hash symbol so in this case i convert what i have in our uh in this case in our stream builder right so what i have already visited right you can see we're basically start brand new over so we went from this right to here we know that this current character is a hash symbol so we know that the number of characters we have to iterate is five so then what we do is we move on to the next character right so we're starting from here we have to iterate five times and then we add those characters at each of those single characters onto the screen builder and then this will convert it into world and then at the end you can see we basically use this kind of method and then we will be able to generate this uh result list right so we have hello at world right and this is what we are returning at the end so now let's take a look at the code so you can see here we have a function called on n code uh and basically it takes a list of string and then for each so for basically for each character right we're using a stream builder to append those strings so first we append the list of our current string right for each string we're first getting the length of that and then added on to the stream builder and then we are basically going to add a delimiter uh to separate the number of characters and this actual string right and then we basically add the actual string uh on the back right at the end right and then what we do is we loop through all this all the strings in our list and then we add all of them onto our stream builder and then we convert it into a to a string right after we convert that string you can see in our encode function it takes this string and then what we do is that we basically have our list of string right this is what we are returning at the end and then you can see where first i just want to convert the string into a character array so that would be a lot easier for us to access each and every single character so we basically iterate from you know zero to the end of the array right from left to right so first just like i mentioned before first we want to find the number of characters right so in this case we want to find the number of characters that we have to uh traverse right what like how many characters we have to iterate to uh form our first string right or our current string so in this case you can see first we have to get a number um so you can see here while array i right it's not a delimiter so we keep iterating we keep appending our current digits onto our you know our to our stream builder so we know pretty much that the array or in this case uh each element in the array is between 0 to 200 right so in this case if i were to add it onto our stream builder and i convert it into a integer it will it should be within the integer.max value uh right so in this integer.max value uh right so in this integer.max value uh right so in this case i convert it into a integer value and then i just this is how the number of characters we have to iterate so what i do here is n is equal to i plus number of characters right this is basically how many characters we have to iterate uh basically that's the end index right so we have our stream builder in this case this is this stream builder basically is the actual string that we're going to add it out to stream builder and add it on to our result list right so while i is less than n we increase uh we basically add the current character onto our stream builder increase i index i by one and then at the end we have to decrease i by one because in this case i is equal to n right we don't want when we don't want to happen because you can see in our for loop right we have to increase i already uh at the end we have to increase i by one so we decrease that by one right so that we can be able to increase that by one right and then at the end we have to make sure we add the current string convert string builder into a string and then add it onto the result list and at the end you can see or basically a returning result right so you can see this is basically how we solve the problem and the time complexity for this one is basically big o of n uh for both functions right basically we have to iterate through the entire list of strings and then for each string we have to you know basically add that onto our string builder right
|
Encode and Decode Strings
|
encode-and-decode-strings
|
Design an algorithm to encode **a list of strings** to **a string**. The encoded string is then sent over the network and is decoded back to the original list of strings.
Machine 1 (sender) has the function:
string encode(vector strs) {
// ... your code
return encoded\_string;
}
Machine 2 (receiver) has the function:
vector decode(string s) {
//... your code
return strs;
}
So Machine 1 does:
string encoded\_string = encode(strs);
and Machine 2 does:
vector strs2 = decode(encoded\_string);
`strs2` in Machine 2 should be the same as `strs` in Machine 1.
Implement the `encode` and `decode` methods.
You are not allowed to solve the problem using any serialize methods (such as `eval`).
**Example 1:**
**Input:** dummy\_input = \[ "Hello ", "World "\]
**Output:** \[ "Hello ", "World "\]
**Explanation:**
Machine 1:
Codec encoder = new Codec();
String msg = encoder.encode(strs);
Machine 1 ---msg---> Machine 2
Machine 2:
Codec decoder = new Codec();
String\[\] strs = decoder.decode(msg);
**Example 2:**
**Input:** dummy\_input = \[ " "\]
**Output:** \[ " "\]
**Constraints:**
* `1 <= strs.length <= 200`
* `0 <= strs[i].length <= 200`
* `strs[i]` contains any possible characters out of `256` valid ASCII characters.
**Follow up:** Could you write a generalized algorithm to work on any possible set of characters?
| null |
Array,String,Design
|
Medium
|
38,297,443,696
|
1,254 |
hey everyone welcome to my channel in this video i'm going to try to solve this problem at the same time i'm going to follow the generating theory steps while trying to solve this problem so let's get started so in the real interview the first step is always to try to understand the question if there is anything unclear please bring the clarification questions to the interviewer at the same time think about some ash cases so let's try to read through this problem first so give a 2d grade consists of zero representing the island and once representing water so island is a maximal four directional connected group of zeros and the closed islands is an island totally surrounded by ones so we are going to return the number of the closed islands so let's see the example first for this example we are returning to that is because we have two closed islands so there are two other islands like this one the upper right corner so this one is an open island because it's not it's just partially surrounded by ones and similarly for this one that's why we returned two for this one and similarly for this example you're going to return one because this is only a closed island so let's see the constraints we have the uh the row number and the number of the rows and the number of the columns for the grade anywhere between 1 to 100 so this means we are not going to be given a empty grade and every cell has a value either zero or one all right so having said that i don't see any clear edge case at this moment so let's try to find the solution so how to solve this problem so it's there's not too much of the room to think about any very innovative way so this is a pretty traditional dfs problem for dfs we are going to define a dfs function uh for this specific case i would say we are going to return pouring for as a return value for the dfs function so the return value indicate whether the island is a closed island or an open island if it is a closed island then we are going to return true otherwise we return false so um the for the condition we access this dfs is either we uh go out of the boundary of the grade which means we are going to return false if we are hitting a one which means it is a piece of water then we are going to return to otherwise we are going to visit um four little directions upper bottom left and right and uh within this close island function we are going to uh go through each of the one pass through each cell so if it is a zero then we are going to call dfs function to try to uh extend as much as we can so having said that the runtime is going to be a and then uh is going to be o and so m is the number of the rows within the column within the grade and the n is the number of the columns within the grade so that's it for the solution part let's start to do some coding work so like i said i'm going to define a helper function let's say we are going to return brilliance as the return value you're going to give it a pass in the grade and also we are going to pass in the current position we are trying to visit like i said we are going to do one pass through each of the cell first of all let's get the number of the rows and number of the columns from the grade the column is going to be grade zero double s remember we are not going to be given a antique right so we don't need to check the we don't need to check whether the like this is a the empty one otherwise we may need to take a look if the grade.lens is need to take a look if the grade.lens is need to take a look if the grade.lens is equal to zero then we and then it is going to cause some arrow here but we don't need to worry about this um so you're going to do one pass through each of the cell i from 0 to row and j is from 0 to column so if the current grade is a zero which is a piece of land then we are going to call dfs and if a dfs return true which means it is a closed island then we are going to plus so we will need to define the num closed islands if this one is going to return true we are going to plus num close islands so dfs function you're going to call passing the grade the current position so finally for this function we are going to return the number of the closed islands and for this helper function the dfs helper function we are going to fill in the logic at this moment um we are going to have a similar piece of the code to get the number of the rows and number of the columns so once we are going out of the range which means if x current x is smaller than zero or x is larger than or equal to the row or y is smaller than zero or y is less or equal to column we are just going to return let's say we are going to return uh return false so otherwise it is not out of the range which means it could be either zero one so if it is a one which means we if we are going into a water case then we are just going to return to here this should be one return true here otherwise we need to uh visit each of the four directions if any direction return a false then you're just going to return false so we have up say this will be dfs um grade this would be x minus 1 y and similarly we are going to visit all of the directions this will be down left and the right just uh small little changes this will be plus one this would be x and uh y minus one this would be x and y plus one finally we are just going to return the end of all of it up or down and left and right so that's it for this piece of code so we are going to rely on this platform to help us to do the debugging work uh okay so let's transfer this one you're going to have a real answer we output zero but uh expected is two so let's see why um so we have the row as the length of the grade this is the number of the columns if x is x or y is out of the range there you're going to return false otherwise we are going to okay so i actually i forgot to set the x and y is one that is because we need we definitely need to set as one otherwise we are going to revisit the same cell over and over again and that's and also it's going to cause some more answer so let's run this piece of code again uh this here it is still wrong let's see what if it is x y is equal to one then you're going to return to otherwise it's zero and uh we definitely need to set this as one and then we visit each of the neighbor up down left and right and then we return the end of everything okay it's just uh there are some typos here all right so now we are good let's run through some other examples here um okay so that's it for uh this coding question so remember um you may want you may not you may want to write the code like this if you write the code which is a mistake i made before if you write the code in this way oops um this is going to be a wrong way to write the code that is because in java yeah so let me finish this one so that is because in java this kind of thing if this is going to be false the rest of the logics is not going to be executed because in the logic we have this piece of code which is going to change the cell value for the grade then it is going so that it's going to some issue if you write the code like this so we definitely need to have the different directions to be executed to fill in the new value for the corresponding cell for the grade so that's why we don't want to write the code in like this but rather you want to implement the code like this all right so that's it for this coding question if you have any question regarding this piece of code or regarding the solution feel free to leave some comments below if you like this video please helps as well this channel i'll see you next time thanks for watching
|
Number of Closed Islands
|
deepest-leaves-sum
|
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.`
Return the number of _closed islands_.
**Example 1:**
**Input:** grid = \[\[1,1,1,1,1,1,1,0\],\[1,0,0,0,0,1,1,0\],\[1,0,1,0,1,1,1,0\],\[1,0,0,0,0,1,0,1\],\[1,1,1,1,1,1,1,0\]\]
**Output:** 2
**Explanation:**
Islands in gray are closed because they are completely surrounded by water (group of 1s).
**Example 2:**
**Input:** grid = \[\[0,0,1,0,0\],\[0,1,0,1,0\],\[0,1,1,1,0\]\]
**Output:** 1
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1,1\],
\[1,0,0,0,0,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,1,0,1,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,0,0,0,0,1\],
\[1,1,1,1,1,1,1\]\]
**Output:** 2
**Constraints:**
* `1 <= grid.length, grid[0].length <= 100`
* `0 <= grid[i][j] <=1`
|
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
319 |
hey everybody this is Larry this is April 26th uh or 20 or day 27 I think on the legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem and also there's a luck thingy click on it for 10 coins they add up I guess today's five is 319 Bob switcher and apparently I haven't solved this one yet uh I don't know just in case uh okay so the end bulbs that are initially off your first turn on above then you turn off every second one and a third one you toggle every third one okay so I mean technically the first two hours of toggle right um I would say this is the problem that I've done before maybe faced in a different way and given that constraint is 10 to the knife you're not going to be able to uh um attention knife you're not going to be able to you know simulate it right because that's just a number I think the idea here is uh I think the easiest way is probably um and I talk about this actually recently on my Discord on similar things which is just do it before us maybe do simulation on small ends and then kind of see if you can figure out a pattern right um here you can't do a little bit of a proof though the idea here is that okay let's say you have now you have all these zeros to begin with so then the first one turns them all to one right and then the second one um goes every other one right so then you have something like this right uh typo but you get the point and then the third one you toggle every third one uh and then so basically what happens is that for uh so for another way to phrase it maybe is just that for the if thing dive bulb um it is going to get toggled by um one just because it's the first one uh and then maybe another way to say it is so I'm trying to like figure a way to articulate this at the same time this is a very one-off thing so it doesn't a very one-off thing so it doesn't a very one-off thing so it doesn't really uh like I don't have practice talking about this one but for example you have just j4 or J where I might J as you go to zero right um and then you can maybe play around with small numbers like for example if you have 10 then you have one two five ten right um those are the factors and then you know if you do 20 maybe it's one two five uh or one two four five 10 20 I think something like that right um and then if you kind of figure it out um another way to say it is um you know um another way to think about that is that if it has even number of factors then it's going to be zero because you toggle the given number of times and then you know that's a full parity you have given numbers of uh yeah it's gonna be zero right and if you have odd numbers well then you have on well what uh and then now you ask well what numbers have uh an odd number of factors right well another way to kind of rewrite this for example for this 20 maybe I can even do something yeah we could do another number it doesn't matter but I think 20 is a pretty good number another way to write it is 1 times 20 uh two times ten four times five right so in this way you can see that for every Factor there's um the opposite not the opposite but like I forget the word the um the dividend no I don't know but whatever as a partner in which it creates the number right except for one case or not one case but it's just that it's not unique uh is when you have a square number right so for example we have 16 you have uh or maybe just yeah let's say 16 then you have one two four eight uh 16 right and here if you want to rewrite it you have one times 16 2 times 8 and then you have four times four so this four times four week is repeated twice which is why you know in distinct factors you only have odd number of factors and in this case because you press this button n times it is going to be uh what should we call it's going to be on right so one more thing to kind of note about this is that everything built on each other in a way even though it doesn't seem super clear at first because you have to because if you look at what I just said I'm just trying to tell you what happens on the 16th one after 16 right and not um how many bulbs are on um I'm not telling you how many bulbs are on after uh iframe right or something like this because basically for example you have six like we say 16 but there's actually 16 bulbs and then you know some amount of the uh whatever right but it turns out that you can actually do this inductive uh is it yeah in with induction you can do this with it inductively because for example after one cycle um after the first cycle you know uh you have some configuration right which is all once actually we have it here right and then after the second cycle you have all the one zero right but the key thing to note right is that uh and then three one oh one something I'm too lazy to figure it out but I like just to do the math but the idea here is that when you go from two to three for example everything before that doesn't change anymore right so the only thing that changes the third one and everything afterwards but then that's part of the math um so you actually have this formula if you take a smaller number before three it would never be zero right it would never be a factor for that reason or the other way around um and so the answer is in a kind of a way the answer for 16 is just the answer for 15 plus uh so F of 16 say is you go to F of 15 plus is six is light 16 on right after 16 rounds so you kind of phrase it that way and you can also say you know F of 17 is similarly you've got F of 17 or 16 sorry plus it's light uh 17 on after 17 rounds right and of course uh you know you can rewrite this as it's like 17 on after 16 rounds and then do one more round but we always kind of did the maths I'm not going to repeat that part under square root frame right so then now the question is how many numbers are there well as we kind of discovered have to end rounds with and light bulbs the only thing that's going to be on are the square numbers right so then now another way to phrase it is how many square numbers are there of length n right well sorry of size n or something like oh like of n or smaller or something like that maybe I'm saying it a little bit imprecisely but you get the idea right um and it turns out the number of square numbers you go or less than n is actually just a square with a band right why is that because um you can kind of think of it another way right the reason is because let's say n is equal to um some big number right let's just say 100 right so how many square numbers are a hundred right then you can write it as one two uh two to the two three Square uh Four Square dot I square right for some I um and in that case of course you can just self I squares you go to 100 or you go to n or whatever so you have I squares you go to n or technically something like this and then you take the square root and you have like I maybe I is that the best way to write it because I can also maybe reverse imaginary so I don't know whatever the point is that you know so that's why the answer is just going to be return square root of n uh yeah give it a run now after and of course uh I mean of course you want to round down uh technically is going down but there might be some mathematical imposition so we'll see I don't think it exists under uh one billion but I could be wrong let's see okay yeah uh I believe someone proved this to me or maybe it wasn't available some other number but I could be wrong so I don't know someone you know have a counter case let me know um due to IEEE um numerical I almost say in position it's just you know that's how these things work sometimes but I believe it should be okay you could add a little bit of effect if you like but I don't know if that messes things up um cool uh that's what I have for this one hopefully the explanation uh let me know what you think the code is very short but the explanation is the fun part I suppose so yeah uh I'm gonna call it a night and watch the rest of the NBA games if you're here let me know uh well one of you watched NBN what team are you winning for this year and that's all I have so stay good stay healthy to go mental health I'll see you later take care bye
|
Bulb Switcher
|
bulb-switcher
|
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb.
Return _the number of bulbs that are on after `n` rounds_.
**Example 1:**
**Input:** n = 3
**Output:** 1
**Explanation:** At first, the three bulbs are \[off, off, off\].
After the first round, the three bulbs are \[on, on, on\].
After the second round, the three bulbs are \[on, off, on\].
After the third round, the three bulbs are \[on, off, off\].
So you should return 1 because there is only one bulb is on.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `0 <= n <= 109`
| null |
Math,Brainteaser
|
Medium
|
672,1037,1491
|
412 |
hello welcome to my channel i'm here to do my angelico challenge uh today we have leeco 412 fits bus and this is one of the easier questions um like what it's uh write a program that output a string representation of number from one to n i think you all know what's this um i'll just i won't repeat it so what's that mean is it could be um divided by three and five and it will output fixed bus if it's only can divided by five it's buzz if you only can divide by this then output i mean three then output fifth and other than that then we can just return the number itself okay we're gonna loop through 1 to 15 in this case you see one cannot divide by either three and five is just one so three can be divided by three only first five can be divided by five only and bus in this case 15 and can be divided by both number and fifth bus so that's the problem i know it's kind of easy and that's why people hate it but it's always good to practice sometime when you just start beginning coding the legal problem so we start with output list with newer array less always and return this output list the end and we have this four is equal to we need to loop through from one all the way to i mean i last or equal to n i plus and now we have 1 to i in this for loop what can do is f i mod 3 is equal to 0 that means it can be divided by 3 or n i can be divided by five equal to zero in that case output will add and words call this bus else if see i'm not typing so fast um so now we have i divided by three equal to zero at that time we'll output dot add will have if it's three will be fixed else the rest of uh actually we have one more else f divided by five to the zero then output um buzz now if cannot divide by any of them the output.add the output.add the output.add i would say i write the number plus as an empty string so it will make this integer become a string so eventually i'll put this it should be good here missing this and now we see one here and that's it for this question and then i think it's no more questions they just need to practice more other than that i will see you in next video bye
|
Fizz Buzz
|
fizz-buzz
|
Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_:
* `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`.
* `answer[i] == "Fizz "` if `i` is divisible by `3`.
* `answer[i] == "Buzz "` if `i` is divisible by `5`.
* `answer[i] == i` (as a string) if none of the above conditions are true.
**Example 1:**
**Input:** n = 3
**Output:** \["1","2","Fizz"\]
**Example 2:**
**Input:** n = 5
**Output:** \["1","2","Fizz","4","Buzz"\]
**Example 3:**
**Input:** n = 15
**Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\]
**Constraints:**
* `1 <= n <= 104`
| null |
Math,String,Simulation
|
Easy
|
1316
|
258 |
hello everybody and welcome to the DC AC channel today we're going to be solving another lead cold question and just kind of preparing for technical interviews so let's pick some question remove outermost parentheses just that sounds probably too easy department table doesn't sound like something out like add digits fifty five point six percent have solved it's not a lot of people maybe it's just a very simple question that's why given I a non negative so it's a 258 add digits given a non-negative integer none repeatedly at non-negative integer none repeatedly at non-negative integer none repeatedly at all it's digit digits until the result has only one digit well I mean that's an easy one so you basically have to separate you would have a none and if you represent you're known for example that's our UNAM if we represent it as an array of characters all right we can in the first iteration we can loop all that this will give us right maybe I didn't really read this properly repeatedly add always digits until the result has only one digit so okay I see so we are actually over the three plus 8 is 11 is yes yeah well actually it's the same in this case it would be a bit too easy because we would if we look at all those three we would end up with eight and this is our inclusion if it was three five eight then we would have this type of array in our first tube which would give us 16 which we could get again separated 1 + 6 + 7 something like this okay well we + 7 something like this okay well we + 7 something like this okay well we could basically start let's put all now as an array or maybe even I want to bring something real fast how much yeah let's just see how a string for example we would have a string two characters and we want to have the length so we would have a digit will transfer it to string and then we just want to print its length okay that works so while let's have our num 10 equals num wire the length of string from num 10 is greater than 1 what do we want to do we would loop four digits in string 10 so for each digit we would basically with taran a batch operation for that or do we really I guess would have our temp result equals zero and would have 10 results incremented by int out of this digit and the digit is from this shrink array so we are incrementing our digits into a temp result and at the end we want our num dam to be this new temp result and we would then again look at non temp we would convert it again into an array we would look at its length if the length is greater than one we need to again start having a sum of each of its digits and yeah I think that's more states it's kind of crude but hello can you do it without any loop / hello can you do it without any loop / hello can you do it without any loop / recursion we are in constant runtime that's an interesting dot I'll leave it for now but maybe we can answer that it kind of tab hmm maybe there's some math thing going on I mean I'm not certain you can do this in any way other than you would definitely need to loop over each of those elements you cannot really you don't really know the end result and Q you have at least gone through each of the digits and then you really have to go over in the next iteration from going from the resulting digit you know and all that not digit but number so I don't think in this case there is a solution at least to my knowledge but it's interesting so quickly we are going to be returning our temporary result I'm just thinking about what if we have an empty and well or just a single digit then we basically return it right and we know that this is an integer type so we don't really care about the covering for other types let's see in this case we get 38 let's run it and see what we get yes we get that let's go nice to get away from the example and oops was it like this and then three five eight mmm-hmm I don't know why people don't mmm-hmm I don't know why people don't mmm-hmm I don't know why people don't like this one maybe it's just to easier I'm not sure yeah sounds good it's just a loop we cannot look that I think maybe that's why it just doesn't really look like something that's super interesting and yeah we solve it so yeah this kind of this is kind of an easy question but I guess it was still worth going through the whole idea of looping through arrays of strings that we converted from an int I'm gonna see if we can get some better question hopefully we can get a better question basically next time for now I hope you learned something if you're new to the channel maybe because she was subscribing it definitely helped me a lot my current goal right now is 10 subscribers and I'm almost there and I'm really stoked for forgetting that goal so to help me a lot if you do and yeah have fun and see you next time
|
Add Digits
|
add-digits
|
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
**Example 1:**
**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
**Example 2:**
**Input:** num = 0
**Output:** 0
**Constraints:**
* `0 <= num <= 231 - 1`
**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
|
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
|
Math,Simulation,Number Theory
|
Easy
|
202,1082,2076,2264
|
5 |
Hi friends welcome back to another video and in this video we will see the longest palindrome substring so this is a medium level problem and basically we will be given a string in it so let's zoom to a string let's c a b a so this is your longest palindrome substring. If we want to find out, then first let's talk about what the sub string can be. So if we talk about this string, its substring can be c can be A and then C can be A and A can be A. B can be ABA, A can be right, then the ones starting from B will be B, A and maybe B in the end, A, so all these will be strings, right, now we have to see which one is palindrome, so C is palindrome, obviously C thing. If there is only one element then it will be a palindrome. Right C is not a palindrome. There is no B, there is A, so basically we get three strings, this is a palindrome, this is a pallidum, but which is the largest pallidum, whose length is the largest, A B, so the basic question is In this program, brother, you have to print such a substring which is the largest and is a palindrome, then there is a function, now this program can also be done with DP, it will be done in a very efficient way with DP, but now we will see the normal method, the naive one, in which what we will do is a We will create a function called ' what we will do is a We will create a function called ' what we will do is a We will create a function called ' palindrome'. There will be a palindrome'. There will be a palindrome'. There will be a function named 'palindrome' which will function named 'palindrome' which will function named 'palindrome' which will tell whether if we pass a word or not, it is a palindrome or not and we will create all such sub- not, it is a palindrome or not and we will create all such sub- not, it is a palindrome or not and we will create all such sub- strings and pass them one by one in this palindrome and see which is the largest sub-string which is largest sub-string which is largest sub-string which is also a palindrome. If we display it as output, then we code based on this philosophy, so first of all we create the above function, Is Palindrome, take public boolean because it will tell true and false and name it E Palindrome and here it will be string and Here I will take comma J, I comma J, so basically what I mean to say is, as in the example we have taken, C A B A will complete the string, B will be like different sub strings, right like A is a sub string, A is pass. Instead of doing what will be passed will pass its index like index of C will be zero, one of A will be cut of B, three of A, so what will be passed to denote the string A, one will be passed in i and two will be passed in j. If this is done then we will not have to create different strings and in this we will use a basic method to check the palindrome of two pointers. Suppose there is a string a c, then the first pointer will point here and the last pointer will point here. Will do and keep on matching, if the match is not matching on the first point, suppose a and c are not matching, then it is Pale Andrum, no, we will return from here, brother, this is not Pale Andrum, suppose instead of a, it would have been c. If it matches, then move this pointer back and then move this pointer forward and then match. BB is also matching, then move this forward and then move this backward. It is matching. Now that we have reached only one, there is no point in checking. So this will be pale androm right so on the basis of this concept let's write this pale androm function and write here while I is lesson j care c I am removing the first character add k at i so took the character from eighth index then from j index Let's take the character Add K At J Now we have both the characters, if not equal then only we can determine that brother, this is not a palindrome, if not equal to C2 then you return false, okay if it is not so. If it happens, then what were you doing with I, we were moving forward and J, minus, backward, right, if no flaws were found, if palindrome did not fall, if you are looking for flaws in a person, if not, get some demat. If it is correct then what will we return in the end as True? If there is no false return then what to return brother True. Now here will be a little interesting story. We will have to create all the substrings, so what is the simple way to create all the substrings? You will have to run a nested loop, right, to create all the sub strings, I am running a loop like eight a i ect 0 i lesson, so the length of this is calculated only once n e add length and here we write a i plus and here We write for i at j and this is run with i. Okay and j lesson a j plus. If we want to understand how I am doing then we can understand from this example. Now see what was the first index 0 1 2 3 So you see here it is starting from zero, in this it is starting from one, in this it is starting from two and in this it is starting from three. Right and then its next element is required, so the loop has been run here accordingly. Now in this palindrome we will send if in this palindrome we will send string and i and j if it returns true from there then okay it means what is the string that we sent is that palindrome. Now palindrome can have many substrings but we have to What is needed: If I want the largest substring, then to What is needed: If I want the largest substring, then to What is needed: If I want the largest substring, then to maintain the largest, I take two or three variables, I take one, Max, in which we will store the length, what is the length of the substring, it is a palindrome and I take one, start, I also take it as zero. By default, where does the end because if it is a string then it must start from somewhere and end somewhere, then I take the start and end, if it is so, if it is a palindrome then I will check that the length is more than the max. Otherwise, here I take j - aa + 1. It is okay Otherwise, here I take j - aa + 1. It is okay Otherwise, here I take j - aa + 1. It is okay because both are starting from the same index, so in this way we have calculated the length of the sub sting. If it is more than the max, then this is a useful person for us. Okay, so we will update max and write 'j' so we will update max and write 'j' so we will update max and write 'j' minus 'i', ' minus 'i', ' minus 'i', ' psv', 'start', 'end', ' psv', 'start', 'end', ' psv', 'start', 'end', ' start' will be 'i', 'end' will be 'j', start' will be 'i', 'end' will be 'j', start' will be 'i', 'end' will be 'j', our work is done, now what will we do after this loop, all in our max. There will be the length of the string but it is not asking the length, it is asking us to return all those strings, so what will we do, here we will return addot substring function and use the function of Java and it will start at the beginning and we cannot give end at the end because If we have to give one more sub string at the end, then we will float it here. If you give index two like this, it will take only till one, so we need till two. Suppose if the end is two, then what will we do, we will give plus and so that the index which is Till I pass, they will consider. I think we have sorted. Now let's run it and see if the sample test cases are passing. Now let's submit. As if we had not used DP, then most probably it would have had a very low ranking. Okay. So the ranking is very low but our solution is getting submitted to the athlete right so this is not the best way to solve the problem but this is solving our problem so sometime in the next video we will talk about how we can solve this with DP. How can we solve this in less time, so thank you so much for watching this video, see you in the next video.
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
1,970 |
hello everyone welcome to quartus camp in this video we are going to cover one of the heart problem that has been asked in weekly contest of fleet code which is last day where you can still cross so the input given here is ah n cross n matrix where the row and column represent the dimensions of matrix where all the cells are represented as land and they have given coordinates for each day where the water will be filled in the mattress so we have to start from any of the rows from the first row and reach the last row by traveling only through land that is zeros so let's understand this problem with an example so the input given here is a three cross three matrix and all the cells are filled with zeros which represent land so let's start with the very first day and they said the matrix is indexed with one index which means there is no it start with one two and three same way one two and three so now uh we are starting with the index one comma two on first day which means one comma two will be flooded with water on the very first day so now our task is to reach from the topmost row to the bottom most row uh and uh no matter which cell we are traveling so we have two options to travel to the last row so via the first cell and the third cell in the first row so these are the two options so you can travel on the first day from the row one to row two row three so moving to the next cell that is next day will be flooding the cell two comma one so once we flood the cell two comma one we stopped with the option which we can travel from the very first cell because there is water in both the directions in the right as well as down but we don't have any left or up cells since all the cells can travel only in four directions we cannot travel from the first cell as the second cell is already flooded with water we cannot travel from the second cell as well so the only option we have is traveling through the third cell but we can still travel from the third cell to the last row so we can walk on the second day as well so third day the cell we are going to fill with water is three comma three and once we fill it with three comma three uh we have again an option to travel from the last cell in the first row to the other cells in the last row so we can cross successfully on the third day as well so again the cell we are going to fill is two comma two on the next day so fourth day we are filling water uh on the cell two comma two so now we have only option to travel from the third cell which is also been blocked because you cannot travel straight as well as travel in the previous path so now we cannot travel from the first row to the last row so we are stopping with the third day itself after third day we cannot travel to the cells so this is gonna be our output so how are we going to approach this so we have seen similar problems in our channel already one of the problems is sim swim through rising water which is again same encroaching grid where water will be rising each day and they want us to swim from the cells which has water here they are asking us to walk through the lands so you must be aware by now we are going to obviously use bfs technique to traverse through these cells and try to reach the last row so we have seen enough videos to uh learn how to do a bfs in a matrix so you can you have a lot of reference videos but here we are going to go through a high level algorithm and then get the details in the code so we are going to as usual gonna have a queue which is going to hold the coordinates where we can travel the travel through land so we are going to start from the very first row adding the cells uh which are having zeros from those cells we are going to travel through the rest of the cells to the next row and then to the last row and whichever cells reaches the last row then we are going to update our result according to that so if we are trying to perform bfs for each filling of water at each day then it is going to time limit exit because uh there is a lot of input after every input if you try to check then definitely it is not going to run in optimal time so how do we do this bfs in a better way so there comes the option for doing binary search so why binary search because we know there are input for nine days given in the uh cell so obviously the output is going to be either from one to nine so we know the limit or the bounds of our uh result so in that case according to our previous binary search videos if we know the lower bound and upper bound of our result then we can obviously go for binary search and the result the bound is in ascending order so now in this case what are we going to do is as usual in any binary search problem we are going to divide the output and fix a mid value and check whether we can achieve or whether we can move from the top cell to the bottom cell by fixing at that particular day if suppose from 1 to 9 the mid value is going to be 5 so we are going to fix 5 and check whether we can move from the top row to the bottom row on 5th day after filling water in this 5 cells if that is possible then possibly our answer could be five or more than five in that case we will fix our lower bound that is left to five and right bound will be at nine and we will do our search between five to nine if not if we cannot do or start from the first row to reach the last row by filling the five first five cells in that case our answer could be less than five so what are we going to do we are going to fix our left bound to 1 and right bound to 5 and do our search again between 1 to 5. again we will fix the mid to 3 and then start our search the same way we are going to perform this bfs to find whether we can approach the last row with within that days if that is the case we keep adjusting our limits and finally arrive at our results so hope you're understanding the solution you will get a clearer explanation when we code it so before getting into code this is going to work in big o of row into column into log of row comma column row into column because to iterate all the rows and columns it is going to take row into column time and to do a binary search between these values it is going to take log of row into column time complexity so let us go to the code now so before getting back to our main method let us look into our helper method which helps us to perform our bfs so here we are passing the cells and the row comma column as the given input and the day at is nothing but the mid value we are going to calculate so this is nothing but that we are at the particular day where we have to fill if we are at day five then we have to film only five cells and check whether we can reach from top row to the bottom row so this grid is going to help us to understand in which path we are traveling and which cells we have already visited so now we are going to iterate the number of days and fill our grid with only those values that is if the day is at five then we are going to fill our grid only with first five cells which are given in the input to one so here we are using a minus one because the given cells are one indexed but the grid here we are using is zero indexed array and as usual we need our help of q and we are going to start from the very first row that is why we have kept 0 and number of columns to iterate so once our first rows value is 0 then we can start from that row to travel towards the last row so we are updating our queue with that coordinate and update the cells value in our grid array to 1 because once we started with that cell which means we have visited that cell so we don't let another cell visit through that so we are updating to indicate that the cell is visited so now once added we are going to i start iterating the coordinates from our cube and we are going to travel till all our coordinates gets empty so as usual while performing bfs we are going to add pick the current coordinates and add it with all other directions so here we have declared direction array globally which helps us to calculate all four directions so before that if the new row or column is the last row then in that case we have reached the last row which means on that particular day after filling that many cells with water we have a path to travel from the 0th row to the last row so in that case we successfully traveled so we are returning true to our main function if not we are going to iterate the array and i whenever we reach the last row we are going to return true so as usual we are going to iterate in all four directions and find new neighboring coordinates x and y which is nothing but the neighboring coordinate at all four directions at each direction we are checking whether they the cells are out of index or they are in the same row or same column or if the cell is already visited then we are going to skip the titration if not if it is not one and if it is not out of index and if it is the next row or column then in that case we can travel via that path so we are going to update it update that path to one because we have visited it and update it to our queue so you can do it either way first update the coordinates to our queue because from that cell you're further going to explore any cell in the next row and we are going to update that cell has been visited so this is going to keep going until all the coordinates are going to be get emptied and once we've reached the last row we directly return true and skip all this because all we wanted is whether we can travel to the last row from the first row on that particular day if any path exist then it is going to return true if not it is going to return false which mean on that day we cannot travel from the zero through to the last row so here comes our main method we now understood our uh bfs method so here we are going to keep our left bound to one and right bound to the number of coordinates that are given in the cells as our input and days equal to 0 is nothing but it is going to be the number of days maximum we can travel from the top row to the bottom row which is going to be our output so now as i said we are going to perform a binary search so we are going to iterate till our left meets right and find a mid and pass the mid value to our bfs method as day at so once it returns to true which means on the day we can travel from the top row to the bottom row so the output can possibly be that value or more than that value so we are going to first fix that as our output and we are going to fix that left bound to mid plus 1 which means this can be output or the left bound can be fixed more number of days and can be iterated if not if it returns false which means we cannot travel from the top to the bottom row on that particular day so the days can be lesser the output days must be lesser so we are fixing our upper bound to mid minus one so once all this completed the number of days will be stored in the days variable and that is going to be our output so hope you are understanding this solution let us try running it so yes let's submit yes a solution is accepted 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
|
Last Day Where You Can Still Cross
|
sorting-the-sentence
|
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**.
|
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
|
String,Sorting
|
Easy
|
2168
|
948 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem bag of tokens so this is basically a little game and the rules are pretty simple so there are two concepts one is known as the score and another is known as the power initially the score is going to be zero and initially the power is going to be given to us as a parameter so in this first example you can see that the power is 50 we're also given a list of tokens suppose that the list is 100 and 200 actually to make it more interesting let's change it to this now for every single token that we have for us to be able to play a token we can do so in two different ways and it's going to be related to how these things work as well so we can play any of these tokens face up if we want to play it face up though it's going to cost us this much power or basically if this token is 50 it's going to cost us 50 power if the token is 100 it's going to cost us 100 power but we don't have that much power so therefore we can't play this token at least not right now we also have another choice of playing any of the tokens face down it won't cost us any power but it will cost us some score so I didn't mention earlier but when we play a token face up we actually gain one score but when we play a token face down we actually lose one score but when we play a token face down instead of costing us power we actually gain power so if we decided to play this token face down we'd gain 100 power but we would lose one score now we can only play a token face down if we have enough score if we have at least one score to basically give now if we have zero score which is what we initially start with we can't play anything face down ultimately what we're trying to do here is maximize the score itself and then return whatever Max value we can get for that so basically everything that we've talked about boils down to wanting to play certain tokens face down which it's going to cost us some score sure so like it'll cost us one score but it will increase our power to the point that we can play multiple tokens so let's just go through this example we have 50 power we can play this token so now our score will go to one our power is going to be down to zero so if we want to play another token we can't and of course which ones would we want to play well for the record when we played this one we played it face up among the other tokens to play we probably want to play the smaller ones face up we don't have any power so we can't play them face up we want to play one of these tokens face down probably we want to play the biggest token face down because it's going to cost us one score regardless but this one is going to give us 100 power whereas playing this one face down would only give us 50 power we want more power so we can play more tokens and maximize the score so we decide to play this one face down we lose a score so our score is down to zero but our power is going to be 100 now we can play this token and then our score will be two our power will be down to zero but this is the way to maximize the score so the max score that we were ever able to create is two the algorithm for what I just did is actually very simple we kind of want to be greedy don't we want to play the smallest tokens face up but we want to play the biggest tokens face down how can we arrange the input such that it's easy for us to get both those well we can basically sort the tokens and then use a two-pointer tokens and then use a two-pointer tokens and then use a two-pointer Technique One pointer over here will be the smallest values and a second pointer over here will be the biggest values so this is basically a greedy solution usually the hardest thing with greedy Solutions is just confirming that they work like this solution might seem too simple to you at first I think it probably make sense to you that we want to play the smallest tokens face up I think that much probably makes sense like if we have a choice any token is going to give us the same exact amount of score so if we have a choice play the ones with a smaller value it'll cost us less power and similarly when it comes to playing bigger tokens we want to play those face down cuz then we gain more power and it costs us the same exact amount of score so intuitively it makes sense the question is like what if I had an extra 100 in here so suppose there's a second 100 over here well let's say it costs us 50 power to play this token and then we have one score zero power then we play this one face down so then we're back to zero score but we have 100 power now then we play these two now we're at two score zero power and now we have enough like with our two-pointer enough like with our two-pointer enough like with our two-pointer Technique we still have some tokens to play this is the last one though and when we play it's going to bring our score down to one it's going to give us a power of 100 now if we had more tokens to play we might be able to maximize our score we might be able to bring it back to two or maybe even higher than two but right now it ends at one so should we return one is one the result no because what we're going to do is keep track of what's the largest score that we could have possibly made at one point the score was two we could have decided to stop playing at that point we don't have to play every single token that we're given so that's kind of why this approach works it will find the maximal possible score even if it continues the simulation because we have no way of knowing if we can actually find a larger score until we continue to play as long as there are tokens left we will continue to play all tokens the overall time complexity of this approach is well the two-pointer solution is Big O of n the two-pointer solution is Big O of n the two-pointer solution is Big O of n but we do have to sort the input so that's going to be n log n where we're sorting the tokens now let's code it up so I'm going to initialize the result at the same time that I initialize the score variable and they're both going to be set to zero initially then I'm just going to sort the tokens input array and then we are going to start with our two pointer solution so left and right are going to be the pointers left is going to be set to zero right is going to be the length of the input minus one and then we're just going to continue while the pointers have not crossed each other ultimately trying to do is return the result the max possible score then we're going to check a couple things the first one is of course we want to play the token face up if we can so let's check is the power that we have greater than or equal to the cost of playing the smallest token we can find with the left pointer and so this is the cost of that token if we have enough power to play it let's go ahead and play it what does that mean well we're going to lose this much power so whatever value it had we lose that much we're going to shift our left pointer by one we're going to increment the score by one as well and to maximize the score just to keep track of what the max possible score ever was we can just take result and set it to Max of itself and whatever score we computed this is what we want to do if we can do it now if we can't do that we just don't have enough power let's try playing a card face down and we can only do that if our score is at least one so let's just check that the score is greater than zero so if that's the case we will take the token with the largest value and play it playing that entails decrementing our power by that same amount then taking our right pointer and shifting it to the left and decrementing our score by one as well now I'm not checking that the result is a new maximal here because if we're decrementing the score it's definitely not going to be a new Max so these are the two main cases now there is a third case if you don't want to get stuck in an infinite Loop what happens if we don't have enough power to play a token but we also have a score of zero so we can't play any of the tokens face down well at that point we should probably just return so we should just return whatever result we got because we can't do anything anymore or we can just break out of the loop and then end up returning down here anyway so that's what I'm going to do this is the entire code let's run it to make sure that it works and I had a unfortunate typo so when we play a token face down we want to add to the power cuz that's the whole point of playing a token face down we're losing score but gaining power here we're losing power but gaining score so sorry about that as you can see on the left though the code does work it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out n code. thanks for watching and I'll see you soon
|
Bag of Tokens
|
sort-an-array
|
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed).
Your goal is to maximize your total **score** by potentially playing each token in one of two ways:
* If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**.
* If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**.
Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens.
Return _the largest possible **score** you can achieve after playing any number of tokens_.
**Example 1:**
**Input:** tokens = \[100\], power = 50
**Output:** 0
**Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score.
**Example 2:**
**Input:** tokens = \[100,200\], power = 150
**Output:** 1
**Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1.
There is no need to play the 1st token since you cannot play it face up to add to your score.
**Example 3:**
**Input:** tokens = \[100,200,300,400\], power = 200
**Output:** 2
**Explanation:** Play the tokens in this order to get a score of 2:
1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1.
2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0.
3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1.
4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.
**Constraints:**
* `0 <= tokens.length <= 1000`
* `0 <= tokens[i], power < 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Merge Sort,Bucket Sort,Radix Sort,Counting Sort
|
Medium
| null |
1,059 |
hey what is up guys for this video i'm going to be solving the code 1059 all paths from source lead to destination and essentially for this question we're given a graph with directed edges and we're given a node which is designated as the source and one node that's designated as the destination and we want to figure out if every path from the source node is going to end up going to the destination one so in this example we can see that's not true because we have a path from the source 0 that goes here to 1 and it just ends up there and it doesn't get us to the destination so we end up returning false so we only want to return true if and only if all of those paths from source ends up going to destination so for example if there was another directed edge here from one to two then we would return to here because we have one path zero to one and one to two that gets us to the destination and the other path that comes from the source goes straight to the destination so that satisfies the requirement for the question and we return true for that so the approach that i'm going to take here is a depth first search approach and essentially starting from the source node i'm going to go through each of the paths and if we end up in a node that doesn't have any outgoing edges like this one here for example we can return false if and only if it's like the it's not the destination note so that's going to require us using a couple of extra data structures to keep track of some of the nodes we've seen uh for example if we're given uh another node here something like so if you have 0 and that goes to 1 and this goes to like 4 and the destination is 2. we want to have an extra data structure to keep track of the notes we've seen to avoid going in a infinite loop uh let's say we have like four that goes back to one so now uh this would end up being uh returning false since not all the paths from the source end up going to the destination because we have this path that could go on an infinite loop which starts from zero goes to one goes to four and just keeps going back and forth between one and four so we're gonna use a dictionary to spot something like this now we're just going to call it like a scene dictionary so that we're able to avoid this uh infinite loop so let's uh start visualizing how this would look like in us in an actual example okay so given this example where we have the source being 0 and the destination being 3 we're initially going to start by building out the dictionary that resembles this graph and it's going to look like this in the end once we iterate all the edges we're going to have a dictionary that holds the state of the graph so the key for this dictionary is all the nodes that have outgoing edges and their value is just a list of their a list of the nodes that they're going to so for 0 it's going to one and three we also have one that goes to two we have two that goes to three and that should be it we're going to use this dictionary actually to uh in our depth first search function so that we can iterate through the graph so once we call our depth first search function we're going to obviously start from the source just the signature of the function is going to be the source destination the dictionary you we built and like a scene uh dictionary so that we can avoid the infinite loop that we talked about so initially what we're going to do is check if we've seen the node that we're at right now if we did then that indicates that we're in a loop so we can return false we could also check if there is any edges going out of the node that we're in right now if there is no we need to make sure that's the destination if it's not then we return false otherwise we iterate the graph uh using the dictionary here so initially we're gonna mark zero as seen so the way that's gonna work is we're gonna call this function initially with zero as the source and the destination is always going to be the same which is three and now we go through each of the neighboring nodes in zero in a for loop so we're going to start with one then we're going to recursively call this dfs function passing it one as the source now so now we're gonna be a one and we're gonna go through the checks that we already did one is not in scene so far seen only contains zero and one is also not the destination since it already it still has outgoing edges so now we're gonna jump here to one and we're gonna do a for loop for all of its edges which it just so happens to be just one edge in this case so now we're gonna jump to two and we're gonna mark one as seen so now we've seen one and we're gonna do the same checks that we did at one as well we're gonna mark two a scene and jump to its edge which is three so once we reach three we're going to have a check that says like as i mentioned before if there's any outgoing edges and there is no outgoing edges for this case and it's also the destination so we just simply return true so we're here at this point and we're just going to return through throughout this call stack so now we're going to go back to here and go through the second iteration of the for loop so now we're gonna look at three so from zero now we're gonna go again to three and notice that three is not even in the scene dictionary that's because we check whether this is a destination uh before we add it to the scene dictionary so now when we're at zero and we go through to three we also return true again and this function ends up returning true because it goes through each of the possible paths starting from the source and they all lead to the destination now let's quickly look at an example where this returns false just to see what that looks like we have zero goes to one and goes to two and two is the destination so in this case the dictionary is just going to look like this zero goes to one and 2 that represents the graph so now when we do the for loop and go through each of the neighbors of zero we're gonna start at zero recursively call the dfs go to one and from one we have that check that we make sure that this is the destination if there's no outgoing edges and that's simply going to return false because this is not the destination and there's no outgoing edges so there is no possible way for us to get to the destination from the source using this path so this ends up returning false in the dfs and that's how we can code this algorithm i think this will make more sense once it's seen in the code so let me jump to that the coding part let's start by first building out the representation of this graph which is going to be that dictionary and here we can just have a check if we don't have anything in the dictionary or the destination or sorry the source is not even in the dictionary uh we can return false right away we can define our function here the dfs function which takes the initial node that we're going to be on so current node the destination the dictionary the way built out and a scene map so we can avoid the infinite loop and let me just return this and then the code for this so when we call it we're going to call it with the source the destination that we're given the dictionary that we already built and we can just leave this an empty parameter since it's going to default to an empty map so here is where we check whether we've hit a dead end so there's a couple things that we need to make sure if we hit a dead end and make sure it's the destination so instead of make sure like return true if it's the destination if we've seen the node then we return false to avoid the infinite loop otherwise return true so for the function that's the going to be the final case we're going to return true if it satisfies everything else so if we hit a dead end that means that there's no neighboring nodes in the dictionary for the current node that we're in so we only want to return true if it's the destination so we're going to do return uh this current node that we're on is equal to the destination so that way once we hit this node one this is not the destination so this is going to be false current is going to be one and destination is going to be two so if the note that we've seen is in the note that we're in is in scene then we return false otherwise we can add it to the scene have the recursive call here and once we're done we can remove it from the scene or a scene dictionary so now we go through each neighbor and if the recursive call returns false we can simply return false otherwise we return true and that should be it's there's one uh minor check that we can do uh to prevent the case so if we only have one node that goes to itself like it's the source and destination we can simply check here and rather than returning false we can just return whether the source is equal to the destination if it's that's the case we want to return true otherwise that should do it and just a small typo we actually want to go through the edges here and yeah that should be it hopefully that made sense thank you for watching
|
All Paths from Source Lead to Destination
|
missing-element-in-sorted-array
|
Given the `edges` of a directed graph where `edges[i] = [ai, bi]` indicates there is an edge between nodes `ai` and `bi`, and two nodes `source` and `destination` of this graph, determine whether or not all paths starting from `source` eventually, end at `destination`, that is:
* At least one path exists from the `source` node to the `destination` node
* If a path exists from the `source` node to a node with no outgoing edges, then that node is equal to `destination`.
* The number of possible paths from `source` to `destination` is a finite number.
Return `true` if and only if all roads from `source` lead to `destination`.
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[0,2\]\], source = 0, destination = 2
**Output:** false
**Explanation:** It is possible to reach and get stuck on both node 1 and node 2.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1\],\[0,3\],\[1,2\],\[2,1\]\], source = 0, destination = 3
**Output:** false
**Explanation:** We have two possibilities: to end at node 3, or to loop over node 1 and node 2 indefinitely.
**Example 3:**
**Input:** n = 4, edges = \[\[0,1\],\[0,2\],\[1,3\],\[2,3\]\], source = 0, destination = 3
**Output:** true
**Constraints:**
* `1 <= n <= 104`
* `0 <= edges.length <= 104`
* `edges.length == 2`
* `0 <= ai, bi <= n - 1`
* `0 <= source <= n - 1`
* `0 <= destination <= n - 1`
* The given graph may have self-loops and parallel edges.
|
First define a function f(x) that counts the number of missing elements until x. Then use binary search with the given function f(x) to find the kth missing element.
|
Array,Binary Search
|
Medium
| null |
942 |
all right think we're hey what's up guys Nick white here just I do tech encoding stuff on twitch and YouTube if you wanna check the description I have everything I'm doing another leak code video I have all these recode videos I'm doing series on videos we're doing the easy one right now this one's called di or ya di string match d stands for decreasing I stands for increasing it's an easy one it was pretty easy given a string that only contains letters I and D so it tells you if it's increasing or decreasing then you're going to want to return an array of integers from zero to the length of the string so in the first case we see we have four letters right here so length of this string would be four so then we're gonna have an array it's gonna be one more than the length of the string right so the length is four here but the array is gonna have five elements so the numbers are gonna be corresponding to the letters of the string right so if we see an eye then the next element in the string is going to be increasing right so it would go from zero and then we see four and then we see one three because we see decreasing in the second spot for is going to decrease to one increase one is going to increase to three decrease three is going to decrease to two right hopefully you guys understand what I'm saying here let me know in the comments if you don't understand but should in if we see increase it's just gonna go zero one two three pretty straightforward there's just gonna be one more element in the output array than there is in the input string so not too bad so I didn't really know how to do this at first it was kind of I had to like a look up how to do it honestly it's not it wasn't intuitive to me I guess it should have been but now that I know how it's done it's pretty straightforward I wonder if I'm gonna see more problems like this in the future but this is the solution right here I'm gonna run it I'll show you it works and then we'll retype it out and then I'll explain it as we go so let me actually let me explain it and then I'll type it out okay so 100 percent of solutions right complete success so the size is going to be s dot length then we have a low we basically have a low and high points or high pointer is gonna be the length of the string low is going to be zero and we're gonna have the output of right because we have an integer output array this is the integer output array and we're gonna loop through this string of I and D and check at each letter if we see an IR D if we see an eye we're gonna make that current element of the array the low pointer and we're gonna increment it at the same time so we could just make it low and then just do low plus equals one just so you guys understand that it's more clear else we're gonna make it high right so high is gonna start at the top and that's it's gonna work out perfectly every time luckily and by the end of it the low and high will be at the same point in the output array we're just gonna have to set the very last element because I said there's gonna be one more element of integers then the string has of letters right so we're gonna you could set this to low or high if we set it to low it's also gonna work and then you just return the array right so we can I could type this out for us again right in size is equal to s top plane right so we get the length of the string right and we're gonna need the array to be figure of one element bigger remember that and then we're gonna have our low pointer the sequence to zero just like eight pointer is always zero and people and there's always the length of the string and then int I you can call these whatever you want actually is going to be equal to size and we're gonna have our in Turay so int I called it output array call whatever you want is they go the new int of size plus one because there's going to be one more element loop through hopefully you guys are understanding this too sighs just keep incrementing you could do that or us dot length you know look throughout where you want and then we're gonna do s touch our adds i if i start i is equal to an i were going to and this is why just so you guys understand if we see an eye the next element has to be bigger so we're gonna want to put the lowest possible element at that current point in the Iraq right so output array of I is equal to well right and then we'll all increment it here just so it's more clear for you guys else you know the exact topic opposite and will decrement I this is how I like pointer things work anyway usually pointer problems that read are to do with sorted things so I wasn't this wasn't intuitive to me and then hi gets deeper message right so and you know if we see a decrease then hot we put the maximum element in because the next one can't be the maximum it's got to be less than that's literally all it is and then at the end just because we have that one extra element we just got a you know do output array of size is equal to lower high whatever you want cuz they're gonna be the same because heís getting decremented while low is getting incremented and then we return the array and hopefully this works pray you know Wi-Fi might be a little pray you know Wi-Fi might be a little pray you know Wi-Fi might be a little bit messed up here what's going on oh no s stuck char at I know what's the issue oh you got to make sure when you're doing in Java you gotta have the single quotes for characters sorry about that okay it works ran perfectly perfect hundred percent of solutions beat yes 100 percent okay so that was the video thank you for watching let me know in the comments if I didn't explain it that well or what improvements trying to get better I just started streaming again more consistently this semester just started so I'm doing an algorithms class this semester too so I'll beat you like back on streaming a lot more so thank you guys for watching please check me out on Twitch matrix man and then you know subscribe thank you very much see you guys later
|
DI String Match
|
super-palindromes
|
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where:
* `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and
* `s[i] == 'D'` if `perm[i] > perm[i + 1]`.
Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**.
**Example 1:**
**Input:** s = "IDID"
**Output:** \[0,4,1,3,2\]
**Example 2:**
**Input:** s = "III"
**Output:** \[0,1,2,3\]
**Example 3:**
**Input:** s = "DDI"
**Output:** \[3,2,0,1\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'I'` or `'D'`.
| null |
Math,Enumeration
|
Hard
| null |
356 |
hello everyone let's look at lead code question 356 line reflection so in this question we're given end points on a two-dimensional plane and we need to two-dimensional plane and we need to two-dimensional plane and we need to find if there is such a line parallel to the y- axis that reflects the given the y- axis that reflects the given the y- axis that reflects the given points symmetrically in other words answer whether or not if there exists a line that after reflecting All Points over the given line The Original Point set is the same as the reflected ones note that there can be repeated points okay before we're going into depth uh with these examples let's look at the constraints so the constraints are n equals the points. length and the values of n will be somewhere between 1 and 40,000 the values of the points i j or 40,000 the values of the points i j or 40,000 the values of the points i j or XY will be negative to positive 1 billion and the follow-up says could we billion and the follow-up says could we billion and the follow-up says could we do better than o and squared time all right let's take a look okay so here's the code let's run through it with the examples basically what is happening here the first chunk of code defines the Minx and Minx Max X values and the set scene this will Define for us the Reflection Point for the Minx and Max x uh values so we do so next in the for Loop we go through every single point and locate the Minx so we find the minimum x value of all the points and then we find the maximum x value of all the points and add that to the set and after we do that we then uh calculate the sum so Minx plus Max X will then be the Reflection Point the center point of all the other points after we do that then we go through all the points once more we Loop through them and we check if the sum minus X Y is not in scene return false this line of code basically checks the opposing x value the opposite x value and the Y value which will be the same in scene we'll check if it's in the scene if it is in the scene that means that the uh reflected Value Point does in fact exist but if this uh point is not in scene then we return false because that point is not being reflected uh correctly so then let's run through this example okay so first thing we do in this example we have the points 1 one and negative -11 as you can see it and negative -11 as you can see it and negative -11 as you can see it clearly reflects here but let's still run through this simple example we Define Min X to be uh infinity Max X to be negative Infinity then we go through every single point and then we Define Min X to be the minimum between uh Minx which is currently infinity or one which is smaller one so we Define minx then to be one and then for Max X which is bigger we have negative infinity or one the same value we just looked at the first x value of this point and that is one and then we add this to the set so the set currently has 1 one the next value is -11 so we got this one now value is -11 so we got this one now value is -11 so we got this one now we just looking at negative 1 one and we do the same thing so for Min X which is smaller one or negative 1 is smaller so it becomes Minx the next point is one which is bigger one or one they're the same thing so max remains as one so see becomes uh the set of 1 one and -11 then we calculate the of 1 one and -11 then we calculate the of 1 one and -11 then we calculate the sum so add these two together the Minx plus the Maxis is -1 + 1 that's zero plus the Maxis is -1 + 1 that's zero plus the Maxis is -1 + 1 that's zero this will be our Reflection Point our reflection line then we check through every point to see if the reflection exists in the scene set like we said so looping through all the points we have one once more and uh we check so sum is equal to what currently two or sorry Z because 1 + 1 is 0 and then we do su - 1 because 1 + 1 is 0 and then we do su - 1 because 1 + 1 is 0 and then we do su - 1 that's negative 1 some negative 1 minus one that's 1 one so these points exist in the scene set that just means that the corresponding points are existing in the set and uh they have a reflection value and it is true so we return true let's look at a more complicated example now for this example we have the following points okay so we have 22 -22 following points okay so we have 22 -22 following points okay so we have 22 -22 -14 and 14 so there is clearly a -14 and 14 so there is clearly a -14 and 14 so there is clearly a reflection value at x equals z but we need to run through the code and check exactly uh the processes which validate these reflection points so we Define minx and Max X already as infinite and negative infinity and are set to be an empty set we Loop through every single point and uh we Define minx and Max X we update these values and add them to the scene set so Minx equals infinity 2 -2 -2 -2 and this makes sense because 2 -2 -2 -2 and this makes sense because 2 -2 -2 -2 and this makes sense because the smallest x value is -2 and the smallest x value is -2 and the smallest x value is -2 and the largest x value is two so max x = largest x value is two so max x = largest x value is two so max x = 2 -2 and as we're doing this we've 2 -2 and as we're doing this we've 2 -2 and as we're doing this we've filled up our scene set so the scene set is now the points that we have described and so then we want to find our reflection line how do we do this well sum equals Min x + Max X that is -2 well sum equals Min x + Max X that is -2 well sum equals Min x + Max X that is -2 + 2 = + 2 = + 2 = 0 so then once we get the reflection line defined we can do the final part which is Loop through every points and check if the Reflection Point exists in scene if it doesn't we return false okay so let's run through this part because it's probably the most tricky at first uh glance XY in points that is first let's go through 2 two uh sum minus 2 two what was Sum sum was Zero 0 - 2 is -2 and Y Remains Two was Zero 0 - 2 is -2 and Y Remains Two was Zero 0 - 2 is -2 and Y Remains Two okay is -2 in scene you say yes it okay is -2 in scene you say yes it okay is -2 in scene you say yes it is so that means this is true next Point -2 to the value that we just validated -2 to the value that we just validated -2 to the value that we just validated as having a reflection point is sum minus -2 and 2 that becomes 22 okay is minus -2 and 2 that becomes 22 okay is minus -2 and 2 that becomes 22 okay is 22 in scene yes that is just the point we were at but this is the corresponding Reflection Point validated as true so then we go to the next point 0 - 1 is-1 then we go to the next point 0 - 1 is-1 then we go to the next point 0 - 1 is-1 and -4 so we say uh that's for this uh and -4 so we say uh that's for this uh and -4 so we say uh that's for this uh value right here 0 - one and4 is this value right here 0 - one and4 is this value right here 0 - one and4 is this point that we just used cuz We're looping through every single point and then we check is this value in the set it is it's this value and finally we do 0 -14 that's this value and this becomes -14 that's this value and this becomes -14 that's this value and this becomes 14 is 14 in the set that is the case so far all of these values have the reflection points defined as true so this return false statement will never be uh accessed for this example and we just return true for this uh example so let's once more look at the solution let's see if this solution Works submit all right so it works it's a great solution now what is the time and space complexity of this solution the time complexity of this solution is O of n where n is the number of points this is because we iterate through the points twice once to find the minimum and maximum X values and once to check if the Reflection Point exists in the set both operations take o of end time which simplifies to O of end time so then the space complexity is O of N and we use the set to store the scene points in the worst case all points are unique and we need to store them all into the set that's it for this problem thank you for watching
|
Line Reflection
|
line-reflection
|
Given `n` points on a 2D plane, find if there is such a line parallel to the y-axis that reflects the given points symmetrically.
In other words, answer whether or not if there exists a line that after reflecting all points over the given line, the original points' set is the same as the reflected ones.
**Note** that there can be repeated points.
**Example 1:**
**Input:** points = \[\[1,1\],\[-1,1\]\]
**Output:** true
**Explanation:** We can choose the line x = 0.
**Example 2:**
**Input:** points = \[\[1,1\],\[-1,-1\]\]
**Output:** false
**Explanation:** We can't choose a line.
**Constraints:**
* `n == points.length`
* `1 <= n <= 104`
* `-108 <= points[i][j] <= 108`
**Follow up:** Could you do better than `O(n2)`?
|
Find the smallest and largest x-value for all points. If there is a line then it should be at y = (minX + maxX) / 2. For each point, make sure that it has a reflected point in the opposite side.
|
Array,Hash Table,Math
|
Medium
|
149,447
|
67 |
in this video we'll be going over add binary so given two binary strings a and b return their sum as a binary string so in our first example our a is one and b is equal to one so our and then the sum of the bits is gonna be one zero so let's first go over the dot process we will need to add the bits from right to left we can implement a two pointer approach so one pointer i will indicate our current location inside a and one pointer j will indicate our current location inside b and in each of the iteration we will be finding the sum of the bits located at these two pointers we should note that when adding two bits there may be a carry over so we will need to keep track of the we will need to account we need to account for the carry too let's go over all the possible cases so let's indicate the current bits as b1 and b2 and our carry b1 b2 and carry and now we're going to try to find the sum of all the possible cases so let's first write out all the possible cases for b1 then all possible cases will be two currently i'm just writing out all the combinations that's possible now all possible values of carry now for now we'll find the sum of these this one sum is three two gets two one so in this case we have a bit is go to one in this case we have it's equal to one and carry is equal to one so we get bits is go to zero but carry is go to one in this case same thing in this case bit is go to one and carry is go to zero this one is zero carries go to one this case is similar in this case bit is going to zero and carry skills is there okay now we're ready to write the pseudo code create the following variables i our current index inside a initially at the last index because we're processing from right to left so our current index inside b initially at the last index two and also our results so it's gonna be a string builder to keep track of our result uh one more thing we need to notice is so one more side case we need to fulfill is one of the side cases the two input strings may not be the same length this means when we process the bits one of the pointers may go outbound when a pointer is outbound we will default the value of the current bit uh default value of the bits to equal to zero this will be more clear when we go through the pseudo code so while i or j is not outbound so greater than or equal to zero then we retrieve b1 from a so the current bits retrieve the current bits b1 from index i inside a make sure to convert it to a integer value if i is outbound we will default one two zero now we're gonna do the same thing to retrieve the bits from b so it's gonna be b two from index j is out of bound default b2 to zero with decrements j here and then we'll decrement i here now we're going to find the sum find the current sum oh one more thing we need to do when you keep track of the carry the current carry so find the sum here calculate the sum so sum is equal to first bit the second bit plus the current carry if sum is equal to three or just go to three or two then the carry will be set to 1 because in this case we can see if is if the sum is 0 3 or 2 our carry is already set to 1. else sets carry to zero then if sum is equal to one or three append one to our result because when we have one when our sum is go to three or one our business is our bit is going to be equal to one so we append one to our result else we're going to append zero else append zero to result okay now if after we process all the bits if carry is greater than zero we will need append another one two results now we're going to reverse results and then return a string representation of results we need the reverse result because we were processing the bits from right to left but we are appending bits to our resulting appending bits to our result string builder so we need reverse after it returns a string representation of result now let's go over the time and space complexity so our time complexity is equal to where n is the length of the larger string or longer string so i'm going to process all the bits and then space complexity is also going to be of n that's going to be for string builder or we can say is of 2 times n which should be similar because string builder and resulting string because we're going to convert this result to a string representation after so we can do two times n instead of just of n okay let's go over the code so let's first create our variables so a current pointer inside a initially from the end and j is um our current pointer set b also at the end our current carry is going to be zero i'm going to create a string builder and then while both of the pointers are not outbound or either one of them is not out of bound retrieve the first bit b1 from a so if i is greater than equal to zero then we convert the current bits to a uh to convert the current character to integer so again numeric value i then would decrement i after else we're going to be followed to zero if eyes outbound then similar process here and retrieve e2 from our second string at index j and what deck is j2 i'm going to find the sum b1 plus b2 plus carry and then set carry to if sum is greater is equal to if sum is equal to three or sum is equal to two we said carry to one else we set character zero and then we are append if sum is equal to one or sum is equal to three then we're going to append one to our results i always repent zero then if carry is still greater than zero after we process all the bits we're going to append one to our results and then return result.reverse so and then return result.reverse so and then return result.reverse so reverse the result and then to string let me know if you have any questions in the comments section below you
|
Add Binary
|
add-binary
|
Given two binary strings `a` and `b`, return _their sum as a binary string_.
**Example 1:**
**Input:** a = "11", b = "1"
**Output:** "100"
**Example 2:**
**Input:** a = "1010", b = "1011"
**Output:** "10101"
**Constraints:**
* `1 <= a.length, b.length <= 104`
* `a` and `b` consist only of `'0'` or `'1'` characters.
* Each string does not contain leading zeros except for the zero itself.
| null |
Math,String,Bit Manipulation,Simulation
|
Easy
|
2,43,66,1031
|
345 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is reverse veral of a string so this question is similar to a question called reverse words so in that question you reverse all the characters in that string in this question only have to reverse the vbls in the string and return it so we are given a string called s and we have to reverse only all the bubbles in the string and return it so bubbles are the characters a I or youu and they might upper in both lower and upper cases more than once so if this is the input string hello this will be changed to here you can see there are two WBLS E and O so you swap them so this will become holy and in this case you have lead code so you identify the WBLS first last uh wubble comes to the front the second last comes to the second most this goes here and this goes back here and this is the output we need so we declare two pointers which is starting at the beginning so this will be the start pointer and this will be the end pointer will be starting from the end we check if the characters at these pointers S and E start and end are not WS if that is the case s will move from left to right and end pointer will move from right to left and if those characters point to a Vel we swap those two pointers using a swap method and once these two pointers cross each other or meet when s is equal to E uh we end the iteration so let's Implement these steps in a Java program so I created a character array which will convert the input string into a character array so let's take the same example s is having hello so this will bect converted into a character array and I'm creating a string called vels which is containing uppercase and lowercase vels so I will use this string to check if a character pointing inside the car array is a Vel or not and I'm declaring the two pointers start and end start is pointing in the beginning and end is pointing at the end and I'm using a y Loop to increment the start variable and this is to increment the end variable so if that current character pointing at start so start is now pointing at H so this is having H I'm checking if H is present inside this bubble string it is not present so it is equal to minus1 so this condition will pass and start will increment so I move start and this while loop uh I check if the character at start is e I check if e is present inside this wubble string yes he is present so I stop this while loop will be skipped and it will comes to the second while loop I'm checking if the character at end is pointing at the character o I'm checking if o is present inside this V's uh string yes it is present so it will skip this while loop now s is pointing at e and he is pointing at o so we swap this two so this will become h o l e and now start will increment and end will increment to check for next bubbles so start will now point and end will decrement cash. start is pointing at L we check if L is present inside this wubble string no l is not present so we move start further so start is also pointing at L now start and N are both equal so this condition will fail we come out of the while loop and now we converting the character array into a string so character array now having these characters h o l e and I'm converting into a string so this will become o l e because we have to return a string as the output so this will be returned as the output and that is the expected output so the time complexity of this approach is of n where n is the length of the input string as the space complexity is over one because we're not using any extra space to solve this question that's it guys thank you for watching and I'll see you in the next video
|
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
|
74 |
Hello Hi Everyone, This Time Had Solved Problems In To-Do List To Play List Problems In To-Do List To Play List Problems In To-Do List To Play List Problem Please Give Every Spirit The Last Five Strict Sure Properties Also Apni Total Roop Africa Garhwali 110 And Neetu Se Possible Price Adhesion Problem In Such A Condition She Bigg Boss Ko Security Was Last Updated On That I Will Help From 2030 Hotspot 2030 Spot 13238 Water Will Be Selected Value In Various Crops Like You Are In Interview You Can Get Rid Of Problems In Interview Reddy Labs Not Tree To Avoid The Virus From Hearing From You were a text message approach but Buddheshwar such a win suggestion unit revenue oil against post Recent Posts By Others on Death Row Ro Last Ko Long Post Roop You All The Problem Of Property Everything Will Be Oak Everything Is Exist 2825 Screen 27.27 Is Exist 2825 Screen 27.27 Is Exist 2825 Screen 27.27 Last Point 43.23 Movie Download2017 Last Point 43.23 Movie Download2017 Last Point 43.23 Movie Download2017 Main Parties Left Want You Relation 63.23 Left Right Left 154 Relation 63.23 Left Right Left 154 Relation 63.23 Left Right Left 154 Select It And You Will Observe This Point To point out element subscribe last go left straight from number Fifty Shades Divine Kauthig Target Garlic Amazon doing great work number subscribe approach for this problem is property distance of button 1000 will always be greater than they can right all elements in three 500 Over 600 amazing elements to immerse yourself in your thoughts To find my tom cat but the only problems I'm putting all these elements into a temporary are of science class Seventh basis of using extra space Tweet Figure out how we can do this without using any sacrifice June 2012 Calls Painful Which Unit Of But From Zero 211 The Basically 102 So And Drop Sam - That Bigg Basically 102 So And Drop Sam - That Bigg Basically 102 So And Drop Sam - That Bigg Boss That's The Last Index Of The Executive Vice President Create A Temporary Tattoo Now Search Using ID Use 2004 Rule Numbers To Find The Amazing Divide divide that once it is number two get s one and five model ut kids one plants 5121 earn one will have to leave one is 1121 mobile recharges eleventh divine tigri find it I answer will have lived in Africa and the middle of the night When Lord Will Come To Know Your Mind And Want To Give Basically 2018 23.28 Hai Basically 2018 23.28 Hai Basically 2018 23.28 Hai 201 More Than 120 Target Thirty Time Answer Will Never Live Only Then Can Live Only White Election Lipika 920 Correspondent 2x Arun Induction Column In Next To status ko laptop 999 9999 imaginary index so you get its corresponding role number one column work in three four to 9 lutyens act-2012 and 130 three four to 9 lutyens act-2012 and 130 three four to 9 lutyens act-2012 and 130 rates equal to our will get you can be present at 2nd number one total number of elements and finally bigg boss time and space you all subscribe your baby able to find any target half valuable phone numbers call numbers for research and training - last imaginary basically to and training - last imaginary basically to and training - last imaginary basically to avoid intake mid-day-meal subscribe must subscribe to your elements mountain dew to adversaries Sunny C Plus Co Demand Recent Years For Males Vikas Element Karne And 1520 Matrix Half Computer Science Of Hero And Scientific Volume Slow Tiffin Soch Lo 10 - 121 Do Gold And Eggs And Tagged With His Life In Point - 205 Enable To Find Element In Point - 205 Enable To Find Element In Point - 205 Enable To Find Element And Understand To All The Best Please Page Like This Video And Do Not Forget To Subscribe Telegram Group One To The Telegraph And Instagram All Will Be Id This Video Subscribe
|
Search a 2D Matrix
|
search-a-2d-matrix
|
You are given an `m x n` integer matrix `matrix` with the following two properties:
* Each row is sorted in non-decreasing order.
* The first integer of each row is greater than the last integer of the previous row.
Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_.
You must write a solution in `O(log(m * n))` time complexity.
**Example 1:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-104 <= matrix[i][j], target <= 104`
| null |
Array,Binary Search,Matrix
|
Medium
|
240
|
236 |
So same gas, new day and new question, today we have question number 54 because our day 54 is the lowest common and sister of a binary tree, so yesterday we had seen the binary search tree, so I would request you first of all to see BST once. What is luck, okay you will understand it well, it was an easy question, if you have not seen it then go ahead, so actually in this question, we want to say that this time we have a binary tree, not a binary search tree. I must have told you that if there is BST then the question becomes very easy because we know that look at this example van, there is no left and right side in it, there will always be smaller routes on the left, there will always be worse routes on the right. Meaning, everything that happens in BST will not be there. Look, zero is here, six is here, Look, zero is here, six is here, Look, zero is here, six is here, anything is happening in it, in this case we have to find LCM, then how will we do it, once we understand it in the copy, then we will come. Here is the code, LCM has to be calculated in this also but the problem here or the different thing is that this is not a binary search tree i.e. here it is not like that i.e. here it is not like that i.e. here it is not like that you will see small ones on the left side and small ones on the right side, it is not like that see five. Six zero anything is visible now how to find your lowest okay who doesn't know lowest communication I would request you to check out the easy problem number 53 which I told you yesterday is okay so tell me one thing here. If you will understand, then I am not like that. Which is the five year old year? Here will return the value. Okay I mean, who is bigger than him, I mean who is his ancestor, so this poor guy is small, I mean If this is a child, then if father gives it, we can also take the self among these two. If he turns out to be the elder, then the answer has been punched, isn't it? Taking the self is allowed, I told you yesterday also and if P2 is there and Q7 is there, then these Which of the two will be bigger, you will be the elder, then one thing is that we are seeing some patterns, one thing is that we are understanding that what will we do, if we have given 3 5 1 6 2 7 4 0 8, this is given. We are okay, so if we have to hit check, how will we check that it is P5 from late, we went to the left side, check is this five, yes, okay, that means we have to check, if we got anything from P, then we got 5. So the return from here, if there is any value returned from here, if the value is present then it means that my second number is confirmed that you will get the purity, you will get it in the tree, okay, why will you get the completeness in the binary tree, so one if I have got five from here, so whatever van is there, it will be found either here or here, will you get it at one of these two places, now let's see a little bit, see what my brain is telling me, what to reduce, punch, we have found one here. Either you will get it here or you will get it here. If you get one here then what will be the answer? Punch will be the answer. I understand the point. If it is found here then what will be the common sister of these two? The lowest one will become three. I will make it once. And let's see the next one, there is not much left, so you have the brains, if you get so much punch, then the return from here is 5. Okay, if a non-value is returned, 5. Okay, if a non-value is returned, 5. Okay, if a non-value is returned, then there is a problem, it is on the left side, I did not find a non-value here. I have not got any back pay, non-value here. I have not got any back pay, non-value here. I have not got any back pay, I have lost four gardens, so the ultimate return from here is 9, so if we get value return from one side and none from the other side, then it means the same value is the answer. So see, 5 answers are all. If you had checked on TV, you would have checked everything for free in the same manner. So, you are understanding that how it will be less. Sahu, for convenience, I have written the code first, what to do in this, if we do not have root, if not root. You return the Naan, as was happening in our case in the future too. Look at the side of the example van. If you go to v0, then in the future, such a situation will also arise or if we do not have the route, then also Naan will be returned. If this is the case, then make it non-return. If is the case, then make it non-return. If is the case, then make it non-return. If anything comes out of the root, I had explained this in the previous question also. If anything comes out of the root, then our ancestor will be the same. It is obvious, isn't it? So, it is obvious that like in the root, if only three comes out then our answer will be the same or if even one of the four comes out, then punch will be the answer, so what will we do now by calling the receiver? Here is luck A, I took root left for left and right and after finding the PK, it is fine on the left. If the right one is searched in the sub tree of the left one, then one thing can be understood if from left and right. Some or the other value is returning ok, meaning both the correct values are returning. For example, from meaning both the correct values are returning. For example, from meaning both the correct values are returning. For example, from here punch came P and K came A, so both are not returning Naan, it means they are returning something or the other, so if L & R i.e. If they have any value then L & R i.e. If they have any value then L & R i.e. If they have any value then return them as root, this means our common ancestor which is three has become okay, for example for six and two, then their comment and punch will be done, right? If there is nothing, take it, I have got 5 from here. As I had explained in the second example, from here, Nan was returned, which means any of these whose value is being returned will be the answer, so from here, the answer was 'five', like in 5 and 4, because here was 'five', like in 5 and 4, because here was 'five', like in 5 and 4, because here I have four. If the answer was not found, then punch was the only answer. This is confusing. Okay, so this was a small code and the time complexity will be of N because this is a binary tree, not a search tree. There were people in history and if for space then anyway. There is constant space, if you consider the recurse frame, then it will be off and on, so I will give its code in the description. I have already submitted it, so it is a very good submission. The code is accepted and its link can be found in the description. If you are new to the channel then hit subscribe my name is that maybe you are watching take it see you in the next video
|
Lowest Common Ancestor of a Binary Tree
|
lowest-common-ancestor-of-a-binary-tree
|
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.
**Example 2:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` will exist in the tree.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
235,1190,1354,1780,1790,1816,2217
|
70 |
hey hello there let's talk about today's lit coding challenge question climbing stairs it's a really classic problem and many people including me the introduction problem to dynamic programming so uh i think if you have cs background you probably already know how to solve this so i'm gonna be really brief on the explanation today uh imagine that we are climbing a staircase it takes n steps in total to reach to the top each time we can either climb one or two steps and this question is asking us how many distinct ways we can clamp up to the top so the top-down kind of to the top so the top-down kind of to the top so the top-down kind of approach is to take this question and try to make it a little bit more generic so instead of trying to solve this directly how many distinct ways we can climb back to the top we replace the ambiguity part the variable part the top by n's step or x step and then if we have a function that can solve this which is f x right uh then to solve this original question we'll just uh plug in plugging in as the input to the function and we can just return now the rest of the problem now is basically how to figure out how we write this function f x so to solve this we look back at the problem each time we can either clamp one or two steps uh so the number of ways we can climb up to uh the x step is determined by the number of ways we can climb up to n minus 1 x minus 1 and x minus 2. and it's actually the summation of those two so so that's the recursive relationship or the transition function for this problem uh so if you look at the formula it's nothing but the fibonacci uh sequence formula and there's just one more thing we need to figure out that the base case which is when the x value input to the function is a really small that we can manage to calculate uh by hand directly and we can just return that so it actually provided us with the base case f2 is 2 f3 3 f1 is obviously 1. so that's the base case so this will definitely work the problem is that it has a lot of duplication in calculation if we calculate f5 it's calling f4 and f3 and add those together within f4 is calling f f3 and f2 so you see that f3 is calculated multiple times and the deeper it goes the more duplicate it has so to avoid that we put a memorization in there here i'm just using a really lazy man's memorization uh yeah so that would be the top down approach with memorization so that's the top down to solve this from the bottom up it's basically starting with the base case f1 f2 and then you know generating f3 and use f2 and f3 generating f4 until that we have calculated fn that's the time that we return fm that's button up uh instead of from fn to look for fn minus one fm minus two we're doing from f1 and f2 and go all the way up to fn that's the button up approach so uh to reiterate the bottom from bottom up uh we have two values fn minus one and f of n minus two uh the initially f1 and f2 we just uh you know generating f3 and then we keep track of f2 and f3 and then we generate f4 after that we keep track of f3 and f4 until that we have fn calculated so i'm just going to call this slow and fast the original one and one or one and two i'm just going to run fix the number of iterations so actually i'm gonna go with uh slower and faster one and one um slow is f zero actually here f zero is one there's just one way you can stay at the bottom there you do nothing there's one way you can get to the first step so i'm just going to call you here so the slow and fast initially are f0 and f1 so i'm just going to update slow and fast altogether slow will become fast will become the summation of slow and fast and i actually i want to run this one steps uh one iteration less than the input x input ahead so that's the uh button up approach uh it's accepted as well so the benefits of bottom up is we can just keep two variables so the space requirements become constant compared to the top down it the recursive function calls triggers basically fn to f1 all the way back to f1 and it's caching all those intermediate results so it's a linear space for the bottom up it's constant space but both it's a linear time complexity i think there is a formula to calculating fibonacci series sequence numbers directly if you choose that then it's constant it might be constant time as well but that's generally out of the scope i think in calculus i learned that but how to derive that actually how to derive that i learned that but so many years of school i no longer remember that so yeah this so this is a really quick to talk about this classic questions if you find yourself struggling it's not really a big deal everybody gets stuck there when they start to learn dp but eventually people get better so that's the two approach um
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
678 |
okay that's off today silicon enchanted question validated professor string we have an impostor in with three type of characters open and closing purposes as well as asterisks we need to write a function to check the validity of the strings by their following rules a the first three things just telling us that we have to close all the opening parenthesis with these are closing parenthesis towards the right of that opening parenthesis so if we do linear scan we put our stack and just whatever we see opening parenthesis all that we just push it onto that stack when we see a closing professors will just try to pop open your professors if we don't have asterisks if we just do that one linear scale we will end up with empty stack that there will be idea that means that we did we have all matching pairs and the asterisk is the where the complexity for the problem comes in you have three different choices of translating this asterisk into either opening up close and purposes or even as a mystery so just looking at even cooler string if we were never at a location we can branch out into three different possibilities opening or closing or empty string before we want to consider all the possibilities of translating the input string into a string with only opening and closing professes and just check whether one of the realizations of that string is valid use not as a final result it will be three ^ and result it will be three ^ and result it will be three ^ and possibilities just imagine that we have a you know when we see a tree when we see a node here asterisk symbol here we branch out into three different possible branches and on even on every that branch on every node there we just keep scanning towards the right when we see a next asterisk we're gonna keep branching into a factor of three so in the end we have three to the end or possibilities that would be exponential and it's quite complexity for this simple question so we don't want to go that route so how we kind of effectively use this asterisk symbol it's gonna be the key to solve this question efficiently number five is that emitted string is also valid I guess this makes sense because every string just means we have a zero open and zero closing so they do merchant's the two number much each other so look at some examples we have example one being open and closing so we'll everyone it's so it's good the second example we have open purposes ask the risk and the closing symbol we treat this as an empty string it's fine the second of the third case is opening asterisk or than closing we use this asterisk as opening parenthesis so it's a match let's think about what's the case where there will be there the string would not be valid right determine whether the string is a valid its equivalent to exclude the possibility that the string is invalid so the Ambala string will be something like this just have a closing parenthesis you will not have any matching just don't have enough open purposes towards its left the second case possible case will be this so we just don't have enough opening purposes to close with so that's a violation as well so when we scanning through the skiing for us a string for a left or right there are two strategies we can two extremes that we can have we can use this asterisks we are still always traded as open parentheses so that case will be handling the you know we will be checking for cases whether we're gonna be have some kind of violation like this if we just treat all the prosthetics as open parentheses we still don't have enough - we still have more closed and enough - we still have more closed and enough - we still have more closed and professor symbol there then it's going to be violation conscious that cases otherwise we'll just try to use this asterisk symbol as close and simple whenever possible so that just the translate is equal to we closing the bare minimum number of opening parentheses if we can do that then and we have a valid result about a string because when you have a valid in frustration don't value the string like the case here we can just randomly in just some asterisk symbol in there the easy way of handling the extras is just treat them as a mature strings so as long as we can close the minimum number of us opening purposes and we don't come into the situation where we just have far more closing purposes to them but we can use us opening parentheses to you know match them on the left hand side then we are good so anything in between we just have a lot of flexible ways of dealing with that either use the asterisk as empty string it's the simplest case or just randomly we translate them into much in pairs and in the right locations day we're still fine so yeah the Australia is gonna be greedy with but we're just gonna try to do a linear scan and to consider the two extremes if we don't see violations of this case this kind and we can close enough the bare minimum number of opening parentheses then if then it means that any casing between us is fine so let's fill this up so this two variables gonna be keep tracking of the current maximum number of opening parentheses at the you know the current timestamp that we are scanning through the string this is the minimum one says the case where we don't treat any asterisk as opening purposes we try to use the asterisk as closing symbol as whenever possible so we've mentioned a for loop we're gonna have test we're gonna branching out based on their of the character we encounter if it's open purposes it's quite simple we have to increment pose because in two extremes physical open purposes it's something we always have to close in post cases let's talk about let's handle the this case oh I guess we will put the violation here as well the code to handle violation as well so if the maximun open yeah let's do this before we check for this condition obviously one thing we need to do is to do this maxim and open document that because every physical closing purposes we're going to close the closed one of the current open one so the violation check for this case or in this case it's going to be less than zero if that's the case we just return for without even go further down into the string I guess the tricky part is how we're gonna handle this being open here it's gonna be maximum of boolean open minus one which is we actually close one or a zero they're all here it just means that we're going to treat one of the previous existing previous asterisk as obvious space we won't need to check for whether minimum open is less than zero it will never happen before in this case because we only worry about whether the Maxima open that's it will cause this case for this case as long as we have this check here we can safely just set it to the maximum between minus one or decrement one or zero the remains that we treat one of the prior asterisk as empty space yeah the third cases we have asterisks and for the max open in case it's a simple whenever possible we treated us open purposes for the closest symbol for the minimal open it's the same as if it's a closing symbol so yeah so this two extreme is we will do some consolidation of the logics here so that this leaves to some consolidation you know we see that this is the same for both the opening and the asterisk case and this is the same for the closing and asterisk same case so maybe we do some consolidation and the logic and may become even clearer I guess in the end we should check whether we can close all the minimum open because it's going to be decrement or zero so as long as this can be 0 it will means that we actually closed all the bare minimum openings and also there is no violation of this so all the asterisks extra asterisk in between we can just treat them as empty space so that's pretty much the code let's see if it works yeah it's okay so let's actually consolidate this logic here this gives us this case only so yeah the logic is not too extreme right the we're gonna use the asterisk as open professors whenever possible so when it's asterisk or open we just stack or we just increment the number of opening parenthesis we need to close otherwise would be this single case when it's our closing parenthesis would definitely want to decrement this and the for the other extreme is that we try to use the asterisk as closing symbol as soon as long as it's possible so the opposite for that is physical opening purpose that's just something we have to increment this otherwise will be a maximum between these two with the decrement be that we actually close one physical hanging opening parenthesis setting it directly to zero means that it's already zero so resetting it to zero is equivalent to we find a prior asterisk and treated as empty space so that's a little bit cleaner in the cold there they should be equivalent yeah let's see if it works No what's the problem okay this time you should work I think yeah okay that's the question so it's a good algorithm just consider two extreme approaches of handling the asterisk this is a little bit hard to reasoning but it's just basically if we just make it unchanged to be reset to zero when it's potentially go to negative it's just means that we find a prior asterisk and treat that as empty space so yeah so that's pretty much it's a linear time algorithm with constant space
|
Valid Parenthesis String
|
valid-parenthesis-string
|
Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_.
The following rules define a **valid** string:
* Any left parenthesis `'('` must have a corresponding right parenthesis `')'`.
* Any right parenthesis `')'` must have a corresponding left parenthesis `'('`.
* Left parenthesis `'('` must go before the corresponding right parenthesis `')'`.
* `'*'` could be treated as a single right parenthesis `')'` or a single left parenthesis `'('` or an empty string `" "`.
**Example 1:**
**Input:** s = "()"
**Output:** true
**Example 2:**
**Input:** s = "(\*)"
**Output:** true
**Example 3:**
**Input:** s = "(\*))"
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is `'('`, `')'` or `'*'`.
| null |
String,Dynamic Programming,Stack,Greedy
|
Medium
|
763,2221
|
454 |
welcome guys so uh welcome to my lego section so in this video we try to solve basically is this for some number two so give you a b c d and uh you need to calculate how many tuples uh in a and b and c and d sum is zero sum zero okay so for example uh this one you have you will have two then just take a zero and one element or the one zero element okay so now if i use the loop then i will use a for loop four different for loops okay so i will take under first okay so but in this case that we can use hash table to collect the first the uh to collect information of the first list so we're going to say that uh for i a for chain b then i calculate a number and then and i the number is not in at least online hash table and we just in we just insert uh else if it already happened then we just passed our mind uh we just add one so basically uh this just counts how many uh so you just count really i just create a dictionary and the key is just the sum uh the different pair uh the different possibilities of i plus c and then value just how many numbers uh how many solutions and then in this case that we do the same thing but uh we first initialize s and for in c for j and d then we calculate this t so if t in h means that i plus the plus this number is zero then we just plus the how many numbers in it so but and then we do a chinese s and every time is s okay and as you'll see that let me see as you see the results looks uh not uh very good uh not very not super faster but it's still okay yeah i think this is okay and then i will see you guys in the next video and be sure to subscribe to my channel
|
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
|
33 |
welcome to lee coats blind created 75 where i'll be solving the top 75 lead code questions this problems search in rotated sorted array suppose an array sorted in ascending order is rotated at some pivot point say we're given a list like this zero one two four five six seven and it can be rotated in this format four five six seven zero one two so it's still sorted sort of but it's spliced at a certain pivot point we're given a target value to search and if that array is found we turn its index its actual index or otherwise return minus one okay so here's our approach why don't we do a binary search and first find that pivot point here in this example the pivot point is going to be what four right it zero one two three four no it's four because that's the point where the actual sortedness of the array exists once we find that pivot point we can just do a regular binary search and return the actual index so let's first initialize some variables get the length of nums as well as the left and right pointer now while l is less than r we're going to check first submit first calculate the midpoint and say l plus r divide by two if the nums midpoint is greater than nums to the right that means that this pivot point must exist on the right side so if that's the case we'll just make left equal to mid plus one otherwise we'll move our right pointer equal to mid and the reason we do it like this is at a certain point it's going to point to these two pointers and we want the left pointer to move to the right because we want the index number right where the pivot point starts so now that both the left and right pointer is going to be pointing to the pivot point we can just initialize the pivot just to make it a little easier here and now we'll do a regular binary search so while l is less than or equal to r we'll say first calculator midpoint and here's the thing we need to calculate the real midpoint using our pivot so all that is just to add the pivot number and we need to do a modular by the length of the array and that's going to give us the actual number that we're pointing at even though this binary search pretends like this is just a regular sorted array so if nums.mid 2 if that equals the target if nums.mid 2 if that equals the target if nums.mid 2 if that equals the target then return mid 2 which is the actual index otherwise if nums mid 2 if it's what less than the target what do we want if this point is less than the target then we know we need to move to the right side right so we want to change the left pointer equal to mid plus one otherwise make r equal to mid minus one and if it's able to break this loop then we can just return to minus one so let's run on the test case and see if i got this right and it does get accepted for the test case let's submit that and there we go so yeah it's basically two binary searches going on and it's just discovering that pivot the majority of this code is where you need to find that pivot point and once you do that it becomes pretty easy to do a regular binary search thank you
|
Search in Rotated Sorted Array
|
search-in-rotated-sorted-array
|
There is an integer array `nums` sorted in ascending order (with **distinct** values).
Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`.
Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 0
**Output:** 4
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 3
**Output:** -1
**Example 3:**
**Input:** nums = \[1\], target = 0
**Output:** -1
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* All values of `nums` are **unique**.
* `nums` is an ascending array that is possibly rotated.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Medium
|
81,153,2273
|
226 |
hello hi everyone welcome back to the channel so this is your randip Singh I'm back with yet another lead code problem after so long pause because I was busy in some interviews and in some not so important work but we'll be consistent from this video onwards so let's read the problem statement the problem name is invert binary tree so we given the root of a binary tree we need to invert the tree and after we invert the tree we return the root of this tree so inverting a so let's first understand the binary tree a binary tree is a special type of tree where for each node we have at most two child nodes and inverting a binary tree means for each node switch its left child with the right child and hence switching the left sub tree with the right sub tree like here in the this example we have this node this tree rooted at node four after we have inverted the tree the left child that was two becomes Its Right child and the right child that was seven becomes its left child and this is true for all the nodes we can see that for node number two we had 1 3 and now we have 3 1 for node number s we had 69 and now we have 96 so we have to make this inversion for each node of the tree and finally when we have made it we'll return the root of the tree right so let's see how we can solve this problem but first let's understand the problem statement better because understanding the problem statement in a better way will do our life will make our life a lot easier so you know like understanding a problem statement gives the intuition to solve the problem so here we have this tree four rooted at this node four so let's start from the very simple statement we need to invert the tree means switching the left child with the right child so let's say switching the left child with the right child is simple just swap the left pointer with the right pointer it's a constant time operation so it will give me 4 7 2 fine a constant time operation 6 9 then for two we'll have 1 3 so we have made the swap but this is not the final form we can see that we also have to make the switches for each node for the child nodes as well like here we can see that for seven we had 69 and now we have 9 six in the final form that means we also have to switch these nodes as well or these sub trees as well so let's make it four 7 then two then for seven we'll have N9 then we'll have six then for two we'll have three then we'll have six it's not six it's one I think yeah for three for two we have 31 now not 31 we had 1 3 now we can see that we have made the switch for node number four and here we made the switch for node number seven but we also have to make this make the switch for node number two as well we have to invert the sub tree of the node number two as well so let's do it four 7 we'll have 9 then six then we'll have two then we'll have three it's not three yeah it's three and then we'll have one fine so is it the final form 472 9631 yes 472 9631 so that's what we have to do one step two step three step can we do the same for these Leaf notes as well no because we can see that these are the leaf nodes and they do not have child nodes we can't switch anything for them right so swapping the left and right pointer is a constant time operation but doing it for all the nodes is not so what we have to do is we have to start from the root node make the switch for the for its gin nodes then repeat the procedure for the left and right sub so let's create a function which do this job let's call the function to be invert which takes in a node right it makes the switches or the swap the left pointer with the right pointer so let's say left then it with right so we have made the swaps switch the left pointer with the right pointer then we have to do the same for the right sub tree and for the left sub tree so for the left sub tree we'll call the function invert pass this root for the left sub tree that is left call the same function for the right subtree pass the same pass the root of the right sub tree that is right and this will do the job so we perform swap for this node then for this node and so on so from four we move to seven then from Seven we actually move to six we have skipped few steps in this procedure why we'll see why so from four we move to seven then from Seven we'll move to six because that's what this function say from any node move to its left child right so from four move to its left child that is seven then from Seven move to its left child that is six but we can see that for six we do not have any left child so we have to return from there so when I call this invert function for the left child of node number six I encounter a null pointer means this node is null since this node is null we can't switch its Childs because this node do not have any child at the very first place and in that case what we'll do so if this node is null then we'll simply return back to the parent right and that will be the casee for the left and right child of the leaf nodes when we'll call the invert function for the left and right child of nodes like this 69 1 and three will end up with this base case right and this is my base case and that was my recurence relationship fine so this will do our job this function is going to perform the inversion which I want so I hope it was really easy thing all we had to do is swap the left pointer with the right pointer like I did here swap it then do the same for the left child do the same for the right child that's all this was a high level view if you just think about a high level view not going to the nity of the how the recursion is working you have to take care of two things a recurrence relationship and the base case just think about you simply swap the left and right child nodes then do the same for the left child do the same for the right child and whenever we encounter a node which is null we simply return from there fine that's all not going to the very details of the how recursion Works although it is easy to understand how it is actually working we start from node number four we make the switches the tree structure is like this and now we recursively call the same function for this node and then the tree structure is like this these nodes are swept then we call the same function for node number nine and we can see that for node number nine we do not find any left and right childes fine so because they are null nodes then we call invert function for the left and right side of this node where we are passing null pointers for them and when we are passing null pointers we end up with this base case and we return right from there so from here I return to node number seven and then I'll call the same function for node number six and the procedure repeats for node number six we end up with the base cases now I move back to this node number seven now I have explored all the nodes of this sub tree rooted at node number seven and now I move back to node number four that means I am at this point now from here I recursively call the invert function for the right sub tree that is this node fine so from this node I recursively call the function for the left node which is six then I can see that it do not have any left and right child so I end up again with the base case and from this node I move back to node number two from node number two I recursively we call the invert function for the right child and this and I again encounter with the base case because this node has null nodes it do not have any actual child nodes so from this node I move back to the parent node that is node number two and also I make the switches so first when I'm encountering with node number two I actually switch these nodes switch node number three with node number one fine so I end up with this type of configuration then I move back to node number four and I finally get this tree right so this is a top down way to solve this problem that is first swap the child nodes now move to the child noes actually recursively call the same function for the child noes like here first swap them then move to them okay we can also do it in a top in a bottom up approach that is first recursively keep moving down then first recursively keep moving down and while moving back to the parent nodes make the switches in that case all we'll do is simply write this swap function after these recursive calls that is a second way to tackle the problem although that is also a recursive way but just a way of solving a problem a way of approaching a problem and this swap is a constant time operation right it just swaps the left pointer with the right pointer so let's just jump to the code implementation part so let's write this function invert which basically inverts the left and right nodes left and right Childs if the node is null we return right from there otherwise let's perform the swap that is a constant time operation so let's create a temporary variable and store one of the Childs in this temporary variable and into that child which we have stored into the temporary variable assign another child and to the another child assign the initial child which I stored in the temporary variable so we know how we do this and then recursively call this invert function for the left node and for the right node right and here in this invert tree function call this invert function and then return the root right at the end of it let's run this code and it is giving me wrong answer because I think I forgot to write something if node is null if it is some problem return okay I had to write right here okay so that got accepted I hope you enjoyed this video and if you like it then hit the like button uh and stay tuned with me I'll be coming up with new playlists and soon in my next video till then take care bye-bye
|
Invert Binary Tree
|
invert-binary-tree
|
Given the `root` of a binary tree, invert the tree, and return _its root_.
**Example 1:**
**Input:** root = \[4,2,7,1,3,6,9\]
**Output:** \[4,7,2,9,6,3,1\]
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,3,1\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
877 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem stone game and honestly this is a very interesting problem in fact it's so interesting that there's around 10 problems 10 variations of the stone game problem on leak code and believe it or not we can skip directly to the coding section where we can go ahead and just return true run the code and you can see it beats 97 so if that's all you are looking for if you just want to pass this problem on leak code there's your solution but in seriousness let's go back to the drawing board and understand this problem because obviously in a real interview they'll probably know that you just memorized that line of code if you even do get this exact problem but obviously you could get a variation of this problem there's many variations so let's understand it so we have two people uh alice and bob a and b two people and we're given a pile of stones the pile of stones is given in an array so for example this could be one pile the length of it is always going to be even which is very important and every stone each stone is basically a value in this array each stone is going to have a positive value associated with it another thing the total sum of all the values in this array are going to be odd and that's also going to be important because what the problem is about is alice and bob are going to be taking turns uh you know choosing a stone from this array the restriction here is that alice is going to go first and bob is gonna go second and each of them can only choose from the beginning uh or the end of the array right from the beginning or the end of the array so if alice takes five then you know this is our array remaining and then either bob can take uh the three or bob can take the five and we really wanna know who can get the highest score so the question we're asked is uh alice and bob both play optimally return true if alice wins the game or false if bob wins the game now from what i showed you a second ago we know that alice is always going to win the game and we happen to have a big oaf one time solution that can solve this problem so do we really need to do more well at the very least you probably need to understand why the of one solution works because you'll probably be asked that in an interview if you do use that solution first of all since we know that the number of stones is even right the length of piles is even that means both alice and bob are going to get an even amount of stones and we know that the total of this array is odd right the sum of this array is odd so at least one of them has to win right if you take half of the array and just split it randomly how one half is going to be bigger than another half no matter what right one of the halves has to be bigger because the sum of it is odd so we know that alice goes first and because of that she's always going to win the game and that's pretty obvious if you have an even length array of just two elements right because in this case there's just two elements of course alice is gonna be greedy and pick the bigger one so she's gonna get four bob is gonna be left with what's remaining which in this case is three so alice is gonna win in uh pretty much every time in that case so then you might think well is alice always gonna play greedy because right now alice has given this array of four elements alice has two choices she can pick the five or the six now if she picks the six then her total is going to be six and then bob has you know this array of three bob can either pick five or a hundred of course bob is gonna pick a hundred and you know by default there's two elements left bob has a hundred already so bob wins so in this case being greedy for alice doesn't work so alice can pick five first and then of course bob is gonna pick six and then alice can choose the hundred right so being greedy doesn't always work the question is why is it though that alice can win every single time well remember we were told that both alice and bob play optimally so we don't know what optimally is being greedy does not mean optimal and how many different choices does alice actually have like how many different you know combinations could there be of alice choosing stones well alice has two choices each time right and the length of the array is let's say n so really the time complexity is going to be 2 to the power of n that's how many possible ways alice could choose stones pretty much and so among these we're just asked at least one of these ways whichever way happens to be optimal for alice to play at least one of these ways alice has to win right regardless of what bob does if alice chooses the stones optimally then alice has to win at least one way and that's guaranteed to be true but why is it true well we're gonna extend that idea of two elements right if we have two elements it's simple that alice is gonna win alice is gonna pick the bigger number and then she's guaranteed to win well that idea does work in four elements as well think of it this way if alice picks six first right she has two choices five or six if she picks six first then she can guaranteed pick this element as well this one element as well why is that because bob is gonna have two choices bob can either pick the five or the one hundred so if bob picks the five then this element will be available for alice to pick if bob picks the hundred then this element will also be available for alice to pick but in this case one plus six is not the solution right seven does not mean alice wins right that's not enough but remember alice chose six initially alice could also choose five as the first element so if alice chose five as the first element then bob could either pick one or six but then alice is guaranteed to be able to choose this if she wants to she doesn't have to but she can because it will be available for her basically we saw that alice has a guaranteed way of getting five and a hundred if she wants to and then this would be the total that she could get if she does that she also has a way of getting six and one if she wants to a guaranteed way of doing that and then this would be the total we don't know for sure which one of these like combinations that alice could pick is going to be the one that gives a greater total until we actually run the calculation like i just did we don't know which one is going to be the solution but we know at least one of these has to be greater than the other in this case we see 5 plus 100 is greater than the other we know this because the total sum of this is going to be odd both of these cannot be equal right one of them has to be greater than the other and using this idea we can kind of formally this isn't like a formal proof but it really gives you the intuition of exactly why alice can always win let's extend this idea that i showed you to a more generic sized array so let's say we had a generic sized array this is index zero this is index one two three etc until n right and we know n is going to be an odd n an odd index number because we know we're always gonna have an even number of elements right we're starting at zero so this has to end in an odd number basically what i'm about to show you is that if alice wants to she can guarantee herself to be able to pick every single even number in this entire array if she wants to she also has a guaranteed way of picking every single odd number in the entire array she can pick every even number or every odd number if she wants to and we know for sure that the sum of even is not going to be equal to the sum of the odd elements right we know that for sure it cannot be that the that one half of the array is equal to the sum of another half of the array because the total sum of the array is going to be odd so if she has a guaranteed way of picking even or odd elements if she wants to then whichever one of these happens to be greater alice can play in such a way that she picks the one that happens to be greater so that's the idea and how exactly can alice pick every odd element or every even element you might be wondering well that's the simple part actually if she picks right now we see that the left index is zero that's an even number the right index is n which we know is initially going to be an odd number so if alice let's say picks the zero then the choices for bob are either an odd number here or an odd number here right so if bob picked the odd number here then alice could pick the even number here or if bob picked the odd number here then alice could pick the even number here so basically since alice is the person that has the first choice alice can control how the game is played alice can make it so that she gets all of the even ones or she can get all of the odd values as well if she wants to and so that basically proves that alice since she goes first and if she plays optimally she's gonna win every single game so i hope you enjoyed that o of one solution for this problem it's very rare that we have a constant time solution so that's what's really interesting about this problem i really like this problem but there's another solution for this problem what if they changed the problem slightly and what if they said that the total sum of the input array is not necessarily going to be odd it could actually be even in that case is it always going to be true that alice wins every single game no it's not going to be necessarily the case because it could be that one half of the array is equal to another half of the array so even if alice picks every odd element or every even element it could be the same value as what bob picks so they're equal that means alice isn't going to win every single game so if you got this as a follow-up question or if you just want follow-up question or if you just want follow-up question or if you just want to know a different way of solving this problem let's try to understand the dynamic programming solution of this problem so first of all let's start with what we actually started with when we first talked about this problem the brute force right we know that how many different combinations could alice actually pick from these piles well she has two choices each time right and the length of the array is n so the brute force is there's two to the power of n different ways for alice to pick uh stones right what would that decision tree of her choices actually look like well initially so of course she could pick the element at index zero or she could pick the element at index three each of these choices would give her a total of five and six respectively right what we care about what alice's total is that's what we're going to be keeping track of we know that bob's total is just going to be the total of the array minus alice's total so we could calculate that easily if we wanted to but we care about maximizing alice's so that's what we're going to be keeping track of as the total value so what makes this a little bit difficult is we don't only care about alice's choices we also care about bob's choices and bob is technically also going to play optimally but that's not really a main factor for us so of course if alice picked 0 then bob's choices are either 1 or 3 or if about if alice picked three uh bob's choices are either zero or two in both cases though the total is going to stay the same for alice right alice is still gonna have a total of five in this case and alice is still going to have a total of six down this path and i hope you i hope this gives you a general idea of the brute force solution we'll continue on just one of the paths for this tree because i don't want to spend too much time on it but you can probably see why this is 2 to the power of n the height of the tree is going to be n and each node we have two choices so that's kind of where we get to the power of n from let's finish up the tree and then understand how we can apply dp dynamic programming to this problem to actually get the time complexity to be down to n squared rather than 2 to the power of n and the way i'm going to be implementing this is actually by using recursive caching dynamic programming with caching rather than a true dynamic programming solution just because it's a little bit easier to understand but going down this path we know that if alice picked zero and then bob picked one alice can either pick two uh index two or index three of course we wanna go down this index because that gives us a total of a hundred and five of course bob doesn't even have a choice anymore uh because we already picked zero one two so the only remaining element is three so in that case our total is going to be a hundred and five that's for alice right alice is going to have 105. so how do we know if this amount is enough for alice to win well we could compare it we could check is alice's amount greater than bob's amount right so that's how we could implement this uh recursively and this solution is easy to optimize with dynamic programming basically you want to find a way to eliminate repeated work the main way so initially we start out with an array that we can pick any elements from right but if alice picks this element then we have a subarray right we want to know can alice still win the game with this sub array right what's the max amount that alice can get from this sub array so the way we can cache is by using two values a left and right index for the array right this will be our sub problem but i think the way that we're going to be caching this will be easier to understand when we actually go into the code so let's go ahead and do that now the time complexity will be n squared because how many different combinations of left and right indexes can we get from this input array well there's n possible values we could have for the left index and n possible values we could have for the right index so n times n is n squared that's how we're getting n squared for the time complexity of this problem so without further ado let's jump into the code okay now let's get into a more heavy solution than just returning true for this problem but like i said we're going to be caching to speed up this problem so we're going to initially start out with the brute force and then apply caching to it uh the way we're going to be caching is we want to basically for a particular subarray of piles and we're going to determine a sub array by taking the left and right index of the array to determine the sub array and for that sub array we want to know okay what's the max alice total we can get if she plays optimally right so if we can you know do this then we can efficiently solve this problem but now let's get into the actual recursive part of this problem the brute force and then apply caching to it so there's two parameters we're going to pass in the left and right index because that kind of determines what elements are remaining for the array right what elements can alice actually choose from and i you can see that i have a function defined inside of a function that's just so that we don't have to pass every variable like piles and dp into this function every time we call it that's just my preference but you can do it differently if you would like so now we're doing this recursively what's a base case well the first one is if we have no more elements to choose from right like what if we have gone through every single element in the array how will we know if we have done that well if our left index passes our right index right if our left index becomes greater than our right index which normally shouldn't happen until we have reached every single element in the array if that does happen then we can return 0 if there's no elements to choose from what's the max amount that alice can get of course it's going to be 0. and by the way that's what our dfs function is going to be returning the max alice total from this array right you can see that the what this function is returning is the same as what this uh cache this hash map up above that we've defined it's going to be storing the same value right the max alice total uh which is you know why we're using this to cache the result of this function so that we don't end up calling the function with the same parameters twice right and that's going to actually be our other base case if this left right pair of values has already been called or if it's already stored in our dp hash map then we can go ahead and return that value we don't have to recompute that work so that's what we're going to be doing here it's already if this left right pair has already been computed and stored in dp then we can immediately return it that's what we're doing here otherwise we have to do the recursive part so if alice is making a choice alice can pick the left element or the right element so if alice picks the left element then what are we gonna be calling uh recursively well if alice picks the left element then we're gonna set left to l plus one and leave right the same because then we're saying that okay these are this is the remaining subarray right for bob to choose from if alice picked the opposite case if alice picked the right uh value the right pile then left would stay the same but we'd take right and then subtract one from it right because that element is no longer available so we're decrementing our right pointer so these are the two choices that alice can make and we want to know which of these two choices is gonna maximize the amount that alice can actually get but don't forget about one thing this function is about returning what the maximum alice can get but we actually have to make bob decisions as well right bob has choices that he can make as well and how do we know if alice is the one choosing or if bob is the one choosing well it's basically about how many elements are remaining if we have an even number of elements remaining that means alice is the one making the choice if we have an odd number right like basically if alice picked one of the elements then we hadn't have an odd number remaining so then bob is the one making the choice so let's just uh basically determine if the length is even or odd so we can do that like this just by taking right minus left and then mod it by two this is just a ternary operator just determining if we have an even or odd number of elements and then we can use the result of this to basically clean up the code a little bit this so basically here we wanna know okay if alice picked the left amount how much is it going to contribute so piles index left the reason i'm doing this is because we know that bob's choices aren't going to contribute to the result of this function only alice's are so if alice picked left which alice can only do if the length uh is even right if it's even then a left is going to be assigned to piles of left if it's non-even else is the is that if it's non-even else is the is that if it's non-even else is the is that case then this is going to be assigned to 0 because that means bob is the one making a choice this probably is going to look a little bit confusing until we actually finish the function so you can take your time and understanding this so we're just copy pasting this so same thing left and right these are the choices and so using these values left and right we can actually finish up this function so if the person made a left choice uh this is the function for that plus left and this if they made a right choice is this plus right so remember we want to return the maximum of these so we can do that by just taking the maximum of these two and once we take the maximum of those we're going to go ahead and put it in our cache and then return that value right so left right is our key for our cash and then we can store the maximum inside of it and then we can go ahead and return dp at this so i know this probably looks a little bit confusing but just so you know what we're mainly doing here with the left and right is about the return value here right we want to return what's the max total that alice can get so every time alice is the one making a choice we want to add that to the return value but every time bob makes a choice we want what bob picks to be zero because we don't want bob's choices to contribute to the return value so even is basically when alice is making a choice if it's odd that means bob is the one making a choice so when it's bob left and right are going to be zero so then here in this computation you can see that left and right are zero so they're not contributing to the result but if alice is the one making a choice then left is the value of the stone she picked and right is the value of the stone she picked and then these recursive functions are the amount that alice is going to get from the remaining stones and of course she has two choices right left and right we want to take the maximum of these and then return that because we want to know what max value alice could actually get so that's kind of the logic of this problem last thing we have to do is just call dfs uh starting from the beginning of the array and from the end of the arrow which is the length of piles minus one so then we can return that value and that's the entire logic of the code let's run it to make sure that it works and as you can see it does work it's pretty efficient for a dynamic programming solution but you can see it's definitely not as efficient as our just simple solution where we just return true so yeah you can see that the return true solution is definitely a lot faster but i really hope that you learned something from this problem because it's a very interesting problem i hope this video 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 and hopefully i'll see you pretty soon thanks for watching
|
Stone Game
|
shortest-path-visiting-all-nodes
|
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`.
The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties.
Alice and Bob take turns, with **Alice starting first**. Each turn, a player takes the entire pile of stones either from the **beginning** or from the **end** of the row. This continues until there are no more piles left, at which point the person with the **most stones wins**.
Assuming Alice and Bob play optimally, return `true` _if Alice wins the game, or_ `false` _if Bob wins_.
**Example 1:**
**Input:** piles = \[5,3,4,5\]
**Output:** true
**Explanation:**
Alice starts first, and can only take the first 5 or the last 5.
Say she takes the first 5, so that the row becomes \[3, 4, 5\].
If Bob takes 3, then the board is \[4, 5\], and Alice takes 5 to win with 10 points.
If Bob takes the last 5, then the board is \[3, 4\], and Alice takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
**Example 2:**
**Input:** piles = \[3,7,2,3\]
**Output:** true
**Constraints:**
* `2 <= piles.length <= 500`
* `piles.length` is **even**.
* `1 <= piles[i] <= 500`
* `sum(piles[i])` is **odd**.
| null |
Dynamic Programming,Bit Manipulation,Breadth-First Search,Graph,Bitmask
|
Hard
| null |
1,499 |
q for max valuable equation so this became a mano q max Q algorithm I have a link below to my explanation of how to sell my new cube bombs but the tricky part and it is not easy is recognizing that so one is that the X are sorted so I actually try to sort first but it's not necessary because it's already sorted but you kind of go from left to right you're trying what this looks like is that given though it human this formulas like this I think that's the part that I struggled with a little bit when I was looking at it so you have this formula but actually since J is since I is less than J and we were told that X sub I is s the necks of J you can actually rewrite this as X of J plus XR x j- x o5 right and now from that point x j- x o5 right and now from that point x j- x o5 right and now from that point you can separate it out to X sub i's and except sorry yeah you could separate out two J's so that looks like this plus this right yeah and you know so here so now you have this element as you go from left to right using a mono Q or monotonic T or a max Q right so now you're given this number and a max Q all you have to do is take the max element and then add it to the current element and when you put on the Q just put this sum back in and that's how you did it do it the implementation may be a little bit tricky again check out my monotube video I didn't even solve it that way I did it I did the model Q but I did it with a heap because I wasn't quite sure why we're solving it there are a couple of ways to do it I was described this way of solving it on that mono Q video so check it out but yeah but now that you know you've written it this way this is the thing that you're trying to get the max and you know as soon as X sub J minus X sub I is greater than K do you remove it from the mono queue and that's how you solve q4 pretty straightforward once you do this for my manipulation I took me live long because I didn't make the connection but yeah
|
Max Value of Equation
|
maximum-performance-of-a-team
|
You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`.
It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`.
**Example 1:**
**Input:** points = \[\[1,3\],\[2,0\],\[5,10\],\[6,-10\]\], k = 1
**Output:** 4
**Explanation:** The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
**Example 2:**
**Input:** points = \[\[0,0\],\[3,0\],\[9,2\]\], k = 3
**Output:** 3
**Explanation:** Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
**Constraints:**
* `2 <= points.length <= 105`
* `points[i].length == 2`
* `-108 <= xi, yi <= 108`
* `0 <= k <= 2 * 108`
* `xi < xj` for all `1 <= i < j <= points.length`
* `xi` form a strictly increasing sequence.
|
Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds.
|
Array,Greedy,Sorting,Heap (Priority Queue)
|
Hard
|
2229
|
1,302 |
hey everybody this is larry this is day 15 i think of the may like day challenge hit the like button hit the subscriber enjoyment discord let me know what you think i still have crazy allergies so oh man it's so hard to talk so give me some love and support oh i need to take more whatever it is and the contest is coming up soon so i'm going to try to keep this a little bit quicker than usual but we'll see um okay sorry excuse me still recording this live so oh okay seasonal allergies pretty rough uh need to take some medication but yeah so i'm in the lanterns you can maybe guess my new background it's very hard i just got in so and apparently allergies in orlando is not better than where i was so still sneezing like crazy uh so that's the update um yeah let me know anyway okay let's get started today's problem we have about or i don't know you can't see it but we have about 20 minutes before the contest uh the saturday weekly contests begins or maybe sunday for some of you so let's get started uh today's problem is deepest leave some given a root of a binary tree we turn to some of the values of its deepest leaf okay so here's seven and eight okay so just the sum of the uh of the roots okay so yeah uh that's not so bad i mean i think there are a couple ways you can do it but yeah i'm going to do it with a little global e bubble but this is just going to be recursion problem and just keeping track of problem and just you know thinking about how to dissect the problem right so now first i'm going to have d plus is equal to negative one just as a thing and total is equal to zero right and now we're gonna have we could do it in order to post order pre-order doesn't in order to post order pre-order doesn't in order to post order pre-order doesn't really matter right so just uh traversal so whatever you know of a node if node is none we return um actually we also wanted current depth so let's have that um if node.left is none and know that if node.left is none and know that if node.left is none and know that oh and no doubt right is none that means that this is a leaf and this is a leaf then we do um yeah and then we just have some if statements i think if deepest is less than depth then deepest is equal to depth right of course you have to do non-local allergies is really kicking my butt in this apartment it's okay maybe i need to wash my faces i'm gonna put it and then now if the deepest is equal to depth then we oh and here we set total is equal to zero and here we can something weird why is it not uh why is this not uh not auto whatever ring okay whatever uh then we add it to the node.value and then we add it to the node.value and then we add it to the node.value and then l which that means the else is if it's not a leaf then we just go in order no doubt left that plus one in order no doubt right that plus one and oops and that should be good enough so we do it from the technically it's not in order so maybe i just uh just got recursion from zero and i think at the weight and it should be good return total uh yeah let's give it a spin this is just regular recursion and just keeping track of the depth is basically the cost of the problem um let's give it a submit i don't really have anything i don't know if there's anything weird about this one uh this one is my timing is a little bit slower than usual but i saw it in the past but 775 days go streak we're gonna hit 777 in a few days so that sounds like a weird number or whatever but yeah this is gonna be linear time linear space just from the core stack and this is very typical from three related things uh yeah i'm gonna call it knight as you can see i'm kind of struggling talking and all that stuff so uh we'll see how that goes on the contest but for now i'm just gonna i don't know take a shower or something maybe hopefully that becomes better anyway um let me know what you think this i would say for interview problems this is probably like within the scope so definitely get good at it get familiar with it um just some trees and recursion in general teresa and peop people on interviews really like recursion for some reason and trees are already you know is as a very intuitive uh or not intuitive maybe that's not the right word but an innate um recursive structure right so yeah uh that's all i have for this one let me know what you think actually let me take a look to see why the previous one maybe they added more test cases or something but uh yeah i mean i think it's the same thing so yeah i mean this one i did it without the global variable good job past larry uh current larry a little bit lazier but yeah cool i think that's all i have stay good stay healthy to good mental health i'll see you later and take care bye
|
Deepest Leaves Sum
|
delete-characters-to-make-fancy-string
|
Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 100`
|
What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest.
|
String
|
Easy
| null |
399 |
Jhal Ajay Ko Hello Friends Welcome to my YouTube channel Today they are going from Solid Problem to 1000 Problem Yes-Yes Railway Division The 1000 Problem Yes-Yes Railway Division The 1000 Problem Yes-Yes Railway Division The Problem of Medium Category Lahari Doctors Statement Your Given Address of Variable Pairs Equations and the Area of Real Numbers Values Where Equations And it of Real Numbers Values Where Equations And it of Real Numbers Values Where Equations And it is equal to take off but and values at it is equal to take off but and values at it is equal to take off but and values at it represents the equation airport also and tableau testing different servi let's move to the white and explain how to solve question in which it is like this divided So how much is this tweeting, after that when we also tried to divide, if we divide like this, then tri-valley air is free, then it is free, okay, now tri-valley air is free, then it is free, okay, now tri-valley air is free, then it is free, okay, now what did this thing tell us, life told us, is it different, tell me one more. Machine is a normal sequence, meaning is take pleasure points only, how much will we get from this point, what can we write in Fateh or coffee, they can write egg wipes, appoint also multiply given which one is simply our answer, what does it become, upon being allocated to was If Meena was a positive person, then the answer is six within the first and how many should be ours, it is the teeth that Nav Bibi Ko My Ab Ko, what is this in BJP, we know that f4 is also responsible for ours, what can we write on A. Otherwise the point is this point is also special again 1.2 special from 0.5 to 1.2 special from 0.5 to 1.2 special from 0.5 to 0.5 inches 0.5 inches 0.5 inches that further in these I one and I now we can see that we do n't have any of the elements in the name so it means - because you know there is so it means - because you know there is so it means - because you know there is no thing We do it straight like this, now tell me what will it be, AB means it is this point means what will happen if it is cut and we should make more Sita, so here we have written straight one and if neck mic we know there was someone extra. Not only this, we have it for that also - it has been written, you have come, so the for that also - it has been written, you have come, so the for that also - it has been written, you have come, so the question is clear to you, what is the question, now let us see how we can do it, what do we do here, its test graph, we become a customer here. Let's give like we take graphy notes, put them in a note, put a bead in a note and let us know what correction is coming from SSB. Tell us, on dividing 2 by 2, we get 2. Is it active in its weight or is it broken? Let's do it, then next we have b2c basic, enter customer correction, I also know how much the weight of all collection was, now look when I have it, as if the first Korean also made this phone call, this is simple, what can I do, you can directly write that my The famous answer is second, if I have preparation for SSC then what can I do, I have to go for SSC, it is ok, I know, I can appoint upon bbi multiply, so it means, it is straight, which part is there, which pass can I go. I am like this in this graph, I will start traveling in gram. Idea fried face I can reach from where to be done b2c you bittu and then what will I do with these two why multiplication in purse because I am doing edit medical store and Now I have approved from the family that what does the result of these two give us only, so with this type we can turn off the customer mode here and we can multiply its corresponding one and give its result, so this is We have the solution for this question and in addition to this, we have set a request that it is necessary for you to tell the bloody story of Face and Daddy. To solve this question, if you do not know then please comment on the number of Gautams in the benefits and graph. Once a video chat is created, I cut it. First of all, what will be my task? First of all, I need my own graph. So, I must have created the function Let's Support for the graph and now I will simply call the Create Graph function and pass the equations there. I am doing the equations and their arrangement so that I can design the complete graphic, what kind of graph, as I also showed in the white board, you know what it will return, let me know if you like the return, then like, when I am taking my graph from it, how is it? I create the time of the graph in which what will be the string because in the questions we have the source and our notes from the notes, we have to keep the string, so and the behavior pass can be called atlist can be Hey list of type loot to custom type hair. Make because I have to do two more tests in the list there, so what I have to do here is that when I take a string that we are in time, then its correspondence should be increased by the amount of it as it was and its weight in that. That is, what was the matter of Twitter in between, then someone else would be dependent in the coma, as if this connection was direct till here, then we Arpan CEA in coma, their son Akshar of cases like rape would have become one, then we would have the balance of one pair, so I am here. But I called for the graph and here I also define the custom class of my legs and what hair will be there in it, firstly I will have this type of son only and also this is of a double type velvet, after that you can do it here. Let's design it will be easy a string meanwhile comma that WWW which will like 19 only requested DMW request to we that this I have a class on custom From here our function gives us graph dev or now we have when If the graph comes then what do we have to do? Once the graph is gone then we now have to answer it from each note on our page like we have some queries for list of astring how to use in cars to or what do I have around 1020 or so. Will there be any string source which is Mari Sports Mode from which we can do our question like here at all this is 2010 and sincere destination sauce notice issue dated research that and string that destination is equal to cull date were first index nor way that now we have here But let's check something like just thinking dot s is equals that Bigg Boss destination is August destination and already equal, before that let's read that there is no element in either of them here, dear ones, first see me. In this graph, this note graph is Donison's thinking of yours and this note is again of daughters that what will we check in this statement of the destination here that if we do not have anything in the destination, what will we have to do? At that place, whatever answer is given to our answer madam, we will have to want that what do we do with flaxseed fat, the sources at events, the destination in that case, we know that when this and both are similar, there is something in it. We can simply return one There was tension on our position Reddy Clean text is equal to 1.04 In this we have to take the result 1.04 In this we have to take the result 1.04 In this we have to take the result Double result is equal to The first to visit a graphic source and destination I often edit Particular index is equal To result intermediate return to the difference, here we take out the darkness and take double 13307 you know that double the size as our but its length will be but on this note alien DTH that it has become with me, we create bomb functions, this is at First of all, if you read the client e will take the list of equations and values, then here we do not stitch it again. The proposed map is equal to the new map and the object is added to the custom app. Let's update our for laptop string aq in cars jhal that Priyanka is acute water 1004 that ring type destination notice and you can either with child and the number of the current nodule day test one nine match in this map A map that contains the information that the vegetables are already present on the map, so you can simply gift them there, you can open our map to our children, you will share the special feature of Map Don't Get, Daughter Mode Hair, when you die and what is its weight. The password will also be there in front of this platform, our questions are being migrated in carry store requirements migrate, equations are APQR why and video and our weight also let's mix double waste is equal to value certificate in text that induction here. So let's do intex request zero nine more what you have to do is put our weight here and SKS but if it is not in the map then we will have to shoot adilet test player m requesting you are list a jhal 2018 new peer Wait ki at SRC ko mar di da a at SRC ko mar di da a at SRC ko mar di da a similar li because the graph we will have is directional because always when we divide, the table is also the weight, how much was the tooth, if we release it in the end then it will be 12152 in reverse. If we go, we will do reverse tow in our connection, then for reverse connection, we just have to replace Chanakya in the simple place, it will take many hours for these Bihar shares, we will do the same here and instead of weight, we will change ODI World by weight channel here also. We think and pay VAT in the divider made here and also pay Bihar here PNB R&B RO PNB R&B RO PNB R&B RO how to merge, this entire map is ready, now we do immersion from here. The return is in a sit last, let's make our important decisions from private double in bf this tweet is a graph jhal ki and admitted san ki snowden it will take him ki destination note now we make this here to add Marathi Crop is wasted cup request for why type pair how to use a question new reddy why love you dot ru agree now starting from this note short and waiting shiv 1.0 will short and waiting shiv 1.0 will short and waiting shiv 1.0 will be made and in our videos in which what we will do we will maintain the nodi visit This trick definition bullion visit a devotional new map the wild love you dance 100 affair picos why do you fear imo that now visit check let this visit content a MP3 anything doubt speed data fit third bank continue that s always kill Visited Hotspot Ki Dot Nadak With A Belief How To What do we do here? This print and data is equal to destination. If we have reached our destination then we can simply return from here. Return weight is. You can make your better return. Let's do Redmi speed boat lift otherwise, now let's add children in it, why Kaur Ajay should prepare that child in graph dot son that is not visited New Delhi contains a jhal that child son love you dot old age is new fair where is the data on this side The current president will go to multiply by child not reduce weight, our from here 2 and available 168 test face will have to get done in not recognize the complete the jhal that the said ok queryist show's quality service tax credit size question is implementation is Very long on loot ok eat ok Google indexed based on any civilized one lion induced 10 after each stage a loot's one more thing that here also the values we have that here also the values we have that here also the values we have are very next so we have to increase our index here also End time of creation okra hai lootera ok so let's take a look in this never met on karo loot this issue so here we have put great equal to sting to humar posting to check on the net valid source and destination Hey Equal Development, we know that there is a difference, there is a special checking address in this operator that it checks the address by stretching and objecting and dress but this data is not found, so we had to use the third one, that mistake remained ok. If yes, let's wander, submit loot, ok, it's accepted, this is a lighter video, please comment here.
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
48 |
Hello Hi Everyone Arts Private Or Suggest Or Don't Specific Problems Candidate To Update Your Data Matrix Is Abodh A Few Loving 10 Minute Series Please Make Sure You Have The Like Button And Subscribe To Effective Youtube Channel Problem Basically Straight From Throw Tourism And Tricks Latest Tips and tricks directly from decree 12345 chapter wise 123 basically 12345 600 you can visualize please like you are in interviewer in bigg boss interview me tesu solvent to basically water world has limited gift roll whole the last call from one also control superintendent of police Anil Das and Taxi Driver Tinted Glass You Can Simply Take One Day at a Time Complexity of Being Physical and Complexity of Beneficiary Students of You Will Not Want to You Subscribe the Channel Please Will Be Performing Transport 1253 E Hua Tha Sacred Waters Transport Matrix Snaring Decolum Vikram Dros and Dros Will Become the Calling Next Suhana Transports Let's See How Can They Reduce 741 Sequence to 0258 You Will Get 8520 66 Subscribe Bose Virot Mein Simple and Very Easy You Can See This Difficult subscribe and subscribe Uttar Pradesh Superintending Engineer Sal Gurudwara Shree Time Complexity For actually bhigo of and shadow transport se tubego of in square leg * * tubego of in square leg * * tubego of in square leg * * Inspirational very bhigo of inspire and space complexity of bagga of one because you doing in place in the matrix give me to you so let's discuss disciples of valediction vash love you can see The Initially Is Completed Its Eyes And Remorse And Crops And Tricks Computer Science Of The Number For Alms To Transpose Matrix Person Use This Loop Instruction Ideal Of Every True And Everyone Who Has Just Known From 028 York Rangers Every Rule Solution Basically Transport And Tricks Key Subscribe our youtube channel that you deserve two point amit third to reverse every drop all storm tomato basically tales us you stand at one stand situated red cross bhawan situated and keep on doing previous mood points in both directions latest roda hai viewers up sample transpose reverse only roadways Delist the stand between the two handed wisdom enter explanation 2 episode please make sure hit the like button vidron in the president new to channel please subscribe and press the bell icon in telegram group and subscribe diy ocean
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
98 |
all right we are still doing the top line 75 leak code questions and we are on the tree section so now we're doing number 98 validate binary search tree given the root of a binary tree determinative is a valid binary search tree so as long as you're familiar with the data structure for binary search tree um this should be pretty easy there's two main ways to do this one is to be aware of the fact that performing an inorder traversal on a binary search tree should yield uh nodes in ascending sorted order so if you think about it here's the root two we do in order so we go to par you know recursively call in the left subtree first then the current node then the right subtree which will yield one two three so you can use that to create a list of nodes that if it is a binary search tree they will be in ascending sorted order then you just iterate over that list sequentially and check that they are indeed an ascending sorted order that's one way however the um the memory complexity of that is not optimal because we are using a extra data structure and creating that list which will have oven memory so what we need to do is um do this recursively um without using an extra data structure because that inorder traversal is also going to be recursive so it's also going to be you know collecting stack frames um and that memory is going to be the same regardless of whether we uh you know use the previous method of creating that list or not um so we might as well not use the list and cut to cut down on that memory so here we go so what are we going to do is um we're just going to recursively check each node and keep track of the upper and lower limits so for example when we're at node 2 um it can be anything there is no upper or lower limit it can be any number we want all right but then when we call left subtree right now this node here its left child cannot be greater than two so when we go down to the left subtree we set the upper limit for that particular function call to be two right and when we go to the right the opposite is true it cannot be less than two so we set the lower limit to be two right and this is true for more complexities as well if you think about so we'll go through this example five we call it the right four the lower limit is five because this cannot be less than five already we see it's false but just to give another example to see how this continues this logic continues when we get say this is like six then that would still be true so then we call left and now we still use the parameters upper and lower set by the previous recursive call so at this point the lower limits five the upper limit is infinity now we're going left so now the lower limit is five because everything in this entire sub tree has to be less than um you know all of its parent nodes so uh or greater than sorry so this node needs to be greater than five and again it's not but the lower limit will be five and the upper limit will be four hopefully that makes sense we'll go through the code now so the base case there's gonna be multiple base cases base case one oh my goodness well okay hold on first this if you notice here this method only allows for one parameter doesn't allow for upper and lower limits so i'm just gonna make a quick helper function it's gonna be the same thing but with a couple extra parameters lower and upper right okay base cases if not root what does that mean it means we've successfully recursively called ourselves without hitting any of those conditions that would be false meaning so far all the nodes within the correct upper and lower bounds so when we get to none we're good so we can return true okay base case two will be if that node does not fit within the lower upper and lower bounds so if roof.val is less than or equal lower or root.val is less than or equal lower or root.val is less than or equal lower or root.val is greater than or equal to upper return false right so like in this example 4 is not greater than or equal to i'm sorry less than or equal to five which would be the lower bound because we're going to the right otherwise standard case what we're going to do is return uh no so we're going to say if not and then we're going to do that left call so we're going to do um helper root dot left and remember we're going to the left so right every time we go to the left we're going to update our upper bound because everything in the left subtree has to be less than that parent node so that was going to be same lower bound but the upper bound is going to be root of l so if that's not true we're going to return false or if dot let root.right so we're going to check the root.right so we're going to check the root.right so we're going to check the right subtree now and for the right subtree we're going to have a new lower bound so that's going to be root divel for lower and the same upper bound so if either of those are false oops so if either one of those are false we're going to return false otherwise we'll return true okay and then finally what we're going to do here is actually call this function so we're going to return helper root and we're going to set the bounds initially to negative infinity and infinity this should work and normally you would check some edge cases but i already did this problem so we're good there you have it
|
Validate Binary Search Tree
|
validate-binary-search-tree
|
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_.
A **valid BST** is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** true
**Example 2:**
**Input:** root = \[5,1,4,null,null,3,6\]
**Output:** false
**Explanation:** The root node's value is 5 but its right child's value is 4.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,501
|
189 |
Hello Guys Myself Amrita Welcome Back To Our Channel Technosis So This Is Read This Top 150 Interview Questions Series In Which They Have Already Solved Few Problems So Today Bill Will Be Moving On To The Next Problem Date Is Rote Are So Late Get Started So This Is A Problem number one 189 which has a medium complexity life and wait while earning money rote di are you are right by the steps where this is non negative so basically you have without life one nas are and you have taken the right side by the steps so In the example you can see Namaste Are and K is 3 so date mains you have tu rote di are three steps to do right so let first understand what is Roshan and ho they are going tu rote de are to do right side by side how steps so let take d se numbers 1 2 3 4 5 6 and 7 right and k is 3 dat mins they have tu rote di are three steps tu d right side so let se in d first step k is one right k1 mins when you are rotating d Hey one step date mains which d elements will be shifted by one position tu d right side so let me right d index first zero one tu three four five and six right so no way have tu shift h element by one because of this one so one Bill come tu d first position and give tu three four five and six zero one tu three four five and six right so they don't have other index afterwords so no they are left with one element right last element so where d element bill to this element bill B shifted to d first position date min's the arrival Wickham 71234 56 step one k is tu again one more time tu three four and five bill b shifted to d first position so this would be output so date min's when they rotating d are in three Steps h element bill b shifted to d right by three positions so know if you see careful what was input date way one to three four five six and seven right and what was d output after three elements shift one bill to d fourth position right H element bill b shifted in three positions so give output is 56 7123 and 4 right and IF you see this careful last three elements and they can say last k elements are shifted since d front correct and d remaining elements are shifted tu d back side so the original erase one tu three four five six and seven so they have tu shift some elements through d front and some elements tu d back date mains way can reverse them so if i reverse d complete are what would be d result so What bill happens when they reverse d element from zero tu k minus one five six seven and four three tu one bill remain d se but style they didn't get the correct output right d elements tu also be next step they have tu reverse the remaining Element so dat mince five six seven bill remen se and four three tu one bill be reverse which bill wickam one tu three four date mens they have reverse tu the elements from k tu and mince one three tu de last element and they go the desire output Dat men's they have tu do three steps so d step number one dat men's they have tu reverse d whole are step number tu they have tu reverse d first's elements and step number let move on tu write d solution and it would expect tu input spanish Number by name three steps date mains first way are you reverse d are from zero you and minus one are and next step they have you reverse d elements from 0 and minus one date mains first k elements and give last step they have you reverse d Remaining elements dat men's tu and mine's one the rotted also they need tu write function wild status le give equals tu and they have to do the same three steps which they do to reverse the start index in d temporary variable and non stop times so this Are there three steps you reverse and are if you don't know reverse and are they have a separate video on date you can go and check date out and give start plus and minus mines they have two elements you are right by three steps No print statement rote and input sir namaskar so what was are first step first they are going you reverse d elements from 0 you and mines one so in this how they bill reverse the whole are date bill wickam 3 2 1 and d next Step we are reversing d first k elements tha mains 023 so again d output would be one tu three and in the next step we are going tu reverse d elements from k tu n - 1 reverse d elements from k tu n - 1 reverse d elements from k tu n - 1 right so in this how what would be k this 4 And n - 1 is you right so this how it would this 4 And n - 1 is you right so this how it would this 4 And n - 1 is you right so this how it would face so this is n one how greater than length of d are so it is going you face and date how what they are going you do they are not going you take d value of Directly we are going to see this how so let understand example SK mode non stop program and directly output so you can see it is accepted and run time is zero milliseconds so we can submit the code so the court has bin Submitted Successfully I Hope You Understand If You Have Other Questions Other Doubts Please Let Me Know In This Common Area Video Bill Cup On Solving The Interview Questions Thank You So Match Par Watching
|
Rotate Array
|
rotate-array
|
Given an integer array `nums`, rotate the array to the right by `k` steps, where `k` is non-negative.
**Example 1:**
**Input:** nums = \[1,2,3,4,5,6,7\], k = 3
**Output:** \[5,6,7,1,2,3,4\]
**Explanation:**
rotate 1 steps to the right: \[7,1,2,3,4,5,6\]
rotate 2 steps to the right: \[6,7,1,2,3,4,5\]
rotate 3 steps to the right: \[5,6,7,1,2,3,4\]
**Example 2:**
**Input:** nums = \[-1,-100,3,99\], k = 2
**Output:** \[3,99,-1,-100\]
**Explanation:**
rotate 1 steps to the right: \[99,-1,-100,3\]
rotate 2 steps to the right: \[3,99,-1,-100\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
* `0 <= k <= 105`
**Follow up:**
* Try to come up with as many solutions as you can. There are at least **three** different ways to solve this problem.
* Could you do it in-place with `O(1)` extra space?
|
The easiest solution would use additional memory and that is perfectly fine. The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays. One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example. The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on cyclic-dependencies between elements.
|
Array,Math,Two Pointers
|
Medium
|
61,186
|
273 |
hey guys how are you doing this is Jay sir who is not good our algorithm today let's continue our journey to needs code let's take a look at two seven three integer two in English words we need to convert a non-negative integer okay it's convert a non-negative integer okay it's convert a non-negative integer okay it's English words representation given input is guaranteed to be less than this so what's this so 2 to the power of 10 is 1,000 so 2 to the power of 10 is 1,000 so 2 to the power of 10 is 1,000 right so this will be 1,000 and a 1000 right so this will be 1,000 and a 1000 right so this will be 1,000 and a 1000 that's one minion and then 1000 this one minion and 1 billion right so that will be no more than billion level several billion I don't know okay so for example that's 1 2 3 it's yeah 123 and this one 12 12345 and this is one minion to hunt one minion 234 oh yeah 102 1/3 23 mm-hmm one minion 200 102 1/3 23 mm-hmm one minion 200 102 1/3 23 mm-hmm one minion 200 oh I'm confused two hundred and thirty four thousand five hundred a 67 1 this is 1 billion 234 million five hundred 37,000 891 Wow 37,000 891 Wow 37,000 891 Wow it's a it's uh it is the obvious that we can split this numbering by three digits right so these three digits actually have the same word wrap English word representation except the base right for these three like say this one is 891 but this is the last one so base is nothing so a thought 891 and these three will be 567 so 567 a 67 except it has a base called a thousand and the same is here 234 million right and this is one 1 billion so I think the idea is obvious we just Travis the string from right to left and collect them by three digits and then transform the three digits into representation and then add the base right so like it's when we collecting this the first one is the only special case is that so well there's two digits you see if the first next one is one if it's different like say we get one it's one right until nine it's nine itself we got this and this is ten it's not one ten right now there's nothing is only 20 but there is no oh no 1t like things so from 1 to a 1 like 19 it's all special case and then for 20-something up we could and then for 20-something up we could and then for 20-something up we could just the separate this same - - which just the separate this same - - which just the separate this same - - which would be - 23 34 40 60 and the rest would be - 23 34 40 60 and the rest would be - 23 34 40 60 and the rest is 2 to 3 like this is 23 so it's 20 plus 3 23 right and 69 right and what if there is a zero like 0 well 0 is nothing so we don't we just skip them what if it's 1 0 1 it's not special so one is of course it's 1 and then 0 with skip and this should be 100 so it's 1 and is hundred so right this is yeah cool so let's do it this the idea is Oh leave the command loop through the words backwards update the base every three digits mmm all right yeah okay so let's say for let hi we need to update base right yeah okay so how we how are we gonna do it when we first met one we're heading to the first two letters a special case and then when we go to eight it's too right so we handle it after that we need to insert to add the base right soddin and then do it over again if it's uh after so we need to keep track of where this current number is right if it is ranking we split it into three segments of three digits so this one will be indexed is zero or two or a zero or two or one or two so that's actually the mod right so let's say of course we need to cast a result mod three yeah now for the first number if it is first we need to take care of the second one also right if not we'll use quicker your switch Mart case one break case two good break zero right so this is zero zeros mod is zero so zero okay 0 1 2 0 okay let the base also we need to know which bases are their constant basis equals empty the first one is empty nothing and next one is a thousand million be bin okay so if it is zero like this 0 or this we actually need to insert the base first right so first we need to insert the base that push bases shift okay so for first letters is empty now we're handle what it is for the first digits we need also to take about take care about the special cases right and three all the how can I do it well let's check the legs letter if next one comes I minus one is one and oh the special case and then we could we need to skip the next one right so we I actually will plus one and then we can jump to next one if not we will actually will check that ok so the words I think words like four we will use array for the first round for the first wording would be case one alright so the first for us to did second digit third digit so it would be if it is zero then we do nothing right if it's one we say it's one two three four is America hmm before ah doesn't matter five six seven eight nine right and now for the second digit second and now for the second digit actually they are the same one two three four right but we need two plus oh no 35 to 40 oh yeah so it's the same so for 0 its 0 there's no 1 20 30 40 50 60 well this is a challenge for my English skills 60 70 80 90 cool and for the third one error for the fair 30 it's just that the one right this is the first dater plus 100 cool and there is some special case I'll say it's special case because it's special so I just ready now for its if it's ten this is 11 well English numeric system is it's complicated comparing to Japanese or Chinese or anything 12 is this right third thing for ting fav ting Wow actually this may be this is the first time I've ever reading the 15 like this 1617 a ting 9 ting okay so if the next one is one we actually could get that get the digits from special right so result were just a bit push a special what noms I was one plus lumps I write a special yeah they're all strings so it's okay it's um okay so this is done for the special case if it is not special say next one is twenty with something so we need to push the word in it right so it would be result push words zero numbs I okay we've done the first digit now go to the second one when we go to the second one the special cases are already handle right now so we only check directly to the words there's all no one but two so it's something like this yeah so we could just push directly upwards one I'm sorry and then we go to the third one which is based on hundred and here's a special case it might be for one for the first for the here it is 0 we say nothing for second one if it's still zero we do nothing but for the third one because we're gonna use the words here and plus hundred eight hundred there's only singular for all we don't need two hundred eight hundred okay we need to check the special case of empty right so if nums I equals zero we skip so you only check if it's not zero for this we will do what we will all we push hundred first result push 100 Oh God okay result push and then numbs I it is not we just use the first one word zero no I miss I right so now everything is done the input must be valid right and yeah billion yeah zero one two three yeah I think we're done so we now collect the result by join the result enjoying the results which okay so return the result reverse join joined by space you run the code uh-oh llamas is not defined hmm no oh God it's not num bug-free is so hard oh what not num bug-free is so hard oh what not num bug-free is so hard oh what a push right we join we open nothing one two three Oh we console.log nam i number we console.log nam i number we console.log nam i number ah Oh God we are giving an integer ah oh I'm so sorry that's integer so that's let's remove it - let's transform that's let's remove it - let's transform that's let's remove it - let's transform it to string switch Modi's not defined okay 120 300 where things happen 123 what but we get 120 300 also problem is become push 200 we need to reverse right so the fact last one because we get 1 we get to the hundreds in it we log not only the digit but also the result so hard so four three previous one is 12 so we push uh-huh one is 12 so we push uh-huh one is 12 so we push uh-huh I push work I'm sorry the 300 hmm haha I'm sorry wish I should do I should the eye is not start with zero it starts from numb I minus one so it should be the mouth should be um top and then minus one - I well for the last one he should be - I well for the last one he should be - I well for the last one he should be it's so I was zero yeah 123 still wrong answer haha yeah we is joying hmm we use join both need to dream oh my god quote this is right but allow me to try this one oh of course one answer what do we got 1 billion two hundred thirty-four we got 1 billion two hundred thirty-four we got 1 billion two hundred thirty-four mean Ian five hundred sixty seven thousand eight hundred ninety one mm-hmm thousand eight hundred ninety one mm-hmm thousand eight hundred ninety one mm-hmm it's the same right there's some seems some ninety yay there's a title here we run the code core let's try one more this one what keep out of memory really this one is right one two three so K is 4 is okay 5 so 5 if this 5 it's something wrong maybe it's pop because about this one - okay now it's no problem so there's some punk in the special case handling oh it's not plasma bites - one oh my bad plasma bites - one oh my bad plasma bites - one oh my bad so actually alex is no error but the answers wrong 12345 44 yeah there's a title here for huh it's really a challenge for English skills so what if there is zero will you still work haha no 123 million four hundred so here's a problem we even if we insert the empty string but we use join so I would not use join but I will reverse result okay and when I will not reverse I was just the final let final result for that I equals result and we filter the empty one and if I is not equal to zero wait a minute if we meet an empty one we forget it and when first we met an good number yeah this is okay so for the only except the last one we add oh my Mac is very runny is freezing click add one space return is final result oh my Mac is really freezing hope this will work no still might be I should put this if in here I really need to improve my so for the last one I get the five because I the first one might be zero if that is case I think hmm if that's the case I think I'd better really I better sorry uh I remove it I better still it was join but stop inserting the empty one right so the words say special shift okay this one special is okay the other one is this will only do it if love is bigger than that zero so the case here is also bigger than zero right yeah oh here forgot this one reverse Mike I got 123 a median 400,000 reverse Mike I got 123 a median 400,000 reverse Mike I got 123 a median 400,000 5 Studios this space what push oh yeah if so I remove the empty one here just to say if I speak it at zero it's not I bigger than zero but I smaller than then okay Oh finally man it's uh okay it's a myth hahaha oh these are there is a prop there is a this special case man my god if nom equals zero turn zero 19 worst night little 1999 god Wow it's not Terry right 1 million thousand oh yeah so 1 million thousand wish you not huh we actually need to cash that result by segment before we push into the words right yeah wow this is hard man so we will use a like sack array to cache the result we use this push everything into this set X first right and of course I need to reset a base push the sack push the SEC push the sack now every time we met a zero we need to push the sexy and reset it flush this is how to say this is a buffered whisk call it buffer flush the buffer when flash birthday when case is zero right unless we create a flash method and you to call it here and also I began we needed to flushed also so I think will be bigger than minus one and if we made the last one okay to do this just do this and we flush it flush the buffer so how do we flush the buffer means the first one the space is nothing and here or flush it so if the buffer is not empty we need to push a bass in it right so when do we flush then f7 at four add here at the end so the flush for the zero we could call flash but there's nothing there so if buffer top then it's bigger than zero if there's something to flush mm no we need to push the base verse right base basis shift if is more than it's not the first one you can flush if it is not if you're something in the buffer we should push the base first result push base and then push the buffer in it oh this your work of course it's wrong answer I forgot to we got to we forgot to reset it okay we get 1 billion 234 million five hundred sixty seven thousand eight hundred ninety one we've got an extra space and do we flush right there's an extra space we've already removed the empty cases I'll log 198 hundred these are all right over 1 so we flush push base and then push buffer or set it so the result is oh there's an empty string at the beginning I said we shouldn't flush at the and at the first one flush buffer for this case we should only 5 1 2 3 4 and then wait Oh lock result why we flush this we put fish oh the bass right oh my oh Wow well my name is limitation is really dirty I think it's so dirty Wow now let's try the biggest one this should be called I know ten million whoa I'm so moved oh yeah we've finally we achieved the right answer but the implementation is very ugly so I don't know whether it helps you're in it or not the general idea is the same I think we just to handle it by three digits and then we flushed and then we insert the basis right in search of the basis this is here faces and we and then we generate the final result the part of here actually there is no problem the only problem is that when we fall we need to handle zeros first we should avoid insert the empty string because you are finally when we joined what generate extra space another thing is the first base is the first read they just have not no bases so we should avoid in push the base also and why we use a buffer because we need to handle the 1 million cases all zeroes right we need to know when or when we need to insert the base or not so we will only decide determine that after all three digits are all processed yeah so and there is a challenge of typing right English is not my mother language so I have few titles anyway this is a tip I think it's not a difficult problem but it's true it's a verbose we need to handle so many educators like zero like or zeros and yeah like this intermediate zeros and everything and space and anything like that so we need to take more care spend more time on it and yes that's all for this one that's a little long hope it helps you next time bye
|
Integer to English Words
|
integer-to-english-words
|
Convert a non-negative integer `num` to its English words representation.
**Example 1:**
**Input:** num = 123
**Output:** "One Hundred Twenty Three "
**Example 2:**
**Input:** num = 12345
**Output:** "Twelve Thousand Three Hundred Forty Five "
**Example 3:**
**Input:** num = 1234567
**Output:** "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven "
**Constraints:**
* `0 <= num <= 231 - 1`
|
Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
|
Math,String,Recursion
|
Hard
|
12
|
462 |
hey everybody this is larry this is the last day yes it is june 30th the last day of the june nico day challenge hit the like button hit the subscribe button join me in discord let me know what you think and hope y'all if y'all here hope you're here for the full 30 days if not i mean you could look at my playlist or something and then just check it out but uh whether you're you have a monthly streak or not let's get this part started remember that you know whatever i don't know what the streak is at nowadays i guess it's actually on the screen uh 8 20 820 day streak going so that means that you know it's we're not stopping tomorrow we're not stopping next month uh i think knock on wood so yeah join us do the problems together and come to discord post your code so uh you know ask questions about it whatever you need to do uh it's free yeah because some a couple people ask me like you know but i'm just saying it's free and i don't you know i don't intend to do anything like that uh to charge i mean anyway all right let's get started today is the last um problem so minimum moves to you to eco away elements two so given an integer array numbers of size n return the minimum number of moves required to make or array a limit seeker in one move you can increment or decrement an element of the way by one okay so i think one thing that you can do is uh binary search right um can you hmm well you could definitely do a ternary research um which is not a common thing but there's something that's my arsenal and i do think about it probably more than i need to be i think this is one of those problems that the thing that it reminds me of is a classic problem where um where basically you have a white or well x coordinate you have basically a one dimensional line and then you all try to figure out what is the best place to meet right and this is basically that problem uh where you can go left and or right and then you try to find you know and the answer is going to be um you know you could probably do a and based on that visualization even though yeah and i think this is exactly the same problem but with a easier visualization um basically as the as i say again it's the uh you have a one-dimensional line or a street or one-dimensional line or a street or one-dimensional line or a street or whatever where you know you have all these people and you're trying to find where to meet and i think by that um there are two answers right one is okay actually i was gonna do some ascii art but you know while i'm at home while i have this beautiful joy let's uh let's bring up my drawing pad hang on and i think i have a good um good idea for we'll see if this actually works hang on but yeah so let's say you have this timeline right and then you have um let's say you have something like this and these lines are and they're not equally spaced they're like in all place and then now you're trying to find out where to meet right so i think the intuition is that it's going to be the median or well okay so let's do two cases right if i'm thinking about median then i'm thinking of well like let's do the odd case because it's easier uh to know what the median is and then the even case okay so let's say there's odd number of um things we're trying to get find the middle for and then i think uh you can prove i think this is the middle and i think this is where you would put the numbers right why is that well the reason why is because if you move let's say you move to the left one right what happens well that means that to the right uh you know that me that moves plus five and then everything to the left right is minus four right um so then by that means that you know by moving to the left one space you're making your answer one space worse right and of course you can do the same for going to the right i mean i'll leave it up to you without loss of generality i like saying that so that's what i'm saying but hopefully that makes sense as a racialization right and then of course uh so that's the odd number right and i think you know i think this is good enough of a proof let me know if you uh you know want to add it on later let me try now we have another one right and now let's say the even number so maybe i should have spaced it out a little bit better but anyway so uh and i think this is still the median but let's say about 4 and then now the median well i mean you could i know that the various definition of medium but it actually if there's even a number all you have to do is just between um the two numbers in the middle right why is that same logic right let's say we are here um oops let's say we're here right um well moving to the left one means that here we have plus 4 and here or to the right we have minus 4 right and of course this is true for everything in the middle right and maybe i should use the different color um and then of course now let's say that we move to one of the numbers let's say here right and then now if we want to keep on going to the right well past this that means that here it's going to be -5 it's going to be -5 it's going to be -5 and here it's going to be plus 3 because you're moving oh sorry the other way around my phone my fault um but we're moving to the right then on the right side is going to be -3 because the right side is going to be -3 because the right side is going to be -3 because that means that every all those three people can move one step less whereas plus five to the right or to the left i don't know what i'm saying but hopefully the visualization's right though that means that everything to the left has to go one extra step if we're moving it one step to the right so hopefully by this uh visual proof we get the idea that um yeah we want the median also i need to space figure out how to space out my planning my drawing a little bit better because as you can see i have so much space on top anyway that's a little matter so yeah so now um and with our loss of generality let me bring it back up for a quick second that means that because on the bottom the one on the bottom we can go any number from here to here um that means that we don't need the true median we can use we could probably round down around up because let's see which is our number uh we have seven elements if it's zero index then the number that's in the middle is three so it's about divided by two where if it's uh let's say there's two elements and you could choose zero and one um if we do it by two it's gonna be the one round up but it doesn't really matter so yeah so that's good and i wanna say one thing i'm lazy so i'm gonna do a sword right and then the median number is the element in the middle of course you can optimize this with a median finding algorithm uh which is you know o of n um there's o of n squared worst case however you can just randomize the input to make the worst case um very unlikely right so that's basic and you would add the randomization just because um because you don't know or if someone wants to give you a really bad input they cannot if you randomize the input that's basically the idea um at least not easily i mean you could you cannot get unlucky but they can't force you to be unlucky uh i'm not gonna do i want to go over median finding right now um yeah i'm not gonna go over median finding for this video but um if you have questions about it let me know but that's basically one way that you can do an n of n um however i am a little bit lazy so i'm going to uh at least because i want to focus on not the median finding part but just the part where you know we're coding so yeah uh so median ish is equal to numbers of uh numbers over two and then we just you know sum up for x and nums uh total is equal to zero total uh absolute number of x minus median ish and then we turn total right uh that seems okay let me just double check my n is equal to zero cases and because i feel like recently i've been really silly on edge cases so let's quickly you know try a little bit more um okay it looks good let's give it a submit and then cool yeah again you can do this in oh the june batch nice uh yeah again you could do this in linear time but this is gonna be n squared because of the sorting um but yeah how did i do it last year did i do medium finding uh oh i did some crazy technology what is going on here oh huh i mean i guess i could do this i know what i did last time i guess last time i was a little bit not as sharp on the proof what this is just figuring out a way to do brute force which is i guess like if you didn't want to do the proof doing blue force is pretty good and then it's just basically um choosing okay if this number is in the middle then what is the cost right and then take the best cost i think this is what this is doing still n log n but yeah um cool um i think that's pretty much all i have for this one let me know what you think uh cool yeah have a great end of the month stay good stay healthy take your mental health i'll see you later and take care bye
|
Minimum Moves to Equal Array Elements II
|
minimum-moves-to-equal-array-elements-ii
|
Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_.
In one move, you can increment or decrement an element of the array by `1`.
Test cases are designed so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** 2
**Explanation:**
Only two moves are needed (remember each move increments or decrements one element):
\[1,2,3\] => \[2,2,3\] => \[2,2,2\]
**Example 2:**
**Input:** nums = \[1,10,2,9\]
**Output:** 16
**Constraints:**
* `n == nums.length`
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Math,Sorting
|
Medium
|
296,453,2160,2290
|
1,015 |
hi today i'm talking about leap code problem one zero one five smallest integer divisible by k what this problem asks you to do is write a function that takes an integer k and returns the smallest in that is evenly divisible by k where n is entirely composed of the digit one and if there's no such n you're supposed to return a negative one so their example your input k is one your output is one because one is evenly divisible by the input and one is entirely composed of ones so another example they give is if your input is 3 excuse me i should say what you're supposed to output is not the n itself but rather the length of n so here the output was 1 because n is 1 and the length of 1 is 1. i hope that makes sense excuse me so here 3 is your input and the smallest number in that's divisible by 3 is one which has a length of three so three should be your output and they explain that here the smallest in one it which is evenly divisible by your input k has a length of three and so then if you have an input where there's no valid in so there's no number of ones in a row no matter how many ones in row you have that are evenly divisible by this input k two then you should just output negative one there's no positive integer in uh divisible by two where n is entirely composed of ones so that's what the problem is asking of you and the first thing i did to think about solving this is i asked myself this key question when is there no 1 n divisible by k because if i know that there is some value then i can just go ahead and search all of my one ones until i find one that is evenly divisible by k and when i do find one then i can just return my result i'll return the length of my result return the length of that one string so when is it the case that there is no 1-1-1-1-1-1-1 so the first thing that occurred to me is if k is even so if you think about it an even number plus an even number is always going to be equal to an even number um so i mean that's pretty straightforward and any even number kind of rules out um ever landing on a string of ones so like the reason why i'm talking about addition or why i'm saying you know it kind of rules it out is we can say um you know there if a number is going to be evenly divisible by k then you should be able to say k plus some number of k's is going to equal our in our string of ones but because this would be even plus even e plus e that would simplify to an e the next k is going to be an even e plus e whatever we would never be able to hit an odd number which is required to be to get to n so if k is even then we know the answer is negative 1. one other conditions you know i just kind of asked well what if the number ends in one there yeah it's pretty obvious we can get to a one what if the number ends in three any number where the digits summed three is equal is evenly divisible by 3. so 1 the example they gave so we know numbers ending in 3 or sorry we know 3 has a solution 5 is interesting because it's an odd number that has no solution multiples of five either end in five or they end in zero so 10 15 20 25 so no multiple of five will ever hit one on one seven and nine i found they had multiples that were were divisible four five just by kind of exploring like this six um i find that they have one sequences that are evenly divisible and so then i just kind of i suppose you could say conjectured that all odd numbers other than five would have a one string and i tested this um and it seems to be true so i'd say i haven't proven that but it seems to be true and it works well enough to solve the problem so at this point you know i can basically just implement it by saying what i'm going to do is check to see is there a solution if yes search for it and if not return negative one so it's pretty straightforward um and here's my implementation of that solution so the function that lead code requires me to write smallest rep unit div by k i guess is the name they have for it um i'm just making this check is it even or is it divisible by five if so return negative one we know we can't solve this and otherwise what i'm going to do is search for the answer inside of this generator function so i'm going to say for each o in this in the result of this generator function if o is evenly divisible by k then just return the length of the string about and the reason for converting it to a string is just so i can easily use the length function because that's the format that they want the answer to be in they don't want you to return the number itself they want you to return the length of that number and so the generator function is just going to give me one strings like strings containing only the number one and how that works it's going to start with an n so i'm just going to start it off i know that i don't need to consider any one strings that are smaller in length than the input value because that wouldn't make any sense you can't evenly divide a number that's smaller than yourself so the first thing i'm going to do is it's kind of complicated notation i think to get to a simple idea but just convert it to a string so we can again get the length of it and then put the number of ones put one character for each length of my input string so if my input string had a length of two i would get two ones if it had a length of three i would get three ones and so on and then just convert those three ones four ones whatever it is um number of ones into an integer so ones will have a value of 1 the same number of ones as the number of digits in n and then while true we're just going to yield my ones value after we yield it we're going to multiply ones by 10. so multiplying by 10 means that the last digit is going to be a zero and then i'm going to add one to it so the last digit will change from zero to one and so this generator whenever it's called it's just going to yield the next ones so if i invoke this with one as my argument it'll yield one first and then 11 and then 111 and then 1111 and so on and so i can just loop through all of these and recall that we know there will be an answer eventually at least i've conjectured that so i can just run this loop in perpetuity until i find the answer and so to test it what i did was i used their examples one two and three then i just put in some random numbers because i couldn't think of anything that's really specific to this problem it seems like it seems to me that my solution will work generally or kind of not at all so i was just testing it with a few different examples and i tested it with their maximum constraint and with their minimum constraint um and then just some numbers that i thought seemed you know seemed kind of uh kind of weird or interesting to me um so i wish i had a better methodology for testing it but testing it worked and seemed to kind of prove out my conjecture that um yeah there would be a ballad in for all of those cases as you can see it's not the most performance solution but um yeah i think without figuring out a kind of mathematical insight that would let me uh produce one values more intelligently i don't think there's a more efficient way to search this space so i need to have some kind of mathematical insight which i don't have and i think like possibly i could get by reading the discussion forum obviously but one thing i did want to show is that it sometimes requires you to search a large number of ones to find the value that eventually solves it so i think that's why this program is relatively slow because i'm searching in this case i'm searching 600 plus integers to see if they're evenly divisible so there's got to be a better way but i don't have that better way actually while i'm speaking it's occurring to me that um rather than just well i guess that idea is not fully formed but there's got to be a better way i don't know it yet but this is at least a i think fairly straightforward or efficient solution so that'll do it for me if you enjoyed this video let me know by clicking the like button leave a comment to let me know you're watching um if you want to see me solve about one leak code problem a day then go ahead and subscribe thanks for your time
|
Smallest Integer Divisible by K
|
smallest-integer-divisible-by-k
|
Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`.
Return _the **length** of_ `n`. If there is no such `n`, return -1.
**Note:** `n` may not fit in a 64-bit signed integer.
**Example 1:**
**Input:** k = 1
**Output:** 1
**Explanation:** The smallest answer is n = 1, which has length 1.
**Example 2:**
**Input:** k = 2
**Output:** -1
**Explanation:** There is no such positive integer n divisible by 2.
**Example 3:**
**Input:** k = 3
**Output:** 3
**Explanation:** The smallest answer is n = 111, which has length 3.
**Constraints:**
* `1 <= k <= 105`
| null | null |
Medium
| null |
228 |
K ribbon I have given this Adarsh Mishra and you K ribbon I have given this Adarsh Mishra and you K ribbon I have given this Adarsh Mishra and you this mission code and today we are going to talk then on the list about the summary ranges from this product there is a very lovely problem so understands and what is saying to us that your life is solid unit interior subscribe What is to be done is going to cover the accused in this case, okay so here you guys subscribe egg 123 subscribe my channel it takes half a liter as if see this from here it is here so it will be investigated yourself okay example time And appointed in good time 08 2012 subscribe should a in just 4 5 6 way means subscribe and subscribe our channel now here subscribe 601 then subscribe my channel subscribe 892 subscribe with 80 to reset us and I have understood that the work is fine, if you have been given the tempo first, you have to return the MP list here, it looks at the fourth example, this is what to do here, if an element is closed, what will you do at that time, simply. - We will do it what will you do at that time, simply. - We will do it what will you do at that time, simply. - We will do it here - And it is going to be seen, Sir, now here - And it is going to be seen, Sir, now here - And it is going to be seen, Sir, now here you have been told a little bit about these things, in that I have to extract from you the summary agreement about the overall range which we, the number providers, now the school and not you people. Let's see the example 02 1457 Okay, if subscribe is appointed, then subscribe, you should subscribe to the channel, okay, this should be done, from where to where, I have not subscribed in the other two different villages that I have selected this, okay after this What is Vitamin C? If you have the answer in your list, you will send it, then how we have made it simple here, by using it a little psychologically, we have made a point of I am okay, now let me clear it here, let me explain to you, I have given this element this decision. I did that my brother said that TV Replay This range is 0123 45 This is given in the shoulder What does it mean that they will be next to each other in consecutive order When I picked it up, what should I do, then I call a person named J and it is formed by doing the name J. Which will run from IPS one, from here it will run that I have simply selected you here, after that as I do, where are you, we will check whether there is a jam element, whether it is consecutive to the element one step behind it or not. It means hero plus one, here we will add oil to it and start simplifying it - it is equivalent to ' add oil to it and start simplifying it - it is equivalent to ' add oil to it and start simplifying it - it is equivalent to ' Subscribe to Meghnad channel', Subscribe to Meghnad channel', Subscribe to Meghnad channel', then there is no 'subscribe' here, it then there is no 'subscribe' here, it then there is no 'subscribe' here, it means that we should put in 'Village' and 'Subscribe my means that we should put in 'Village' and 'Subscribe my means that we should put in 'Village' and 'Subscribe my channel'. Have to take channel'. Have to take channel'. Have to take meaning 012 We have this hobby so let's come decoration element is that and MS Word is prohibited He picked them both up and put them for the skin with force and then what will we do then again appointed is simple Now there will be tables and chairs for this One step further it will ask 4529 constructive melt that this four consecutive hatred is required if it is like this ghee subscribe channel subscribe you can use subscribe toe hai what is the first thing to do I set zero in brother's streets because First of all, we have selected the limit, okay, its result is prepared for the exam, okay, in the result list, we are not going to get all the ranges of the patient, instead we are going to take all the history and keep it inside it, okay, there may be a scene that we Length of our alarm's 20's prohibition neither do for that then our channel should subscribe that young man should subscribe then from where to where it will go from that to full subscribe is the proper step for aa j is the first limit if it has plus one Will do ok please come home and subscribe our channel like comment share mean luttu subscribe do n't forget to subscribe the channel complain this is a statement after that it will go for a minute and keep checking side by side PK is running consecutively that If you don't want 1234 then if it ever breaks then subscribe subscribed 2012 and from then till today subscribe here - - - from then till today subscribe here - - - from then till today subscribe here - - - This means that in lots of 182 Aaraghya Ishta from each other, you will see that our Ghaghra is appointed Subscribe Had appointed appointment on this appointment as soon as possible Our - I that it becomes soon as possible Our - I that it becomes soon as possible Our - I that it becomes equal If the loop next to the forest camp will run then IA will start It will be done and घर मे अग्ध घर में अग्ध आई है है है है है है है है है है है । done and घर मे अग्ध घर में अग्ध आई है है है है है है है है है है है । done and घर मे अग्ध घर में अग्ध आई है है है है है है है है है है है । So Z - I is creating value here So Z - I is creating value here So Z - I is creating value here intake that it means that we do not forget to subscribe a particular subscribe while moving from village to village subscribe accused 123 45678910 will take quote its has said first limit is for g man judgment Pick it up and put it in the middle and whatever at that time I have appointed to complete drinking it, we will check for that. Inch from here easily keep it on low that subscribe this channel for Yuva Sangh is not working. Okay, so here we have left the appointed subscribe appointed, so here we will be soaked off from time congress and not square.
|
Summary Ranges
|
summary-ranges
|
You are given a **sorted unique** integer array `nums`.
A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive).
Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`.
Each range `[a,b]` in the list should be output as:
* `"a->b "` if `a != b`
* `"a "` if `a == b`
**Example 1:**
**Input:** nums = \[0,1,2,4,5,7\]
**Output:** \[ "0->2 ", "4->5 ", "7 "\]
**Explanation:** The ranges are:
\[0,2\] --> "0->2 "
\[4,5\] --> "4->5 "
\[7,7\] --> "7 "
**Example 2:**
**Input:** nums = \[0,2,3,4,6,8,9\]
**Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\]
**Explanation:** The ranges are:
\[0,0\] --> "0 "
\[2,4\] --> "2->4 "
\[6,6\] --> "6 "
\[8,9\] --> "8->9 "
**Constraints:**
* `0 <= nums.length <= 20`
* `-231 <= nums[i] <= 231 - 1`
* All the values of `nums` are **unique**.
* `nums` is sorted in ascending order.
| null |
Array
|
Easy
|
163,352
|
283 |
given here a rain dance write a function to move all of its zeros towards the end of the array while maintaining the relative order of the nonzero elements how will you do that's about today's video let's get into it Row 1 this is Steve today let's go through a legal problem 283 moves zeroes take a look at the problem first given an array nums write a function to move on zeros towards the end of the array while maintaining the relative order Hampton done zero Edmonds given this example 0 1 0 3 12 so we see there are two zeros and the Opera is that both of the zeros and moved towards the end the relative order of the nonzero elements is still kept 1 3 12 this is the problem very simply easier problem number one solution is not very optimal actually it's not going to mean one of the notes you must do this in place this number one solution might be just make a copy of the array so say we just loop through this array make a copy of all of the nonzero elements while maintaining its relative order and then also we can maintain a counter meeting a hundred of the zero elements so while we finished iterating through the array for the first time and then we can have a while loop to keep decrementing the 0th hunter 2 while the zero country keeps dog remaining we can append zeros towards the new copy I hope that makes sense if we do that time complexity is open we look through this array there is no nastic for loop but the space complexity is not in place its own end as well because we need to make an extra copy right that's actually not going to mean one of the requirements say if your interviewer gives you this requirement during an interview you must do this in place using constant space on one space without making any extra space requirement now let's take a look at think about is it possible to further optimize that brew for some Oh in space oh and time complexity solution just like us there is because that there's a known which says you must do this in place without making a copy of the array so let's take a look at this example I've copied the example over here values these are the values 0 1 0 3 12 the index is 0 1 2 3 4 so which is to start from the very left see here is a 0 here is a 1 so what do you first is well swap these two right or swap these two or swap 0 with 1 with a 0 because 0 is a 0 we'll move all zeros towards the end right so as long as we encounter and nonzero element we're going to swap it I hope that makes sense and then what we'll do is we'll keep moving forward suppose we have a pointer pointing to here and another point increments to here and we're next step let me I like this and next step what we're going to swap so just to think about how we swap with that very we move from the left end towards the right end whenever we encounter a non zero elements were just going to swap in with the very first 0 elements so in here we're going to swap this one island in red and very first of the very last 0 on the very left hand which is this so these two at the end instead we're gonna swap so after swapping this array becomes this that makes sense so what keep continue to move forward we have one pointer pointing here another pointer pointing here and this is a non zero element so we're swapping with the last zero element which means we're going this one so I like this one get it back into black and this one make it blue this one make it black this one make it blue so these are the two values that were going to swap so after this one the array becomes the final correct array right so how did we achieve this of the technique so the algorithm that we used is then we keep track of the very first zero and then we also keep track of that very first and none zero and on the right-hand of the none zero and on the right-hand of the none zero and on the right-hand of the array whenever we encountered the very first non zero and which is to swap this one with the one on the left hand that very early the earliest zero hanumant that's what we did right so with that said what we can deduce from over from that technique from that idea is that we can use two pointers one pointer is always pointing at the very early zero the zero on the very left end and another pointer were quite fast pointer which were just to keep moving forward which will keep moving towards the right hand it's always going to check the very first non-zero element whenever the first non-zero element whenever the first non-zero element whenever the first pointer finds the nonzero element it's going it's just going to swap with the first zero element just swap their SWAT leg keep swapping in this way we're doing this in place right using constant extra memory so we'll have two pointers here I and J which is quite a engine and you can't call it slow or fast pointer well use J as the fast pointer which were just keep moving towards the right and Jennie will only check whether the current elements that's the current Hammond that is pointed by J whether that one is a non zero element so first both I and J start from the very first to zero index so when J is 0 this Hammond is zero so J will keep moving forward J will keep moving Jane was here J is pointing at this parent so this Hammond is in a 0 and what we will do is that we will swap these elements most what these two that's what happened here right and then and this moment remember previously I we didn't increment I because that one is slow I will only be increment only when we do the swap but J will keep moving this one it says fast point J will keep moving so at this moment we did this one okay let me topic you moving here and this movement hi I guess incremented Jenny also gets incremented so J is pointing at the third event here so J is a J is Ponyo and 0 and so we don't do anything so we don't increment I on with you and swap so at this moment we keep incrementing j is a fast pointer so now j is pointing at ananza ram and so what keeps wobbling the two animals pointed by I and J slow and fast pointer so now hi españa here J is program here what keep swapping in this room 0 and 3 so 0 still the very earnest 0 and 3 is the very first than 0 and that we encountered while the fast pointer is everything through so after we swap these two elements the array becomes this 1 3 0 12 and after this will keep well implementing both corners both slow and fast pointers so at this point I is going to be incremented by 1 G 1 will also be incremented by 1 and then J is pointing at the very last non-zero pointing at the very last non-zero pointing at the very last non-zero element and I is still pointing at that release to 0 so what we will do is that so since J is pointing at a non 0 and when what world do is was what these tournaments so we got this and then we keep incrementing well increment I and we also increment J at this point we find J is equal to the length of the array so what is the break out or stop that's the entire algorithm that's the entire idea this way were only using o and O what we use one time complexity but the space complexity is constant we only need a 1 temp variable to hold the element to do to help to do the swap so we don't need to include the entire array that help us to meet both of these two requirements you must do this in place without making a copy of the array in the first proof for solution we were actually using own space we were making an extra copy right and keep a counter after zero admins that's not very optimal and also this solution when it's also helping us to minimize the number of total operations we're only doing a swap when we encounter the nonzero element and we swap that with the very earliest zero we keep doing that helps us to minimize the total number of operations why would I see that why will this why when this idea to help us also minimize the total number of operations think about we only do a swap when we encounter the first non-zero elements encounter the first non-zero elements encounter the first non-zero elements that means the number of operations are the number of swap it is only going to be equal to the number of nonzero elements right think about an array with most of the array is filled with zeros of the entire array is completed zeros there are 1 million zeros in this array in that case we don't do any operations right that's why this algorithm is also helping us to minimize the number of operations which is the second requirement alright I hope that makes sense if that does let's put that into code which is we're going to use I think three or four lines in synopsis you can even do that in one night just cos wall but in Java let's put in the more verbose way to help everybody on the same page to understand this idea completely then yes Niko has recently implemented the autocomplete feature which is super awesome good all that in real interview if you were asked with the code on the whiteboard you don't allow to come to you but it's just a nice feature to have or keep incrementing jail regardless whether we encounter anything but well what we'll keep checking is J well at J equals to zero so remember here J is our first point what we were check is whether the fat pointer is pointing at a non zero when every that is the case were doing a swap let's check so if the first pointer in J is pointing at a non zero Hemet what we'll do is that was why temp names I named J and this is well J to I and then I have is J assigned temperature J and I is our slow pointer so what I'll do is then well increments low point here will increments low point only when we do the swap so we do this well now we increment on here we do the swap then we'll increment I to be here that's the only place so I is our small point our slow pointer will only increment snow pointer when with doing the swap that's the idea assign s double check assign names to temp and then put names change the increment I and then assign okay I think that's going to work let's hit some min and see all right except them well 100% 100% except them well 100% 100% except them well 100% 100% I don't know how accurate that is but anyway this is the idea to use only a 1 you don't need any extra memory and it's space complexities own one so time come times many so what that's it if this video helps you to understand the problem and the solution just do me a favor hit that like button that's gonna help a lot with YouTube's algorithm and don't forget to subscribe to my channel as we continue to go through a lot of classic leave code and interview coding interview questions to help everyone better prepare for their upcoming interviews that's it for today's video I'll see you guys in the next one
|
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
|
34 |
welcome to this lecture where we will solve the first and last index problem we are given a sorted array of integers R and an integer Target and we are asked to find the index of the first and last position of targeting r if Target can be found in R we turn -1 if Target can be found in R we turn -1 if Target can be found in R we turn -1 minus 1. for example if R is 2 4 5 7 9 and Target is 5 the output would be 2 6 because the first position of Target is 2 and its last position is 6. first of all the user array is sorted all the elements with the same value will be adjacent to each other for example here all positions of the value 5 are consecutive it means that the first possible solution is to start traversing the array from the beginning find the first position of Target and keep Vulcan until finding the last position with our example we have 2 4 then 5 we found the first position we keep walking we have five this one is the last one we found the end position we return them in code we start traversing indexes of R and if R of I is equal to Target it means that we found the start position now we keep walking while the next element exists and is equal to Target while I plus 1 is smaller than length of R and R of I plus 1 is equal to Target we'll increment I after the while loop I now represents the position of the Lost occurrence this is why we return start I and if the for Loop ends without having returned the result it means that we didn't find targeting r at all we turn -1 know that it's possible to have start position equal to end position it happens when there is only one occurrence of targeting r for the time complexity when Target exists we Traverse the part before its first position then its sequence of occurrences and when it doesn't which covers the whole array in both cases which offers at most n elements where n is the number of elements of R we get a Time complexity of O of n and a constant space complexity because we're just using end variables this solution uses linear search which gave an oauth and time complexity but the array is sorted so we can think of using binary search let's try to use binary search to find the start position with binary search we can find the position of an element in a sorted array but here we're not searching for any position of Target we're searching for the first one I is the first position of Target if R of I is equal to Target obviously but also R of I minus 1 has to be smaller than Target smaller because the array is sorted so we will use binary search normally but we add that second condition before returning met let's try it with our example left and right start at first and last element of r as usual mid is left plus right divided by two we get 4 here is true that R4 is equal to Target but it's not enough out of four minus 1 is not smaller than Target so mid is not the starting position of Target but should we go to the left part or to the right part now R of mid is not greater than Target so the first position can only be in the left part we continue mid is now zero plus three divided by two we get 1. R of 1 is smaller than Target so the starting position can only be in the right part we continue mid is now two plus three divided by 2 which is 2. R of mid is equal to Target and R of mid minus 1 is smaller than Target so mid represents the first position of Target we return it in code we can first have an early exit condition for the case where the first element is equal to Target we Darkly know that 0 is the starting position we return 0. by the way in Solutions based on binary search put as much early exact conditions as possible to handle edge cases and avoid out of bounds problems after it we initialize left and right at 0 and N minus 1 respectively zero and N minus 1 are the indexes of the first and last element of r now while left is smaller than or equal to right we calculate mid index it's left plus right divided by 2. after it we have three cases the case where both conditions are respected where R of mid is equal to Target and R of mid minus 1 is smaller than Target it means that mid is the starting position we return it second case arov made is smaller than Target it means that we're still before the starting position this is why we take left to Mid plus 1 to start again in the right part else it means that we exceeded the consecutive sequence or were inside it but not at the beginning so start can only be in the left part we take right to Mid -1 and if the while loop didn't return a result it means the target doesn't even exist in R we turn -1 now we found the start index but we still need to find the end index we can think of just Vulcan starting from start until we find the last position of Target but it would ruin everything we did because in the worst case we need to Traverse the whole array which results in an off and time complexity same as the first solution you guessed it to find the end index we will also use binary search but the condition is a bit different from the first time when searching for the start position R of mid had to be equal to Target and R of Min minus 1 smaller than Target and for the end position R of mid has to be equal to Target and R of mid plus 1 has to be greater than Target next element has to be greater because it would mean that from the right we're not in consecutive Target elements anymore so the actual position is the last position of Target in code we just change a few things the early exit condition occurs now when the last element is equal to Target it means that the Lost position of Target is in the last index of R and minus 1 with Darkly return then in the three cases the case where we return mid is when R of mid is equal to Target and R of mid plus 1 is greater than Target for two remaining ones here one hour of mid is greeted On Target then we exceeded the consecutive sequence we'll go to the left part white becomes mid minus one else it means that either will before the consecutive sequence or we're inside it but not at the end so and can only be in the right part left becomes mid plus one now we have our fine start function we have our find end function we can move to the main solution function first of all we have some early exit conditions we can identify at least three cases where we can't find Target Arrow when the array has no elements one target is smaller than the first element and when Target is greater than the last element in the last two ones because the error is sorted we can deduce the target is not equal to all other elements if at least one of these conditions is true we doubtly return -1 true we doubtly return -1 true we doubtly return -1 else we call fine start to get the start position we call find n to find the end position and we return start end if Target doesn't exist in R start and end will have returned minus one buff we still get the expected result for the time complexity we're using binary search twice and binary search has an off log anthon complexity because we keep dividing the input size by two times over log n gives an overlock and time complexity and for the space complexity we get all one because we're just using in variables before ending this lecture I want to tell you that if you're not comfortable with binary search you should really work on it because it's a fundamental algorithm technique that appears in many problems like this one find Peak first bad version and many other ones we reach the end of this lecture I hope that you understood the solutions and see you in the next one
|
Find First and Last Position of Element in Sorted Array
|
find-first-and-last-position-of-element-in-sorted-array
|
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`
| null |
Array,Binary Search
|
Medium
|
278,2165,2210
|
246 |
hi quotas i am sanjay and in this video we will discuss lead code problem 246 a stable grammatic number so let's see what the descriptions is given a string num which represents an integer return true if num is a stable grammatic number is a number that looks the same when rotated 180 degrees looked at upside down so let's see some examples example 1 6 9 is a stereogrammatic number why because if we rotate this 180 degree then 9 will come at first position and it will become 6 will come at the second position it will become 9 so the result will be 69 and for the second example 88 so if we are rotating this number to 180 degree then it will again be 88 so this is a stable grammatic number example 3 962 so if we are rotating this number this will return some other number because the rotation of 2 to 180 degree will be not a number so this will be false now let's check for some other examples so 69 we have already seen one zero one if we rotate this number then one will come at last this one will come at first and this zero will be at the same place so it will be one zero one so this will be a stable grammatic number 131 so this one will come at the end and it will become 1 this will come at the front it will become 1 but 3 will not be a number it will show some symbol like e so this will be false 1 9 6 1 this one will come here they both will be same 9 will come at this place it will become 6 and this 6 will become 9 at this place so it will be same so this will be a stereogrammatic number now 6 0 6 so this 6 will become 9 after coming here and this 0 will be same so it will become 909 which is not equal to 606 so this will not be a table grammatic number okay now from all these examples what we can observe is we have 3 digits 1 0 and 8 which will be same after rotating 180 degree and if we are rotating 9 it will become 6 and if you are rotating 6 it will become 9 so on the left side if you are having 9 and on the right side if you are having 6 then the rotation will not make any difference and if on the left hand side it is 6 and on the right hand side it is 9 then also the rotation will not make any difference because 6 will become 9 and 9 will become 6. okay so let's go to the solution for coding solution we first need to think of five digits first two digits are one zero and eight so they will be the identical characters if you are rotating them to 180 degree they will produce the same characters so let's take one has set for the identical characters and this headset will be storing those three characters one 0 and 8 and then we would check if the left character and if the right character is the identical character and if they are same in that case we would check for the next left and next right elements so let's check two variables left equal to zero and write equal to num dot length minus one and we will check till left is equal to right so if left is equal to right that condition also we have to check in that case we have to check whether that is an identical character or not if that is not identical character in that case that will be some digit which will be different after rotating 180 degrees so let's check for this first condition if our current character which is num dot caret so if our current character is the identical character and it is available in both left and right then we would increment left and you would decrement right now the second condition would be we have to check if the left character is 6 and right character is 9 or right character or left character is 9 and right character is 6 because rotating 6 to 180 degree becomes 9 and rotating 9 to 180 degrees becomes 6 so if on the left side we have 6 and on the right side we have 9 then they will become same after rotating 180 degree so if num dot care at left equal to 6 and num dot carrot right equal 9 so this is the first condition what will be the second condition if on the left hand side we have 9 and if on the right hand side we have 6. then they will produce same string so it will be left plus and right minus okay now there is third condition when our current character is neither in identical capsid nor six not nine so in that case we simply have to return false after executing this loop successfully finally we have found that the string which is given as an input is an stable grammatic number because after rotating this to 180 degree it is becoming same number as the input let's check if it's passing the simple test case okay so there is some issue in line number 19. okay so this will be in one end condition and this will be in other end condition yeah now let's check okay so this is passing the sample test case now let's check if it's passing all the test cases okay so this is passing all the test case now let's see what is the time and space complexity for this problem so we are taking one set which will be storing only three numbers so this will be of constant size and then we are taking one left and right variables which will be iterating all the characters from left and right side so this will be only executing n times so the time complexity will be order of n and the space complexity will be order of 1 because we are not using any extra space thanks for watching this video if you want to get some more videos like this then please like and subscribe our channel you
|
Strobogrammatic Number
|
strobogrammatic-number
|
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_.
A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down).
**Example 1:**
**Input:** num = "69 "
**Output:** true
**Example 2:**
**Input:** num = "88 "
**Output:** true
**Example 3:**
**Input:** num = "962 "
**Output:** false
**Constraints:**
* `1 <= num.length <= 50`
* `num` consists of only digits.
* `num` does not contain any leading zeros except for zero itself.
| null |
Hash Table,Two Pointers,String
|
Easy
|
247,248,1069
|
270 |
hi so this is problem number 270 on lead code closest binary search tree value given the root of a binary search tree and a target value return the value of the bst that is closest to the target so what we will do is since it is binary search tree we will have to traverse it in one of the uh we have to traverse it and then go through each node and find the difference of those nodes value and the given target and keep recording the lowest one so that's how it is so uh let's start implementing the solution so what we will do is we will store the value um dot val and then start the while loop so what we will do is while root is not equal to null we have to traverse first so given a target the left children will have the will have a lower value right child will have a higher value so the next route will be if target is less than the root dot well that means if target value is on the left side that means so next is left or else it is root right this is regarding traversal now checking the closest node condition so what we will do is this we will say if math dot absolute of root dot val minus target if this roots value and the target's value that if the difference is least is lower than the previous minus target then the previous route value is and once you come out of the loop then just return this okay yeah let's run this code it works and submit perfect
|
Closest Binary Search Tree Value
|
closest-binary-search-tree-value
|
Given the `root` of a binary search tree and a `target` value, return _the value in the BST that is closest to the_ `target`. If there are multiple answers, print the smallest.
**Example 1:**
**Input:** root = \[4,2,5,1,3\], target = 3.714286
**Output:** 4
**Example 2:**
**Input:** root = \[1\], target = 4.428571
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 109`
* `-109 <= target <= 109`
| null |
Binary Search,Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
222,272,783
|
171 |
hello everyone welcome to quartus camp we are 22nd day of february leeco challenge and the problem we are going to cover in this video is excel sheet column number so the input given here is a string with alphabets and we have to return the corresponding column number for the given column title so let's understand this with an example so let's consider the pattern of which how the excel sheet alphabets are numbered so as usual as we know starting from a to z the numbers are going to be 1 to 26 correspondingly but then after is it the column number starts appearing like a b a c and so on till a z and once this is done it is going to start with b c and so on till bz so this goes till z so as we know a to z is going to have the number 1 to 26 what would be the numbers that will be for a to z it will be 26 plus 1 which is 27 to 26 square plus 26 so how these things are determined because till z it will be 26 after that it will be a so the next number is 27. so this one comes with a because a is the first character which is holding the value 1 so 26 plus 1 would be a and finally z will be 26 square so first this 26 square comes from all the numbers because every alphabet has to combine with every other alphabet for example a should be combined with a b c till z same way b should be combined with a b c till z and so on so that will actually give us 26 square numbers and this 26 comes from the z here because is it is holding the value of 26 so that is what we are going to add here same way if we are going to have aaa then it will actually be the next number to z so which will be 26 square plus 26 plus 1. so to make it even more clearer let's compare this with how we represent numbers in the number system so let's say we have to represent the number two five six eight in form in base of ten so in this case two should be multiplied by thousand plus five into hundred plus 6 into 10 and finally adding 8 so this is how we represent a number with base 2 10. so this will also be represented as 2 into 10 cube plus 5 into 10 square plus 6 into 10 plus 8. so this is how we are going to represent our column title as well the difference is that the number system holds the base of 10 and our alphabets are the column titles holds the base of 26. so we are going to represent our column titles using the same way so let's consider by replacing this numbers with the alphabets value so now let's consider the example a c d we are going to convert this into a number so now a is in the third position so let's say a should be multiplied with 26 square so a is represented as 1 here so 1 into 26 square plus c is having the value 3 so 3 into 26 plus what is the value of d that is 4. so this is how we are going to represent if suppose we have a number b in front of these 3 then we should be adding it with these values to 2 into 26 power 3. so this is how we are going to represent our column titles to numbers so hope you are understanding this logic so let's get into the code now so let's first do the base condition so yes we have declared the value sum where which we are going to add all the alphabets value and finally we are going to return so as i said we are going to iterate each character from the given string column title and add it with the corresponding powers of 26 so yes we will multiply it with 26 and we convert that number to alphabetical value and we do plus one so yes this is it let's give it a try yes so let's submit yes the solution has been accepted and it runs in four 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
|
Excel Sheet Column Number
|
excel-sheet-column-number
|
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnTitle = "A "
**Output:** 1
**Example 2:**
**Input:** columnTitle = "AB "
**Output:** 28
**Example 3:**
**Input:** columnTitle = "ZY "
**Output:** 701
**Constraints:**
* `1 <= columnTitle.length <= 7`
* `columnTitle` consists only of uppercase English letters.
* `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
| null |
Math,String
|
Easy
|
168,2304
|
894 |
Hello gas welcome you me youtube channel so today we are going to solve today report problem 894 which is possible flower binary tree so what is this question about we have been given n wait and we sir have to return as many flowers as possible So see like the value of N is 7 then it said to return like this is a flower? Is the flower binary? Binary is the one whose every note has either zero children or two children like this is your flower, this is also not your flower why because it has only one. If this is going on, then how do we do this, how will we record the question from record to record, so what we can do is make every note the first note main and tomorrow, that means every note is the root note main, so as if we have If we see, we have 5 notes, then considering each note as a root note, we can do it tomorrow, then if we make zero and do it tomorrow, then what is happening and here we will try to make it from notes, this is your flower binary, so it is possible. Even if we make it, there will be one extra A, hence, it is not possible to make it, so N is equal for you, again from the same, two is two, so again it is not a flower because there should be more on both sides, only then it will be possible, like one will come in the root. Two will come here and here, if it is not coming in the root, then nothing, then what should always happen, either there is no zero, now it is possible to make it from note 3, if not here, then this is also possible, then it will not happen, here zero note will go and on the right side. Zero will not be possible again, it will go 4 A, so we are noticing one thing here, it is possible to make zero only if we have a flower number from the note and note noticing one thing here, it is possible to make zero only if we have a flower number from the note and this is This one is the root, so if there should be more on both sides, only then the note will be made, this is possible, we will see later, N is equal one, meaning what was a note, this one is made and returned, this is what will be made, not just one note and If earlier I took the result variable and what was the option, like I was making it for N = 5, there like I was making it for N = 5, there like I was making it for N = 5, there was an option for every note, zero is possible, three is possible, so now when I am making it for one, then how much will happen on I? One note will go on the left, whatever is the value of I. How much water note will go on the right? N - How much water note will go on the right? N - How much water note will go on the right? N - I - I - I - Whatever is the value of 1, value of N, if there is five in it, then 5 - what is the value of I, in it, then 5 - what is the value of I, in it, then 5 - what is the value of I, one minus one five minus tu kitna ho. If three goes here, then like this we will send both left and right and it will remain complete by doing this, what is my less that whatever is left and right, what will we do by making a route and traveling in both, then help route the route to the left. As much as this answer is given in the right, what will happen to everyone, it will become a sir, like this, there is one more thing in this, what are we doing, why are we making DP of DP, like see, it is a relief, do it again tomorrow. Why would we calculate, like if we have calculated completely from here till here, then if we have already calculated for this value, then why would we calculate it again, we will pay here after doing this and return this one from here. If the salary will be paid tomorrow, then this is what we will do and return it, like for this, see these three bananas, we have already calculated it, here too, we will do the same and return it at both the places, so it is the same. DP Hey, we will create one which will be of vector type vector of vector tree no desktop okay that means this is a free calculator so in this you can also take a map of every place here.
|
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
|
703 |
Hello Everyone Welcome Back to My Channel Today Were Going to Discuss the Problem Share Please Element Industry Switch Very Easy Problem Receiver Problems Designer Class to Front District Judge Element Interesting Key Notifications Rajesh Element in Short and Not as Distinct Element Key Implement Care sa just class sleep classification addition justice constructor and here with now's value addition just million and jerry in life they can stream of teachers and review function and when vitamin A two-minute and function and when vitamin A two-minute and function and when vitamin A two-minute and increased value addition to the elementary setting turn on OK So What is Means What Were Given After All Care Conspiracy Means of Which Lies to Front Constructor Make an Object Like This is Creation of Object of 10 Classes Apart from Just One Object Related Constructor Equal Write Short Note Key Value Shrill End Doms ring it a look soft is given to ask third key and norms given to answer that 4584 560 does not know what minute with every time it's called which is cold water even number is given that will it will add value to this cream and vital Takshashila Judgment à OK Sweater Jasmine for Example Let's Say This Chord Recorded And Element Is Avot Element Third Service To The Number Say District 34582 And Tours And Industry In Tracks Right Special Treatment's Well-Known Right Special Treatment's Well-Known Right Special Treatment's Well-Known Entries Today Lettuce Team Know What We'll Have To Or Twitter The Increase Element In Sight Returns The Apart From Should To Return Back Meaning Largest Element A Right To 200 How We Can Do The Great To Ways Of Finding Apart From Which Element Boys Very Simple But Or What Is A Ride Vowels 30 To Front Four Largest That little jis elements what we can do simply means what things are in decreasing order 100 decreasing order episode 85 floor three do something like this with the third largest in jis waqt hai to for relieving later ons ke din the and doing right this is not wake A Bird Sea English Approach We Are Doing Something Right To Employment With Dignity For This And Loving You Are Aapke A Hai Naveen Can Improve Se Login Ki With Something Ko Liye Block Ki Rat We Can Do Something Chord Using Hubris And Wick And Evolution And Looking so hot is instant which lifting right what we can do is we can have that science this is the printing is coming but if your Navratna gives which will smith see and mini a torch light which gives maximo mini suji 250 final Today Elements Which Might Be Thinking That Will Be Using Maxi A Flash Lights Of Birth Story Elements In The Mess Scene Shoot Two Three Four Five Eight To 12925 Third Largest Tweet Powder Third Largest Value And Will Draw Famous What You Might Be Thinking That Might Interest You have but see guys approach and this is bell work but the things that are very important are that management system acting like right to pose press complex in the open that also every time login only real incidents like avengers maxi pimples login will Be the time for the you must be thinking about what benefit were getting rate and development zee channel main strip emergent a that show this maximum approach will work but addition to approach will be using miniclip right so you can see you can identify like it's something governor Apart from Just Right Care for Latest Something Related Day You Might You May Think Way Wikinews Maximum in Upright and See Previous Justin Uses Mean That Small and You Can You Make a Profit of How ilaj Rock Not Only Also Works But This Is Not a Sufficient Right to vote through this vitamin E should be coming e mini form in his work hain inhi right what will you do the policeman ep 8 ing all that my agenda is not in his I will be storing being limits hua hai Inside Story in New Delhi E 105 Is Clear Events Of Every Time Being To Diminish Day Of Fifth Time To Space Click Okay That Time To Arrange Roles Elements Against These Every Time People Raees Suggestion Yaar Improve The Time Complexity And Take Off But When Using mini suv will know every time will have two three elements in the meaning of fennel and vid6 ki real rights and mirror size apni fees and sure day will go to dhanesh element 5 me virajit meaning singla and tool size relation shoulder joint Nine wicket tweet a yesterday morning tore a that his boat size of minimize is equal to two three layer three element which is equal to two sleep in which anniversary wish to English meaning and ninth tubelight villa dare to men he is but in this is greater than right for That of them in this provision grade one's swift first limit sonu near retrievable fog itself the minimum the element which will for fifth minimum one to the thing doing this alternative science of mini of this greater day's I just from it aphoto that your opposition Listen to that from near this mean that will give minimum volume and just before to this point same minimum balance and 9 News Yasmin to front this last one listen minimum values which you use swift love you to three values which you use swift love you to three values which you use swift love you to three layer to measurement wearing thumb in his Every time when every element vitamin E e me nine wicket size again for witch a great sin ke to will again for no pregnancy is minimum swift the right sudarshan vida media elements right nine ki job complete williams dart courier vihar to 8 3 persons ward-3 So What I Will vihar to 8 3 persons ward-3 So What I Will vihar to 8 3 persons ward-3 So What I Will Do Is I Will Have To Hard Secure The Division Right View All It's Clear 100 Co Cost Vote Mintu Written Updates Largest Swarnim Itihas History Dhundh Element Will Dare Is The Missions Last Minimum Will Come At The Top Leader 12 Button Take Care Share This Water Wars And Stop This Is The Largest Number Of Some Suggested Benefits Of Using Mini Apart From These World It Always Stop Opposition Party Revenue Yadav Bottom Denge Second Largest And Akaliat Will Be Edit Topics Only So They Can Just Vinyas Twitter The Amazing spider -man Amazing spider -man Amazing spider -man those sunshine vitamin e stop ko his seminary na amla the country comes i love you to file elections and timings to come na ring industry 1525 deer ₹5 damini size more visit britain ₹5 damini size more visit britain ₹5 damini size more visit britain 's to will remove the fifth problem english what will i do 's to will remove the fifth problem english what will i do 's to will remove the fifth problem english what will i do Not Mean That Which Is Ride 250 Election For It's Not In The Meaning Of Hai What Is The Meaning Of C 5210 President Largest Switch Between Us Top Richest Right 555 Return Fight A Right Similarly Maintain Welcome To Main Tera Ringtone A That Soviet Yaara Ringtone 203 Vihar Dead In Russian And Will Tend To Mean That No Size Again For Which Region's Distraught Pop Something That 12.5 Developed Minimum Distraught Pop Something That 12.5 Developed Minimum Distraught Pop Something That 12.5 Developed Minimum Volume Fifteenth And Yasmin He Will Appear In Itself Vitamin B5 80 Apart Where 5252 Pirates Similarly Where To Fur Nor a zero two had been done yesterday morning you understood the approach very simple right using mini so that they can find the great soldiers element doodh le chitrakote list of method 4181 10 minutes and it is medium size ok and dangers kepler jakar tractor surya constructive Vivo Getting It Straight Problem There Telling Wrinkles Actor Will Get K Any Query To Fear Of Getting This Thank You Are You And I Are And What Are Doing And Pushing Elements In The Meaning Of What Is The Size Of Medium Grading K I Will Pop Song Meaning Of Vitamin blurred elements of birth now you edit in award function is getting view to have been pushed out volume slow what is the meaning of these many solar year size of days have been days of p why opposition you might be thinking if they can say because of which Vayu is a local to character add me to use in response to benefit viewers will happen soon and stored on your screen size records of this person balance constructor but unit here right the panel has been written speech to start with besides destroyed the 215 problem and Approach let me to the don't see odf please like and subscribe my channel and i think when oo
|
Kth Largest Element in a Stream
|
kth-largest-element-in-a-stream
|
Design a class to find the `kth` largest element in a stream. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
Implement `KthLargest` class:
* `KthLargest(int k, int[] nums)` Initializes the object with the integer `k` and the stream of integers `nums`.
* `int add(int val)` Appends the integer `val` to the stream and returns the element representing the `kth` largest element in the stream.
**Example 1:**
**Input**
\[ "KthLargest ", "add ", "add ", "add ", "add ", "add "\]
\[\[3, \[4, 5, 8, 2\]\], \[3\], \[5\], \[10\], \[9\], \[4\]\]
**Output**
\[null, 4, 5, 5, 8, 8\]
**Explanation**
KthLargest kthLargest = new KthLargest(3, \[4, 5, 8, 2\]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8
**Constraints:**
* `1 <= k <= 104`
* `0 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `-104 <= val <= 104`
* At most `104` calls will be made to `add`.
* It is guaranteed that there will be at least `k` elements in the array when you search for the `kth` element.
| null | null |
Easy
| null |
926 |
Hello gas welcome back to my channel thank you and today's need for challenge Philip string so make a monotonic increasing string ok so in this question basically I have given a binary swing which has zero and one and what you have to do is you flip the zero. You can do this and flip the vane to zero and what you have to do is to do the minimum number of philips. What you have to do is to do the minimum number of philips. Your resulting string should not be monotonic, it should be increasing, like increasing or it becomes 1111, okay or Then zero vane would be 111, it will come out, we have to increase it in number of philips, in minimum number of philips, it is okay, in this we flipped it, by increasing and by doing a flip, it could have also done this, what could it have done that whatever these two vanes are 00 but it gets stuck in it, okay, so how will we do this? Look at what I do, I take my string as far as I have done the process like let it be zero van 0000 means I have found the answer for that. Given to him, I have made Monu token monotonically increasing, I have made him increasing, the part before this is fine and in that, how many of my required the answer number of Philips is required, I am fine in doing it before this, so I am, so far. My zero film required is ok so now this zero has come ok now my zero has come so what about the first one of mine so if this zero has come then what option do I have ok I can either turn it off even then it will not be monotonically increasing or Then, as many descendants as I have in it, I make them all zero, it will remain increasing. Okay, as many descendants as I have in this part, make them all zero. In these two conditions, only mine will remain monotonically increasing. What if more zero comes? A case will be made and if van comes here then this is my monoli increasing and if van comes here then it will remain increasing for monorane. If van comes then it is okay. Here I have taken increasing for my monorane so here Even if the van comes, it is going to be increasing, I will not have to do anything, so my answer will remain the same answer, if there is a van here, then it is okay, now I will tell it for the one with zero, okay, what will happen for the one with zero? If my zero comes, okay, zero comes, then how will my answer change, my answer will be either I vane it, the number of flips I do in the previous part, the number of flips I do to make it monotonically increasing, that is the answer and I call it zero. Also, if I am doing WAN, then what will be the answer? Answer plus WAN is ok, either this will turn my number off or what will happen to me is turn it to zero. Ok, so in this case, my number will be the minimum of these two. The minimum which will be from is ok Ok then it will be stored in my answer ok so the question is over first han so what will happen to us ok space company make them zero ok how many off the zeros before that If van is given, then how much will its answer be, right because either the answer will be plus van, my answer is ok, so till now my answer will be zero, till this point it will be zero, ok, so right now my answer is zero, the value of van is zero, ok, either I am zero Turn it off or make all the vans before it zero. Ok then the answer will be on this zero. So what can I do on this zero or can I make it van So now my answer is Value van toh me answer kam ho gayi toh hai what does it mean basically what did I do its answer is still being made means I reduced it to zero ok actual meaning answer ho jaayega to answer plus van ki value ho gai tu toh answer How much has happened here, you are done, okay, either I am here, I have made this whatever is there, I have made this or I have made all the closed ones first, zero reason, okay, then make this one, then what is my answer before this? Was there before coming to this, okay, you have reduced it to zero, okay, the answer was there till now and now I am doing it, so it is increasing Also like the video in comment.
|
Flip String to Monotone Increasing
|
find-and-replace-pattern
|
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none).
You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`.
Return _the minimum number of flips to make_ `s` _monotone increasing_.
**Example 1:**
**Input:** s = "00110 "
**Output:** 1
**Explanation:** We flip the last digit to get 00111.
**Example 2:**
**Input:** s = "010110 "
**Output:** 2
**Explanation:** We flip to get 011111, or alternatively 000111.
**Example 3:**
**Input:** s = "00011000 "
**Output:** 2
**Explanation:** We flip to get 00000000.
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`.
| null |
Array,Hash Table,String
|
Medium
| null |
2 |
hey guys i'm still unemployed so let's solve another leak code problem today leak code 2 add two numbers together so just like the problem says all we're really doing is adding two numbers together right so like this example 342 465 add them together right that's 807. well you probably remember from elementary school how to add two numbers together right so that's the number one thing to know about this problem right so we're adding 342 and 465. so do you remember how to add two numbers together from elementary school you probably do but you might think you don't so let's just look at this right two plus five that's seven four plus six that's ten but that's a two digit number right so we gotta take a carry for that so we'll put a zero here but we know we have a carry so we're gonna have to put that one over here right so now we have one plus three plus four that's eight so we just did it right that was the result 807 so you do probably remember how to add two numbers together that's really the main part of this problem now the second thing to recognize though of this problem is that there's a lot of edge cases that's kind of why there's a lot of dislikes in this problem you can tell over here but so there's going to be a lot of edge cases and we're going to really talk about those edge cases and focus on them so the first thing they tell us is we're given two non-empty linked lists given two non-empty linked lists given two non-empty linked lists right so these linked lists are representing the integers that we're adding together so they're non-empty what does that mean for us non-empty what does that mean for us non-empty what does that mean for us that means if we're adding two numbers right like uh 500 plus something else right this second number it can't be empty there's always gonna be some number here right so like eight for example something like that it's never going to be empty the other thing is that they're non-negative integers that's really non-negative integers that's really non-negative integers that's really convenient for us because these are linked lists remember so having a negative number would kind of be inconvenient so good thing we don't have to worry about that the other thing is the digits are stored in reverse order now let's not worry about this too much yet so for example we see 342 down here in 465 right in the linked lists they're stored in reverse order so 342 is actually 243. uh 465 is actually 564. so we'll see later that having them in reverse order actually helps us and so we want to add these two numbers and return it as a linked list so for each digit we're going to have to create a separate node so we will keep that in mind so let's look at a slightly modified example in the example given both the numbers had the exact same number of digits right so there were three digits in each but we're looking at it slightly different we added one more digit to one of the numbers because this is kind of a case that you have to consider so the first thing we're gonna do is obvious right we're just adding two numbers together so we're gonna go iterate through them right so five plus two that's gonna be 7 right that's our first node and notice that we're starting at the ones place right because that's how you add numbers and since the lists these linked lists are given to us in reverse order it makes it really easy for us to start at the ones place that's how you add two numbers together so they really made it easy for us so next we're just gonna basically keep doing that right so now we're gonna get to the next two numbers add them together that's going to be 10 so we're going to remember that we have to put a carry so we'll have a zero here and we'll make sure to remember we have a carry so now we're gonna do one plus four plus three that's eight now we no longer have a carry so the carry's gone and now we get to a weird place right there's nothing here so we only have one node right so what are we gonna say is up here well we can just kind of uh assume that it's a zero right so there's not actually any value but we'll assume that there's a zero here so zero plus three that's going to be three and in this case this is going to be our result so we just considered one edge case of what if the two linked lists that we're adding together are of different sizes right so we kind of know what we can do in that case now there's one last edge case that's kind of tricky i seem to never remember it when i'm solving this problem but maybe you'll be able to catch it so let's say we were adding seven plus eight together right now when you add it together with addition right it's pretty obvious uh let me rewrite it so we know it's 15 right so we're going to put a 5 here but we have a carry so the carry is going to go here right but there's no other number that we're adding here right we know we can just put the 1 here but when you're solving this algorithm you might forget to do that because with a linked list seven plus eight you add these together you get a five right that's our result and you'll put the carry here you'll say yeah there's a carry of one but in our algorithm we have to make sure to remember to put the one in our result right even if there aren't any uh nodes here right like there aren't any input nodes that we're adding it with so with all of that in mind let's actually get into the code and it'll probably make even more sense so the first thing we want to do is we know we're creating a resulting linked list so i like to just put a dummy node to not have to deal with any of the edge cases of inserting into a linked list and our current pointer is going to point at the position that we're going to be inserting a new node or the new digit into so we're going to iterate through these nodes now how long are we going to be iterating through them while either of them has a digit so while l1 or l2 is non-null we're going to be l1 or l2 is non-null we're going to be l1 or l2 is non-null we're going to be adding them together now we know one of them could be null so we're going to get the digits from them v1 is going to be the digit of list one only if l1 is non-null if l1 only if l1 is non-null if l1 only if l1 is non-null if l1 is null though we're gonna set it to zero right just like we did in our visual example we're gonna do the exact same thing for v2 now we actually want to add them together but hold on remember we had a carry that we have to maintain so i'm gonna have a carry value and initially set it to zero outside of our loop so carry is initially zero so now we're gonna compute the new digit so how do we do that well we'll say v1 plus v2 plus carry right this is elementary school mathematics but now we could potentially have a new carry right so if our number that we just computed for example what if it's 15 right so that's a two digit number so we're we want to get the carry out of that so how do we get it uh we can just say value divided by 10. also since our value could be greater than 10 right like 15 we want only the ones place digit so we're gonna take our value and mod it by ten so that'll give us the ones place so now that we have the digit we can finally insert it into our list so we're going to say current.next we're going to insert a new current.next we're going to insert a new current.next we're going to insert a new list node with the value that we just computed so now we're going to be updating our pointers so we have to update current so we're going to set current to the next pointer we're going to update our list one and list two pointers if they are non-null so l1 is going to if they are non-null so l1 is going to if they are non-null so l1 is going to be l1 dot next if l1 is non-null l1 dot next if l1 is non-null l1 dot next if l1 is non-null else we can leave it as null right you might say okay now we're done we're just going to return dummy.next right so we're going to dummy.next right so we're going to dummy.next right so we're going to return the list that we just created but remember that edge case that we talked about right what if we had eight plus seven uh our loop is going to stop and we're going to forget about the carry so over here i'm going to add one last thing to our condition while our loop is going if our carry is non-null non-null non-null we want to continue the loop meaning if our carry for example 8 plus 7 l1 and l2 are going to be null meaning v1 and v2 are going to evaluate to 0 but our carry is going to be 1 right so we're gonna say uh we're gonna insert a value of zero plus one because our carry is one and then of course our list is gonna need to have that value in it so don't forget about the edge cases that's really what makes this problem annoying i hope this was helpful for you if it was leave a like and subscribe and thank you for watching
|
Add Two Numbers
|
add-two-numbers
|
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
**Example 1:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,0,8\]
**Explanation:** 342 + 465 = 807.
**Example 2:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\]
**Output:** \[8,9,9,9,0,0,0,1\]
**Constraints:**
* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
| null |
Linked List,Math,Recursion
|
Medium
|
43,67,371,415,445,1031,1774
|
115 |
hey what's up guys this is chung here again so this time lead code number 115 distinct subsequences okay so now this time we have two strings right s and t and we need to find how many distinct subsequences of s which equals to t right so basically for example we have this rabbit and it's a rabbit and this rabbit so the answer is 3 because we have three different subsequences in s right that equals to t right here we have 5 so that's the answer and the constraint is like 1000 right i mean so this is another like uh two strings dp problem right you know because every time when you guys see this kind of two strings and you uh find the number of distinct subsequences and with this kind of like 1000 constraints so most likely it's going to be a n-square time complexity dp problem be a n-square time complexity dp problem be a n-square time complexity dp problem right so how can we solve this one right i mean uh maybe you can start with a simple version you know i think we all know right let's say we have s and t right so if you if i ask you to find to tell me if t is the subsequence of s right i think most of you should be able to solve that right so how do we do it right we simply do you use two pointer right so we have i for s and we have a j we have j in the in this t right so basically every time when we find a match right we move both i and j forward right and if the current one doesn't match then we state we move with we don't move j but we keep moving i forward until in the end we check if the j has moved to the end right if j has to move to the end then we know that t is a subsequence of s right so that's how we find check if this t is a subsequence of s but for this one uh we need to find basically so here we're only finding one of the possible subsequence right but here we need to find all the possible uh subsequence subsequences right um so how do we do it right i mean for this kind of two uh two strings dp problem right though we have i here and we have j here right so what we already have we do this right so if i is equal to sj right we check this one if this one is the same then we will do something like uh we depending on the depending on if this one is true or not we'll have like different type of dp state transition function but let's define our dp state first so we have dpi and j right so this one equals to uh from 0 to i and zero to j right how many subsequence right do what do we have okay and in the end we return the dp of minus one and minus one will be our final answer which means for the whole s and t right and then let's look at uh our different scenario here right so let's say the um let's look at uh if this one does not equal to the sj i'm sorry this one's not tj right so let's say if the i does not equal to j and what then what do we have right if it doesn't that if they're not the same then we only have one option which is dpf ij equals the dp of what of i minus 1 and j right so this means that you know since the current i and j they're different right then we have to go back so basically the number of dpij right so the number of subsequences equals the number of dp i minus one j right because since the current one doesn't equal to this j we cannot match the we cannot match i to this j then we have to go back to i minus one hopefully the i minus one the d dpi minus one c can somehow match this j right and here keep in mind that you know depend uh based on our definition after of this problem you know we cannot consider dp uh i'm i and j minus one so this one is it's not right you know for some of the dp problem you know uh whenever this one does not uh equal to each other we some sometimes we get a maximum between this two right i don't quite remember which problem was that but for this one we cannot consider this one and why is that this is because you know uh depending because for this problem you know we need to know we want to know like uh if our if everything if all both all the characters from zero to j can be it's part of the subsequence from the from o from the zero to i right so if we do this one if we do something like this and then it's not right because our definition is that you know from zero to j basically the j's character has to be uh matched somehow but if we do this one that means that we don't care about the current j right which is wrong based on our definition that's why you know if the current i and j they're not the same the only option we have is go back to the to i minus 1 to make sure the i minus 1 can include from zero to j right and okay so that's that and how about so if the s i is equal to t j then what's going to happen right so the first one is going to be this one right so we have i j this first one is this it's going to be a dp i minus 1 j minus 1 right because you know so again so now right since i and j they are the same character right let's say this one is let's say it's d right this one is also d right they are the same the so d v i minus one j minor j minus one means that so from zero to i minus one and from zero to j minus one we have let's say we have 10 different subsequences right and since i and j are the same so which means by adding i and j to the end of this previous state we can still be sure dpi my dpi j has 10 uh different uh subsequences right but that's not all right so here so the tricky part for this one is that we also need to consider this dp of i minus 1j right so the reason being is that you know because even though the i and j they're the same but we can still we still have the option to e to ignore the current eye right some so for example we have a like i remember we have the rabbit right so rabbit and then we have a rabbit right so basically if the eyes i is here and j is here right sorry i think there's like not enough space here see my eyes here j is here and then it sees if we go back here right so from i minus one here we can still we may still find like match right without moving j's back right so that's why you know this isn't this one is regardless it needs to be considered regardless for both conditions okay and yeah i think that's it right i mean so as you guys can see so that's basically the state transition function for us okay cool um i can't i guess we can start coding oh where is my uh definition here so first we have this m equals to length uh of s right and then we have n is equal to the length of t right so we have dp of this uh 0 for n plus 1 this for this in range of m plus one right so we increase the length by one b uh trying to make sure that i minus one and j minus one will not uh go out of the boundaries right so basically that's why you know for this one we have this one to m plus one right and for j in range of one two to m plus one so basically this now here i and j means that the length of s and t that's why we start from 1 to m instead inside 0 to n minus 1 right so we check if the s i so here we do i minus one equals to t of j minus one right so this i minus one means that you know since we assume this i and j are one base but the s is zero based right that's why you know we need to convert this one base index to the zero base okay so if they're the same then the dp i and j equals to the dp of i minus 1. so that's the first j minus one that's the first scenario right plus the dp of i minus one j right else we don't have any other options but to go back to the dp of i minus one j right and then in the end we return the dp of uh minus one so that's basic the idea the state but we still need to figure out uh set up the base case so as you guys can see here right you know at the beginning everything is zero right so if we don't set up the base case you know obviously in the end everything will still be zero right so then what's the base case so the base case is like this so basically it's either like s is equal to zero or the t is equal to zero so that's basically the two base case category for the uh for these two strings problem right so for this one let's see if s is zero then what's going to happen if x is zero that means that uh everything should be zero because you know we don't have any uh subsequences that can match t right then we can since everything is uh was set to zero at the very beginning we can ignore that and then the other one is t right so if the t is equal to zero right so what's what does it mean it means that all we need to find is that you know if t is sorry if t is empty it's not zero if t is empty then the only valid subsequence is also empty in s which means it is one right so basically it means that let's say as this is abc right and then t is empty right so an empty subsequence it can match this one right because any because for the for any string an empty subsequence is als it's always a subsequence and only this one can match the t that's why we can do this for i in range of m plus one and then we have dp of i 0 equals to 1 right so because so 0 is also 1 0 dp 0 is also equal to 1 because a string empty if both s and the t are empty they still have one match subsequence which is empty itself right yeah i think that's it so if i run the code accept it right yeah there you go right so the time complexity right it's a n square and space is also it's not n square actually it's m times n right space is also m times it's time space right so i mean i think since we only consider like this see the i minus one right we might be i think we should be able to reduce this time complexity from m times n to n sorry for the space complexity because they are because of this right so we're which means that you know along the way we can uh we can use like a temp variable right to store this up previously state and then we in the end we set it back i'm not going to do it here you know what let's maybe let's try to do it let's see if we can figure it out right so which means all we need is like this we have zero of n plus m plus one right so we don't need this dp anymore okay and this dp of zero i think yeah will be one right in this case uh let's see this uh so here i said we have old odp okay dp of this right and so in the end we have dp equals to the old odp right so here we have a -1 dp dpj right so dpj uh so we're gonna remove this one right here it's gonna be this one and this one oh so here oh we're gonna need the out basically right hold out okay here we have this oh no we don't need this one right yeah basically before calculating the current one right we uh if we do this i think this should also work yeah so that's basically how we improve this time complexity right now since this one only like i said um since this one only depending on the previously uh dtp right dp is the first dimension we can just use a in temporary variable every time to calculate that to make sure and then we only maintain this one dimensional dp so this one is faster because we uh use a less space okay yeah anyway so that's it right basically this one uh i think we start from the simple version right i mean to check uh if this string t is it's part is a subsequence of string s and then i think somewhat we use the similar like ideology right and to apply this one to extend this one a little bit to get the count of subsequence right by getting this kind of uh state transition function um yeah i think that's it and thank you for watching this video guys stay tuned see you guys soon bye
|
Distinct Subsequences
|
distinct-subsequences
|
Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`.
The test cases are generated so that the answer fits on a 32-bit signed integer.
**Example 1:**
**Input:** s = "rabbbit ", t = "rabbit "
**Output:** 3
**Explanation:**
As shown below, there are 3 ways you can generate "rabbit " from s.
`**rabb**b**it**`
`**ra**b**bbit**`
`**rab**b**bit**`
**Example 2:**
**Input:** s = "babgbag ", t = "bag "
**Output:** 5
**Explanation:**
As shown below, there are 5 ways you can generate "bag " from s.
`**ba**b**g**bag`
`**ba**bgba**g**`
`**b**abgb**ag**`
`ba**b**gb**ag**`
`babg**bag**`
**Constraints:**
* `1 <= s.length, t.length <= 1000`
* `s` and `t` consist of English letters.
| null |
String,Dynamic Programming
|
Hard
|
2115
|
1,707 |
hey everybody this is larry this is q4 of the weekly contest 221 maximum xor with an element from away so this was um a problem during the contest that i to be honest i feel like i've solved this before a similar version but i couldn't really figure out from where uh and to be honest i actually solved this in about 15 minutes during the contest but and i've looked at other solutions as reviews after this um and it turns out that uh python is just really slow and because i wrote um i would what i consider cleaner code for interview um it the performance was actually too slow i think if i actually wrote stuff without using classes this would have been fine so uh so let's go over that i did and i actually spent an extra 15 minutes uh converting it to c sharp but we're going to go over my python solution um but and the c-sharp version worked uh fast and the c-sharp version worked uh fast and the c-sharp version worked uh fast enough the first try so i think that's you know a little bit unfortunate on the bounce um but yeah uh cool so the first thing that i would say is that when you see an xor problem um you know especially maximum xor um it's gonna be greedy or uh in some way probably uh this is just experience speaking um so also speaking of greedy hit the like button to subscribe and draw me discord uh so you can ask me questions let me know what you think because there might be a lot of questions for this problem but yeah so when i see xor the first thing that comes to mind is greedy why right uh maximum xor why are you driving greedy well the two things one is that when you look at uh the binary numbers because if you do an xo operation um all the bits are independent right so you have to you know a binary number all the bits are dependent um when you want to get the max of it um you always want to greedily um your most significant bit you want it to be a one right no matter what because if that's a one no matter what happens that's going to be your max answer um or like that's going to be bigger than anything that is on the other side where your first number is zero right so that's a property that i would think about um okay so then now i know that is greedy i know that is maximum and then there's this thing right um okay how do we enter this um so there are a couple there actually apparently two ways to do this that i noticed um the way that i would think about it is that okay the way that we have these queries i know that it's online you know you're given an order and you have to do the result in order but actually you can actually cheat a little bit by sorting it first right so very briefly um i actually recently did something similar on an on uh maybe a week ago two weeks ago where um you know you answered the queries with uh if you build the prefix of the uh calculations um then you can answer those queries as you go what do i mean by that right and i didn't do code it this way so um i'm not going to talk about that uh or i'm not go i don't have to code to show you per se but what i um but this is what i call the offline queries because why is it called offline because you know all the queries in the fan so you can do this offline right um the way that i actually solve the learning content is called online right because what i did was that okay given this answer i actually do not um like i do not know anything about the other answers and i do not actually reuse things based on that knowledge right so what i mean by that it's okay well first of all um you know uh if you look at the problem correctly or like carefully um you know you have this m inside the query where you know basically your m will if you sort it in a way such that your m goes up well your tree will only mutate as that m goes right so that you can so if you think about invariance then variant is that um whatever solution that you have um let's say we have some black box solution and we'll go over this for sure let's say you have some black box solution where okay you know let's say we sorted the queries already by the m's and what that means is that um what that means is that okay because if you think about it an m means that okay we only really want to consider you know for m is equal to one we really only want to consider let me just make this bigger uh we only want to consider the numbers that are zero and one right so we only process up to zero and one and then next you know the m is three so then now we have we had zero and one now we query we process the two and the three into whatever we're doing and then similarly once we get to six we go we uh we process the entire thing uh similar here as well let's just say we sort the numbers away as well obviously well one well then that means that we process nothing so this will probably be negative one and it should um let's say we have a three that means that we process the two and the three and then the four we process the four as well so basically that's the idea behind the offline is that um when you do the queries in a in an ordered structured way you can process the input the numbers also in that same structured way so that you just keep on building on top of it um so that's kind of the idea behind the offline algorithm i'm gonna go over the online algorithm and it should be mostly the same to be honest except for um a couple of easier uh simplification which i'll point out later so i'm gonna go over the online algorithm which is what i actually did which is that uh so on an online algorithm uh we assume that the things that don't change is the numbers the input array right so because that this doesn't change uh we should be able to pre-process this we should be able to pre-process this we should be able to pre-process this entire thing um all at the same time and that's basically the idea is that we will process this at the same you know one at a time or we process the numbers away the entire thing at the same time in the beginning and then we're able to answer this one at a time because there's no prior knowledge that um you know and why is this called online it's because in theory let's say you process this you can actually later uh still with the same data structure be like hey larry uh can you answer this query of ten and two or something like that right and then you'll be like okay i can still enter it because i still have to uh pre-processing done so that's have to uh pre-processing done so that's have to uh pre-processing done so that's basically what is meant by an online algorithm and they both have actually the same complexity roughly um the only thing is that if you do it offline um you will have to sort this away and also this array so in that sense um the online algorithm is actually more optimal um but okay i think i talked a lot about the difference between offline and online but i didn't actually go to the algorithm so let's go over it real quick uh so the greedy solution is just um like i said for every bit we um we take greedily the best on the most significant bit so let's go over the code real quick so with this solution we want to build a try up a try based on where the edge is whether each digit is zero or one and we process each number this way so for example for each number we add it to the try and for you to try let's look at the ad part um so we start at the root for the try we start the root and then we look at you know and i do this backwards because we want to focus on the most significant bit and what i mean by most significant bit is that okay uh if you have like a binary number uh like this uh if you just go from the back up that's not greedy in the right direction right you want to be greedy on the earlier uh bit because you know no matter what happens let's say you know even if this the rest is zero um and here the rest is one we clearly prefer this number because this is always going to be bigger than this number right in binary hopefully that makes sense and that's logic behind the greedy but for now we're just thinking about the try and basically we're doing it one bit at a time we're processing the try such that okay for you to for each number that we're processing okay so we have a try and then we just go okay um well this is actually a binary try so you could even think of it as going um one edge going zero from one side and one from other side so basically what i wrote is that okay so i add an edge with that bit if this bit is a one then i just go on i add an edge with the bit of one and then if it's zero then i add an edge with a bit of zero right and this is basic try stuff hopefully that makes sense and just to go over it because there is a little bit of a difference because i do it online which is that for me i actually keep a track keep track for each edge um the maximum number on that side of the subtree right and why do i do that right because uh oh sorry i think so actually this should be technically yi min uh the min number sorry um and the reason why i wrote max is because i missed about the problem and if you watch me solve it live during the contest i actually was confused about why i was getting wrong answers um until i converted to a min and then i changed the signs of some stuff because i'm just misread the problem so um but basically i keep track of the min on that edge because that means that um almost like in a forced contradiction kind of way if you go down that path and the smallest number is uh around that path will tell you whether it is possible to go down that path with a larger number right so basically what i mean is that okay let's say your query number is 10 but your edge um your minimum numbers on that edge is 11 that means that all the numbers that are on that edge you know in that subtree the smallest number will be 11 that means that if you have a 10 then you cannot go down this path because there's no numbers that goes down that path so that's basically the idea about uh keeping track of the men on the edge and um hopefully that makes sense uh i'm just thinking a little bit to see if i can explain this in another way that is um cruel but i think that's basically the idea right is that we keep the track of the min for that subtree because if your current number because you're for this problem you want to get uh any possibilities of you know like if we go down that subtree we want to know that it is possible to have a number that has a number that's smaller than the input number right so that's basically the idea about keeping track of the min and then the hash edge now makes sense in that okay first of all we have to obviously have an edge and if uh if we have an edge there we check that the smallest number on that edge is smaller than our query number which is the m that we're looking for um and then again edge is just getting edged so that's basically my library for node and then as i said add we just go down one bit by one bit we keep track of the x and then to get max is going to be the interesting slash greedy part where okay as i said if we have a prefix of one no matter what happens to the suffix it is still better so then we basically want to optimize for one right so given our current number and this x is the input that we're given uh is actually called x which is like the number that we're trying to get the maximum xor for so here we go okay if the number is of one well if this is a one and you know in the xor case if you have another one then it's going to be a zero and you don't want that so if this number is a one you want a zero so that the xor of those two digits will be a one so that's basically what my idea is and that you know this is the greedy way so if it's possible then we go we take an edge on a zero and then the result will have a one in it because uh because the one x or zero will be a one so that's why we have this here um and then we go to the next edge on this tree um but otherwise we just see if we can go down um uh the one path um in this case the xor on this uh digit will be zero but it's okay well you know you have no choice because there's no edge otherwise um if neither of those edges exist um then we just return negative one because well then it's not possible um uh and then you know inversely if uh if this current bit is zero and then you know to satisfy our greedy nature we need a one on the edge if we have a one then we just you know then the result will be a one and we do the same thing um otherwise we just take we'll take a zero if we can and then we move along other otherwise there's no edge and we return negative one so that's basically the idea behind this problem uh so this is the online version of doing it um again in this way um you know the add function is of um it's all of one kind of and that is of 32 where uh 32 is um you know log of 10 to the 9th roughly speaking i guess it's 31 but uh or dirty actually but maybe i could have done that to be faster but in any case um but yeah so and that is just the 10 to the ninth part so basically is the log of that um so it's basically n log u in that case where n is the number of numbers so um yeah and here it will be uh q log u for the same reason because we look at it for each bit we run the query right so and in total this is going to be o of uh n plus q times log u and just to be clear uh so time is equal to o of um n plus q log u right um and then the space is also going to be just uh n log u for that reason because we only preprocess the space for the input numbers so what changes would i have to make this offline right well first of all as we said we have to sort numbers and curries so at the very least um our thing will be uh n log n plus q log q plus um again uh for each query and number we will have to go through um the log u bits as we still use the try so it's going to be n plus q log u so it's strictly going to be slower for space it should be the same so if we unlock you unless you want to count sorting uh you know and as you want to count sorting the q arrays and the n arrays then maybe then because technically then you're modifying input so uh so that's the space for the uh offline version uh complexity and the online complexity is this version um so how would you do it on offline right so offline as we said you saw this and then for each query you basically processed the numbers you added to the try um so that you added to try if the numbers are smaller than um the m that is in the query um and that's pretty much it uh the only thing you know all the code will look about the same the only thing that's different is that you don't have to do this uh etch min thing you don't have to do this check and therefore you don't need to keep track of it um so maybe it's a little bit easier in that way to write this part of it and it's easier in terms of proving it in terms of invariant because you know you just burn your tree uh knowing that the tree or the tri sorry um knowing that the tri will only have numbers that are smaller than m so then you know that invariant will be true no matter what right so that's basically how i explained q4 um cool um let me know what you think about this problem it was okay but um like i said in unfortunately in uh python it was too slow um but i wrote the same code in c-sharp and it i wrote the same code in c-sharp and it i wrote the same code in c-sharp and it passed this is roughly my c-sharp code uh it this is roughly my c-sharp code uh it this is roughly my c-sharp code uh it took me an additional 17 minutes uh so i'm a little bit sad about that but um but yeah uh that's all i have for this problem uh same complexity obviously for c sharp uh let me know what you think and you can watch me stop it live during the contest now this was a hard contest still i still don't know how to do this one i had to think about it m so this is the tri problem annoying but two of us you a little rusty about it to be honest so this might take a while but let's solve this on code force at some point because i'm just thinking about how to do this for solving it each node or to try what do we want to do to get the car i just um doesn't make sense does it on a path so maximum order path i think that makes sense okay um i don't like this uh this is so yucky it's all implementation the most significant bits first okay hmm you okay zero ah this is a little yucky but silly mistakes today in general down this is our zero so this is the one okay not close hmm what is that i expected that bit okay hmm up i must start oh that's all okay i think i got it well i mean might still be wrong but um it's too well so i don't even get seven there's a negative one right nope oh this is smaller than or greater than whoops oh i messed up okay uh how did i change it do we still have to get the max number yeah okay i don't know if this fixes it though how many prints come on please don't be too slow hmm how can it be too slow it's just hmm i mean it's only too slow um it's only too slow because of uh python i think this is so silly because it's just 32 times 10 to the fifth which is should be fast enough i don't get it can i'm just looking at my power angle so i could optimize anything constantly not really nor should i really need it to be uh so that's a little bit unfortunate and 40 people got in it already so i think a lot of people finish this contest already so uh okay so oh this is so annoying because i'm basically spending the time rewriting this problem or rewriting the solution and my c plus has been let's see i don't haven't done tries in c plus first in a while so that's why maybe doing java don't know if i know enough java is that one no hmm okay so oh yeah of course i haven't done c plus pressing a lot or uh i haven't done this in a long time so c sharp in a long time uh i hate this hate every bit of this all right too uh and i didn't even finish q2 so i this is just a mess this is so stupid oh my god i'm just so unhappy about this um i'm trying to also not use dictionaries that's why what am i writing uh i forgot to see my golems hmm why is this not compelling oh this is not long i don't know anymore okay so you okay don't just know uh management this is ridiculous can we do better than linear time so all right it'll be funny if this is also too slow because i actually don't know how fast uh c sharp performs uh on the code i actually didn't think about it at all so that would be really sad um 64. oh my i hate everything 64 what so um oh my god what am i doing okay i don't remember that's quite right something like that though 179 now my computer is being slow but of course why not come on this is not the time for my computer to be slow i didn't think this would be the point i'm having issues with to be honest but uh okay um i'm being dumb really you if this is too slow i'm gonna be unhappy about it because i spent half an hour on this uh hey yeah thanks for watching the video uh let me know what you think hit the like button to subscribe button have a happy new year and i will see you next time bye
|
Maximum XOR With an Element From Array
|
check-if-string-is-transformable-with-substring-sort-operations
|
You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.
The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`.
Return _an integer array_ `answer` _where_ `answer.length == queries.length` _and_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** nums = \[0,1,2,3,4\], queries = \[\[3,1\],\[1,3\],\[5,6\]\]
**Output:** \[3,3,7\]
**Explanation:**
1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
2) 1 XOR 2 = 3.
3) 5 XOR 2 = 7.
**Example 2:**
**Input:** nums = \[5,2,4,6,6,3\], queries = \[\[12,4\],\[8,1\],\[6,3\]\]
**Output:** \[15,-1,5\]
**Constraints:**
* `1 <= nums.length, queries.length <= 105`
* `queries[i].length == 2`
* `0 <= nums[j], xi, mi <= 109`
|
Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering.
|
String,Greedy,Sorting
|
Hard
| null |
34 |
hello everyone let's look at five first and last position of element in sorted array the problem statement is we are giving an array of integers norms sorted in ascending order we want to find the starting and ending position of a given target value if not found simply return negative one when follow-up challenges can we do that when follow-up challenges can we do that when follow-up challenges can we do that with the time complexity of o log n let's look at example one the input number is five seven eight ten the target is eight the output is three and four that's the start index and end index for this two eight and for the second example input is five seven eight ten the target is six is not one of the element for the input array we simply return negative one and third example if the input the length is zero and we simply return negative one and because of time complexity here we should use binary search and one solution is to run the binary search twice to determine the first position and last position let's look at the code let's try to first write down the standard binary search solution to have a basic structure so because we have these norms lens minus one let's also do a lens check in the first place this is our basic binary search the idea is we run this piece of code twice obviously not exactly the same piece of code we run this basic binary search twice to find the first and last position however the problem here is in the input array it has duplicate elements so we need to do extra step to move our left or right pointer let's say we want to find the first position that's our left boundary the key point is how do we handle the case if target equals norms meet obviously we don't want to stop the loop we don't want to return it we want to move actual steps let me say that again we want to move extra steps we'll make sure this mid value keep pushing to its left the same thing is two we need to make this right value smaller that means when target equals snaps we want to keep moving our right left so we can simply do this so when they equals or less when target equals or less than nums mid we make right move left and in the end after the while loop our left boundary is our left variable let's give them a name let's call them low and high and in the end our left boundary low is left you might wondering why low value is equals left why not right let's look at the last situation in the last iteration left equals right and the value for mid is also equals left equals right and if target value is in our input noms that means this if condition definitely means target equals norm's mid and then if that's the case the right keep moving left that's why this low value should be left because the left didn't move at all it's still point at the last value and let's look at the second one let's first reset the left value and y value let's also copy this whole thing and in the end our height is right here's something we need to change so if the target value equals num's mid what do we do i think for this case instead of moving right we're not moving left so if target value equals now smith we want the left value keep pushing right that's how this mid value get bigger and reach its right and in the end we can simply return low and high but we need to do another check if low value and high value actually make sense so if low value is less or equal than high value that means we actually find some we actually find the element in the input array otherwise we simply return negative one let's try to submit a passed let's look at the complexity here for thai it's login for space is constant and for this piece of code some other people they will put the spine research into helper method and then simply return its left boundary and right boundary but for this i will leave like this if i didn't make this clear feel free to re-watch this video if you feel free to re-watch this video if you feel free to re-watch this video if you have any other questions please leave a comment below thank you for watching
|
Find First and Last Position of Element in Sorted Array
|
find-first-and-last-position-of-element-in-sorted-array
|
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`
| null |
Array,Binary Search
|
Medium
|
278,2165,2210
|
140 |
take a look at a legal problem called word break number two so given a string s and a dictionary of strings word dict um add spaces in s to construct a sentence where each word is a valid dictionary word return all such possible sentences in any order so note that the same word in the dictionary might be reused multiple times in the segregation so basically what it means is that we can be able to use the words in the dictionary multiple times to form different uh combinations right so you notice that we're returning a list of string so in this case you can see here i can be able to uh take the string right this is our string input like i can be able to form or i can be able to split between here so between cat and the rest of the string and i can also split the string right here you can see i have cat sand dog cats send and dog they all contain in the dictionary so that's one combination right and what i can also do is i can also form cats which is also contain a dictionary and it's also contained in the dictionary dog is also contained in a dictionary so you can see here this is also another combination right so in this case you can see here we're returning a list of string which contains all the combination that we can generate that has all the words in the dictionary um and then we're basically adding a space um between those words right to form where all the characters in the strings are in the in s right uh except the spaces but basically you can see we can be able to uh construct a sentence using each word in a dictionary right so in this case you can see here um we can also have another example right we have a pie apple pen apple right so pineapple pineapp pineapple or something like that so you can see here i can basically split between pine right so pine that's is contained here apple is also contained here pin is also contained in here and an apple is also contained here so note that you are allowed to reuse a diction a word in the dictionary so i can reuse apple multiple times right um so and i can also have pineapple which is also in the dictionary right i can also have uh let's see pen and apple right pin apple right so it's in the dictionary and you can see here i can also have pine and apple pen and apple right so we can see pine apple pen pine right so they're all container dictionary so these are all three combinations that we can generate and again at the end we return in a list of string now another example you can see here is cat's cat sand dog but you can see here that there uh there's cats right and there's and right so if we have cats and but the rest of them is og there's no og in here right so we cannot be able to form a combination in this case if i split here so in this case i have cat and i have send right in this case that's not going to work so in this case we still have og at left no g is not in the dictionary so therefore there is an empty list right we cannot be able to generate anything right so in this case how can we resolve this problem so let's say in this case uh the brute force approach right in this case if we want to solve this problem using a brute force approach basically what we're trying to do is we're trying to split each and every single position right so if i put a line right here right i check to see if this character contains in the word dictionary in this case it doesn't right so we continue so i split here i check to see if this charac if this string right here contains in the dictionary in this case it doesn't so then i split here i check to see if this string contains in the dictionary in this case it does okay so once i know that this string right here this part of the string contains in dictionary then i also basically do the same thing right or in this case for the remaining substrings right so for the remaining substrings i have sand so i have sand dog right and then for send dog i do the same thing i split here is your s in this in the dictionary in this case it doesn't right and then i split here i check to see if s a is in the dictionary if in this case it doesn't say n doesn't so all the way up to here in this case you can see we have sen in our dictionary okay so then what we do is we do the same thing for the remaining substrings right so in this case we have dog so in this case d we don't have it do in this case we also don't have it in our dictionary dog we do right so in this case what we're going to do is we're going to add this as one combination right there could also be other combinations maybe in the dictionary there's also a string of do right so d o so in this case what we returning back is a list of combinations that we can generate so you can see here after we know that dog is or in this case for this substring uh the total possible sentence that we can generate is dog right in a list then in this case we know that s and d right sand is also in the dictionary so this will be a one combination right so in this case what we're going to do is we're going to add a combination so which is s and d with a space right and a dog right and then you can see here this is one combination so you can see here we can also um put a or in this case we can try to split between s a and d right so i can also split between here right s and d is not a it's not in the dictionary s a and d o is not a dictionary s e n d o g is not in the dictionary so in this case uh we just have to return this only this one combination right so in this case you can see here once we know that there's this one combination for this substring right this is the list of them then you can see we're just going to uh concatenate the cat appended out to here right so in this case this is our list right so that's like one combination right you can see every single string or every single word is separated with a space right so in this case you can see i can also split here right and i know that for this string right i can also split here right and then you can see we're basically doing this dfx uh dfs right so i have a and d dog left right so in this case i split to see if this is contained in the substring or the contain in the dictionary up to here we know that a and d is actually in the substring or in the dictionary so then we do the same thing for the remaining substring in this case dog but you can see the dog is already contained it's already computed before right we know that total number of combinations that we can generate for dog is just one and then there's this one list right here so we can do so we can basically use some kind of like caching to cache this right and just like this we're just going to return a list of combinations that we can generate which is just dog and then here we know that end right a and d is contained in dictionary so it's basically just going to be returning one combination which is just you know a and d space right dog right which is basically a list only contains one element in this case we're going to return back we know that cast is contained in the word dictionary and this one right here is also uh in the uh in this case it's actually in the dictionary which is also a valid combination so we're gonna combine that right so that's one combination and then we keep splitting we split here right so in this here and they're not like all they're all of them are not valid combination so at the end we're basically just returning the list that we have right because like here they're not in the com they're not in dictionary here they're not in the dictionary here's they're not in the dictionary this substring is not in the dictionary and so does this one right so at the end we all the way to the end also all the way to the very end checking the entire word to see if this word is in the dictionary in this case they're not then we're just going to return what we have right to the uh the function so that's basically how we solve the problem but there's also a couple base cases right so let's say we're dealing with a situation like this right so in this case you can see if i draw this right i know that if i split here there's no c in the word dictionary and then i split continue up to cats or cats first i know that cat is containing dictionary so i have s a and d o g right that's the remaining substring that we're checking right so and then we know that we split here all the way to sand we know that sen is contained in dictionary so in this case we're you know we got og left right so o is not in the dictionary g is not in the dictionary an empty list right so in this case what we do what we have to do is that if we're returning empty list and we know that the remaining substring is not a empty string right then what we have to do is that we have to return a you know empty or in this case we're not we have to continue to split right or try with other combination maybe we're trying to see if s a and uh s and d o contain a dictionary in this case s n d o is not right s t s a n d o g it's not in the contained dictionary so therefore we have to return the empty list back to the root saying that this substring there's no combination we can generate right so in this case what we're going to do then is we're going to backtrack we're going to try to split here in this case we know that cas is in a dictionary so we're going to go for a and d og we know that a and d is also in the dictionary so we check the remaining substrings in this case we already know we already compute that og is not there's no combination we can generate for og we can basically cache this so we're going to return an empty list so in this case we know that hey n is in the word dictionary but the size for this substring right here is actually more than zero so in this case uh and there's no combination we can generate so we have to try with other combination right so maybe we can split maybe like between this one right so in this case this is not in the substring where this is not in the dictionary and then we check the remaining sub uh the entire substring in this case or the entire string or the entire substring uh there's no word in the dictionary so we have to return an empty list and therefore you can see here we're basically just returning empty lists right um so you can see here what i did first is i basically put this in the hash set right this dictionary in the hash set i convert this string to an array and then we're calling this dfx function right dfs function we basically go from a top down approach and then you can see here i have a cache that the key is basically a string and then the value is basically the list of string so what i did here is i basically check to see if this is an empty string right then we can just return an empty list that's kind of like our base case there and then what we do is that we have our string builder right and then we have our results that we're going to return for this recursion stack and then you can see here the key is basically just going to be like the index right so index right here is zero right or zero five or not zero but like zero five or zero to ten or something like right we're basically checking to see for this entire string from starting from the start to the end how many combinations can generate and that's what this function is kind of returning and you can see here that um i basically first check to see if this is our key right we check to see if this contains it if it doesn't contain their cache so if it does contain our cache we would return that if it doesn't we're going to iterate through all this all the combinations right all the splits that we can generate in this case if i split between c and a right if i split between uh you know a and t right which in this case we basically check right so we append each and every single character onto the string builder we convert it into a string and then we check to see if the dictionary contains this current string if it doesn't we continue if it does all we're going to do is we're going to call this dfx function right this dfs function returns the list of remaining strings right that we can or total or all the strings that we can generate uh for the remaining strings right for the remaining substrings the total all the combinations that we can generate for the remaining strings and then what we do is we do our check here right just like our third example that we just talked about right if um you know if the size of the remaining substring is more than zero and there is no combinations we can generate then we have to continue because we can't we have to use all the strings that we have right so but in this case if this is not the case then what we have to do is we have to generate get all the or generate all the combinations right because there could be a situation where there are multiple combinations so i can have like maybe a and d cat or something right and i can also have a n d cat right or i can have like something like a space and d cat something like that and then i have just one in this case dog right this is like dog is like the uh the start right the kind of like our current string and then these are all the combinations so basically what we're trying to do is we're trying to generate all of them and then add it onto the result list so that's basically what we're doing and you can see here if the remaining substrings length is zero in this case we just have to add the current string right so at the end you can see here once we form all the combinations for the current substring um we're gonna uh save it in our cache and return the results right so this is basically like kind of like what i did for my initial uh solution now let's take a look at kind of like a cleaner solution right so cleaner solution is kind of similar to what i did but um basically you can see here what i did is i have well same thing i have a set right i insert it onto a hash set and then in this case i have a map right this hash map is basically using as cache right and then you can see here there's many ways you can cache this you can use like indexes to as a key or you can also use like kind of like a um a prefix of the string as a key right so you can see here for this dfx function right we same thing we're returning a list of strings that this current string uh can generate right all the combinations of sentences that this current string can generate and first what we do is we check to see if it can already be in cached if it's cast with casually return that and then what we do is we create our list and then if the string.length right list and then if the string.length right list and then if the string.length right if this is an empty string like if our string right now our substring is empty then we're just returning a list with only containing empty string right now the reason why we do this is because you can see here at here right like this is what we're calling this and then this is a list of substring we have to if there's some if uh if the current string right if our current string is actually contained in the word dictionary like let's say if our current string is cat and cat is containing the word dictionary so we also have to iterate through that word cat right we all not iterating but like we basically have to add cat onto the result so in this case if i have an empty string right if this is a and if this is uh so in this case if the list sub list right so the sub list is basically this one right here sort of sub substring is empty string right then we can just have this right otherwise we can just have a space right and then we just append it if it's an empty string of course then we basically just have this word itself right if it's not an empty string for our substring in this case what we're going to do is we're just going to uh add a space and then plus the uh the current combination right so in this case we're just going to save it onto the results and then we save it on the cache and we return the result right so you can see here it doesn't really matter which solution you go with um either the cleaner one or the little more messy one but basically at the end the time complexity is still going to be exponential right
|
Word Break II
|
word-break-ii
|
Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "catsanddog ", wordDict = \[ "cat ", "cats ", "and ", "sand ", "dog "\]
**Output:** \[ "cats and dog ", "cat sand dog "\]
**Example 2:**
**Input:** s = "pineapplepenapple ", wordDict = \[ "apple ", "pen ", "applepen ", "pine ", "pineapple "\]
**Output:** \[ "pine apple pen apple ", "pineapple pen apple ", "pine applepen apple "\]
**Explanation:** Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** \[\]
**Constraints:**
* `1 <= s.length <= 20`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 10`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
* Input is generated in a way that the length of the answer doesn't exceed 105.
| null |
Hash Table,String,Dynamic Programming,Backtracking,Trie,Memoization
|
Hard
|
139,472
|
318 |
hi everyone so today we are here with the new lead code problem and that problem name is maximum product of word lines so in this problem we have an array which is a words array and this array contains strings let's suppose a b c d e f g a let me add more abd right so what we do we basically consider two word two string from this array let's suppose if i consider this and if i consider this d e and a b d so what we have to do first we have to check in these two strings there is no common character but as you can see there d and d is a common so we can't process it further let's take another two word having uncommon character let's suppose this so d e and f g a now you can see that there is no character present in this string which is also present here then we have to find its length which is true and its length is three and we have to multiply it and we get six now we have to find the maximum value by taking two word from this array such that there is no common character between these two strings and we get the maximum value so is that 6 is a maximum value no because if we take f g a and a b d in that case you can see a is common so we can't consider it uh yes so it is i think uh so that six is the maximum value right but let's suppose if the value we have is something like e c m so we can consider f g a and e c m now its length is three its length is 3 and if you multiply it we get 9 in that case the maximum value we get from this array is 9. now how we can solve this so if you see this problem very closely there are two things first we have to find whether this string one and string two contain any common character or not and the second thing we have to find the solution which is length multiplication right now the first way to find is there any common character or not what we do as a brute force let's suppose if we have a b c and if this string two is d e f what we do we will make a pointer at this character and we will check whether a is present here then we take a pointer at b and we'll check here and similarly for c in that case we have an approach of we go off and square because for each character we have to check this string as 2. and yes this is not an optimized solution so in order to resolve this what we use a hash map right we use a hash map of s1 and s2 and we can check in we go off when whether these two strings contain any common character or not and if and then what we do if this is the array for each string we will find a hash map and then we will make a pointer at this position and check for remaining strings if we get another string which contains no common character we will find the answer how simply by multiply their length and we take an variable answer in starting it contains 0 and then we will update with the maximum value okay but i am going to solve it using a different data structure and that data structure is set so what this data structure do if i take any string let's suppose a b c and if i give this string to this data structure i get values like a b and c so this data structure basically remove all the duplicates values in it so what i do for all the strings in the array i create a set for each string right and then we will check whether for any two string whether it contains any common value or not how we can check this simply by doing an add operation so how this set behaves for and operation so let me take an example so let's suppose if i have a set which is abc and if i is set which is d e f right so if there is no common character as you can see a b c and d e f there is no common character in that case we get resultant as an empty set okay and let's suppose if i have a b c and d b c in that case we get b and c so we are looking for this if we do add operation between two set values and if we get an empty set it means that there is no common character in it and for these two strings we will get the answer simply by multiplication its length and update the answer variable so let's see the code and then you will understand it more so what we do i will basically use an array and this array contain set value for each word okay so for each let's suppose if i take this a b c w so we get a set value for this and for all the strings and this is the variable answer and we will have iterate uh like we will have to create a nested loop because we have to check for each string and if we do the and operation between these set values and if we get an empty set it means that there is no common character in it and then we will multiply its length and will update with maximum value at the end we will return the answer i hope you like this problem and if you like please like share and share with your friends bye
|
Maximum Product of Word Lengths
|
maximum-product-of-word-lengths
|
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`.
**Example 1:**
**Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\]
**Output:** 16
**Explanation:** The two words can be "abcw ", "xtfn ".
**Example 2:**
**Input:** words = \[ "a ", "ab ", "abc ", "d ", "cd ", "bcd ", "abcd "\]
**Output:** 4
**Explanation:** The two words can be "ab ", "cd ".
**Example 3:**
**Input:** words = \[ "a ", "aa ", "aaa ", "aaaa "\]
**Output:** 0
**Explanation:** No such pair of words.
**Constraints:**
* `2 <= words.length <= 1000`
* `1 <= words[i].length <= 1000`
* `words[i]` consists only of lowercase English letters.
| null |
Array,String,Bit Manipulation
|
Medium
| null |
70 |
hey yo what's up my little coders let me show you in this tutorial how to solve the lethal question number 70 climbing stairs basically you're climbing a staircase and it takes n steps to reach the top each time you can either climb one or two steps in how many distinct ways can you climb to the top here some examples however i will skip them because i prepared my own examples right if n is equal to one how many distinct ways they are to reach the top if you can only do like one or two steps they're basically only one distinct way so you just do like one step and you reach the top if n is equal to two there are two distinct ways you can do like one step plus one step or second option is just to do two steps at the same time and you reach the top we return two here if n is equal to three there are two distinct ways one plus one or two plus one or one plus two here we will return three n is equal to four there are five distinct ways so we can do one step plus one step was one step plus one step or the like two steps plus one step or like one plus two plus one or one plus two and two plus two in total there are five distinct ways to climb to the top if n is equal to four right and it's equal to five okay they're a bit more distinct ways they're eight in total okay i will not go through for them there are too many of them but here just believe me there are eight distinct ways to you know to climb the top if n is equal to five now what it all means guys now let's think about how can we solve this problem look at this you know answers for each n value from one to five just pause this video look at this return values and think a bit do you see any patterns here just pause the video okay cool if you pause the video i hope you figure out it yourself in case if you didn't basically okay we calculate n is equal to one and n is equal to two then if you look at n is equal to three so we need to return three right but three is also the same as you know the sum of two previous values and is equal to two is fact two we do like 2 plus n is equal to 1 is 1 so if we do like 2 plus 1 we get 3 as well if you look at n is equal to 4 we need to return 5 but you know if you look at the two previous return values and if you do like if you sum up them together three plus two we also get five same for n is equal to five so five plus three is equal to eight and here we need to return eight and basically yeah this is the algorithm if you calculate the first you know two values for n is equal to one and then it's equal to two and then like to calculate the next value you just sum up the two previous values okay so you found the answer then you move to the next value you sum up the two previous values and you know until you reach your end value you solve the problem by splitting it up into subs into some sub problems and by solving the sub problems you will solve your final problem in the end as well and they're basically a lot of ways how can you code it so you know so the sub problems first and then solve the final problem i will show you two ways how we can solve this problem the first approach is to use the dynamic programming let me just quickly write the code for it will be a short one and then i will go through it with you in a few seconds here we go guys here's the base case if n is equal to one you just return one because there's only one distinct way then you create your dp array because it's the dynamic programming approach you create your gp array of size 10 plus one you'll use this dpr8 to basically you know calculate all the sub problems then after that we calculate our first sub problems for n is equal to one and n is equal to two and here the return values for this sub problems after that we'll iterate from 3 up to n including the n value itself and then we just simply say that you know the current value is equal to the sum of the previous value and the previous value we sum up them together and you know we'll iterate through from one from three to n including the n and then we just return our last value from the dp array we should represent the amount of distinct ways to reach the top four value n simply as that guys okay what must have been the code cool hundred percent zero milliseconds and yeah this is one possible approach how we can solve this problem elsa the second possible approach if you look at this sequence right one two three five eight if you remember from your mathematics classes from the school i don't know it might look very familiar to you because it looks very similar to the fibonacci numbers just with one difference in fibonacci sequence you have like two ones in the beginning but no in this climbing stairs sequence you have only one volume but yeah apart from that is basically the same so 1 2 3 5 8 13 21 and so on so 1 2 3 5 8 13 and 21 and so on as well we are just missing one value in the beginning but it doesn't really matter the second approach would be to just implement the you know to calculate the fibonacci number basically the fibonacci of n okay let me show you how to do it let me just write the code quickly for you guys and i will go through it with you in a few seconds similar technique here just the only difference here not using the integer array we just are using some variables to do basically the same stuff there are two base cases n is equal to one return one and is equal to two we return two right after that we declare three variables the current integer to calculate the current sub amount so the sub n value after that we have like the previous number and the previous number similar for loop so we are starting at i is equal to 3 and you know we'll iterate up to the end value including the n itself and then we update the current value it's basically equal to the two previous numbers and yeah we need to update the previous numbers as well because you know on the next iterate on the on each iteration of the forum you know the previous values change a bit previous two is equal to previous one the previous one is equal to the current then we'll go to the next iteration of the for loop and the current will be a new current and so on yeah but the algorithm is the same you just like sum up the two previous values and then in the end just return like the current which will represent you know once you iterate until the end which will represent like the n value and the amount of distinct ways to climb to the top giving given this end value simply as that guys let me just submit it 100 as you can see here the memory usage is a bit lower we don't use the any extra space in this case so we don't declare the integer array so we got a better result for the memory usage which is quite good but yeah guys simply as that i don't think that i have anything else to say i hope it was clear if you enjoyed this tutorial please guys please give it a like and subscribe i really appreciate that and challenge your friends to see if they can solve this problem or not and i will see you next video guys good luck
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
1,209 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem remove all adjacent duplicates in string we're given a string s and we're also given an integer k and we want to make a k duplicate removal on the string s as many times as we can basically until we can't do it anymore what exactly is a k duplicate removal basically k is going to be an integer in this case it's 3 and a k duplicate removal is basically removing a portion of this string where there are three consecutive characters so we can see that's happening here there's three c characters in a row so we're gonna do a removal like that now are there any other parts where that's going on well there's three e's in a row so we remove all three of those as well are there any more three consecutive characters left you might think there's not but let's actually rewrite the string because as we remove characters we're actually changing the way this string looks and when you actually rewrite the string you can see that there actually are three b's in a row now that wasn't the case originally but as we removed some characters there and removed some characters there then these groups of characters basically combined and now we have three b characters in a row so now we're going to remove those and then after we do that we're going to have three d characters in a row since this hole is removed that means these groups have been joined together so three ds in a row so we're going to remove those as well and then we'll be left with two a characters in a row and at that point of course we won't be able to do anything else so that is going to be our result in this example so one thing to notice about this problem is the order that we do the removals in is not going to matter at all because if we have a group like this three b's we don't have to remove it immediately there could be some other characters maybe there's three c's over here or some other group in the entire string we can do this removal whenever we want because it's true that when we do a removal we're making other groups join each other so then we're gonna introduce new groups that have three consecutive characters or whatever k happens to be k could be more than three it could be less than three but as we do a removal these groups might join together but there's no way that this group of three b's is ever going to be separated until we actually remove it there's nothing we could do we could remove any character over here or any character over there we're never going to separate this group of bees and in this case it's three b's but it could be a thousand b's so it doesn't matter what order we do the removals in also an immediate solution you might think of is just first scan through the entire input anytime we find a group of k consecutive characters we do a removal and then we know that the string is going to be updated to look like this now and then we would scan through the new uh string and then do the same removal if it's possible for us in this case it is but you're going to notice that in this case we're having to scan through the entire array which is let's say size n the entire string and then we could in the worst case have to do that maybe n times or something like that would be an n squared time complexity solution so the question is can we do better and the answer is definitely yes let me show you how first how are we even gonna identify this group of three consecutive characters let's say in our example k is equal to three well we're going to iterate through the array we could count okay one c so far then we're gonna get to an a one a so far two a's so far is there gonna be a third a nope we have a b now one b two b's three b's so we did count to three b's that means that we're going to remove these three characters and after we do this removal we know that we're going to be joining this part of the string with this part of the string and at this point the naive algorithm would be to start back all the way at the beginning and then iterate through the entire string again but the question is that required for us if we just removed this where would it possibly be that we introduced a new consecutive three characters it's not like we're going to introduce them all the way at the beginning we would only do that by taking this and combining it with this so we only need to check if we introduced three consecutive characters in the middle and how would we do that well we would take a look at our next character that we're getting it's an a and we would check what were the characters that came before there are also a's how many were there were two so that means we do have three consecutive a's now so now we would do another removal but hold on and then we would be left with something like this and again we would repeat the same thing the next character we're looking at is a c here we would say okay what was the character that came before it was also a c and then we're gonna have a third c here so now we're gonna do the same removal so as you can kind of see we are going to have to look backwards we're not going to be starting all the way at the beginning and then going forwards we're actually going to be going from where we are and then looking backwards because as you could see first we got a c an a then we got three b's and then we removed the three b's and then we had an a c and a and then we got a third a and then we removed the three a's and then we are already had a single c and then we added two more and now we're going to remove all three of them this is reminiscent of a stack data structure because we're always going to be removing from the most recently added characters so the way i'm gonna be setting up the stack actually is going to be taking uh the character and then mapping it to the count of that character we don't necessarily need to i think we could get roughly the same time complexity just by adding each character to the stack but it makes it a little bit easier to keep track of the count of it because then as soon as the count reaches k we know that we have k consecutive characters and then we can immediately do that removal so what i'm gonna do is start at the first character a c is this on our stack yet nope so let's add it to the stack we're adding the character c a count of one so far then we're getting uh to the second character a is this the character that we previously added nope so we're adding a new character a it has a count of one we're adding a second a so we're changing the count of a now to be two because it's the same as the previously added character next we're adding a b so that's not on our stack yet so we're gonna add uh b count of one and then of course we're gonna add a second b and then we're gonna add a third b so the count of b is gonna be three as soon as the count of a character at the top of our stack is equal to k we can go ahead and remove that character now removing from the middle of a string would not be super efficient but removing from the end of a stack is much more efficient so all we have to do is pop this from our stack that's an o of one time operation and pushing to a stack is also an o of one time operation so now we're going to add a we're gonna look at the top of our stack a is on the top of our stack we previously added two a's right we're basically pretending like these b's never existed which is correct because they pretty much don't exist anymore so if we have one a here and two a's over there that means we have three consecutive a's so let's take the count of this a over here and make it three and we know as soon as we do that we are going to pop this because three is equal to k and we know that's three consecutive characters we can remove them so we're going to pretend like these characters never even existed now we're going to get to the next character it's a c the top of our stack is a c so we're going to increment this to be two now sorry if my handwriting is a little bit messy but that's a two next we're gonna add the last character which is a c so now we're gonna have three c's and so once we reach that magic number we know we're also going to pop now so we're going to pretend like these characters never existed because these three c's are consecutive right because these are deleted so we have three consecutive c's we pop that and then basically the result is that we're left with an empty string because our stack is empty now and then we would return this as the output but it might be possible that suppose we didn't actually have this third c character then we would have had two c characters right this is what our stack would have ended at two c's and then we would take this stack and then convert it back into a string and that string would be just two c's right because after doing all these deletions we're left with cc and then that's what we would return so you can see that in the worst case we're adding every single character to the stack and removing every single character from the stack so that would be an o of end time operation to add every character plus big o of n to remove every character so the overall time complexity is 2n which is still linear time complexity the space complexity is also big of n because we're using the stack as extra space so now let's code it up okay so now let's code it up you can see i have a stack in this case i'm using an array and it's gonna be a pair of values the character and the count if you're doing this in other languages you could use two stacks two arrays one to keep track of the character one to keep track of the count but in python we can add pairs of values and i think it's easier to do that so then we're just going to iterate through every single character in the string from left to right because remember it doesn't really matter what order we go in we're going to check if our stack is non-empty and if our stack is non-empty and if our stack is non-empty and if the character that we're right now we're at well the top of the stack first right we're looking at the top of the stack we can do that with the negative one index in python and we're looking at the first of the pair we're looking at the characters so we're going to take zero is that equal to the current character that we're at if it is then we know we can actually increment the count of that character by one is the second value of the pair which is the count so we're going to take that and increment it by one if it's not the case either our stack is empty or this is not the same character at the top of our stack then we're going to append to our stack uh this character and we're going to give it an initial count of one that means we have one consecutive of this character now it's possible that the count of that character just reached k we can tell that by checking okay the top of our stack and the count of it is it equal to k if it is then we pop that from our stack now the other cases are that it's less than k if it's less than k we don't do anything you might be thinking what if it's what if the count of it is greater than k then wouldn't we want to decrement k from it my answer to that is it's never going to be greater than k because we're only incrementing the count by one every single time or just initially setting it to one so if it ever reaches k then we're immediately going to pop it's never going to be larger than k we're not going to let that happen so after that said and done we removed all uh duplicate k characters and then we're going to actually take our stack and then convert it to the result string so the easiest way to do that is just to iterate through our stack we're going to iterate through the pair of characters the character and the count we're going to iterate through the pair of values on the stack the character and the count we're going to append to the result this character and then we want to make this many copies of that character in python it's actually pretty easy you can take the character and then multiply it by a number and that'll basically take you know if this was a and this was three it'll create three consecutive a's you could also use like a nested for loop if you wanted to but now that we've built our result string we can go ahead and return it and now let's run it to make sure that it works and as you can see on the left yes it does and it's very efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot if you're preparing for coding interviews consider checking out neetcode.io it's a free checking out neetcode.io it's a free checking out neetcode.io it's a free resource that i created and hopefully i'll see you pretty soon thanks for watching
|
Remove All Adjacent Duplicates in String II
|
design-bounded-blocking-queue
|
You are given a string `s` and an integer `k`, a `k` **duplicate removal** consists of choosing `k` adjacent and equal letters from `s` and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make `k` **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It is guaranteed that the answer is **unique**.
**Example 1:**
**Input:** s = "abcd ", k = 2
**Output:** "abcd "
**Explanation:** There's nothing to delete.
**Example 2:**
**Input:** s = "deeedbbcccbdaa ", k = 3
**Output:** "aa "
**Explanation:**
First delete "eee " and "ccc ", get "ddbbbdaa "
Then delete "bbb ", get "dddaa "
Finally delete "ddd ", get "aa "
**Example 3:**
**Input:** s = "pbbcggttciiippooaais ", k = 2
**Output:** "ps "
**Constraints:**
* `1 <= s.length <= 105`
* `2 <= k <= 104`
* `s` only contains lowercase English letters.
| null |
Concurrency
|
Medium
| null |
33 |
Hello guys welcome back to back door and this video will see the sachin rotated software problem which is from list to dean of the series coding challenge so let's look at the problem statement problem ever originally posted in this has been rooted in the element of this you Need To Find The Length Of The Element Otherwise Elements Present In Them One Day They Can Apply For Brain Research And Development In Just Log In And Take Preventive It Is Not Properly So They Can Still Alive and Pure For Things Which We Can Do It Is the Element Which Sexual Actually The Best Elements of Obscuritism Simply Important Observation for Solving Problems Subscribe Not aware of this fact that depart from 28th Graphs in increasing order from 023 Laga features in increasing Order but in between this to point 600 subscribers reduced visually android element this channel subscribe to The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing video that will find for the best element so will take medicine festival that is The left and right nor will find that subscribe 2017 to the property of but element The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing and also present on the right side of the seven eight to the Left Side And You Can Forget You Just Need To Compare To The Value Of The Current President Loop Dhandhe Subscribe 0 subscribe this Video plz subscribe button Right Side Will Have To Divided Into Two Parts Partition In Uniform For The Obscene Issue Meet Value Of Compare With Left Value Dangers Cash Withdrawal Luis Lu Dis Is Not Uniform Increase In Its Present In The Laptop liked The Video then subscribe to the Page if you liked The Video then subscribe to the Page that in which of Deposit For all know where to check in water in this target elements calling so will compare with the left acid polling in the laptop from left to development as its great think they should select element to subscribe The Video then subscribe to the Page if you liked The Video then subscribe to subscribe the Channel and subscribe the Total Time Complexity of Two Boys Page Subscribe Now to Receive New Updates Reviews and News Second Address in the First Here They Have No Limits of Years into Two Parts in This Will Be Id List Here- There therefore subscribe thank you can see and difficult increasing was or right side uniform divided into two parts subscribe thank you August 2002 left side uniform increase the example you can be divided into two parts element subscribe quite strictly Angrez Singh Sudhir Vikas possible and Will Always Have At Least One Strictly Increasing Since Here Left Side There Identification No One Will Use This A Vent To Solve This Problem In A Single Pass And The Target Was Not To Find The Attachment And Only To Find The Greatest Present Everywhere Nor Can Avoid This Is the element and improve example will be used too fast for which you can easily this is the value of greater than there left value businesses are increasing not increasing their targets President John 12.48 Doob School Divided President John 12.48 Doob School Divided President John 12.48 Doob School Divided Into Two Parts and Will Compete Against This Way You can solve this problem in just an example of elements and divided into two parts subscribe so will compare this made with his left nose in which dual left for this is not the uniform part which were looking for this right hand side uniform Video then subscribe to the Page if you liked The Video then subscribe to the Page That They Can Solve Add In Just Order Of Long And Time And Sister Single Pass Process So Let's Not Look At The Code To Get A Better Understanding Member Court Which Have No Fear Find The Number of elements in The Amazing will run subscribe The Video then subscribe to the Page if you liked The Video then subscribe Kare Shruti is the target Elements present with his left to Meerut Range Its President will update The right for internet and will make a search for the element in directions only other is it is not present in the second day obviously the target elements present in it is present in the distic will update you to plus Sudhir Video not support clean water left or right side Click on subscribe button subscribe The Channel and tap On The Amazing others will update laptop mit plus one and they will make a search for this element which will participate in two parts and will select the right hand side audition for watching and target element is The element is not the side of the - is The element is not the side of the - is The element is not the side of the - subscribe and subscribe elements which will return to avoid you will be able to understand this problem in the cockroach and solution in different languages and everyone can solution in different languages and everyone can solution in different languages and everyone can benefit from video subscribe channel video in
|
Search in Rotated Sorted Array
|
search-in-rotated-sorted-array
|
There is an integer array `nums` sorted in ascending order (with **distinct** values).
Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`.
Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 0
**Output:** 4
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 3
**Output:** -1
**Example 3:**
**Input:** nums = \[1\], target = 0
**Output:** -1
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* All values of `nums` are **unique**.
* `nums` is an ascending array that is possibly rotated.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Medium
|
81,153,2273
|
1,011 |
hello everyone welcome to coderscam and today we are going to start a series of videos that solves medium to hard problems from lead code using binary search and we have came across a lot of problems that deals with finally search solutions but and first go we cannot figure out it is using binary search so i'm gonna discuss those kind of problems here in this video series to help us understand how we can approach a problem using binary search logic let's first start with this problem capacity to ship packages within d days the problem statement says a conveyor belt has packages that must be shipped from one port to another within d days and we have to return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within details let's understand this problem with an example the input given here is the weight of items in the conveyor belt that is the problem statement says there is a conveyor belt and has n number of objects and each of them having corresponding weight save weight 1 weight 2 to weight n and that is the input given here for us and they have specified number of days we need to take to ship all this items to another place so here in this problem we have five days to ship all the items to the port or from this place to another place in this case we can upload or we can send the set of packages from this conveyor belt in order only from starting from first to fifth or sixth you can send us one package and then the rest of the packages we need to send for example if the port is taking in a container first day the weights one and two it goes and drops the items there and come back with an empty container and again the rest of the weights will be filled and then shipped here the condition given is we cannot load ships more than its capacity and we have to return the minimum weight needed so that we can send all these containers in this number of days to the other place so how are we going to approach this problem consider we are sending or loading the ship with each item per day in that case the minimum overall minimum weight the ship can hold is the heaviest weight in the given input that is we cannot divide this item into two or three halves and send it to a ship we can completely put this item in the ship in that case if we are putting one single item itself then in that case the minimum weight the chip can carry would be the maximum weight given here in the conveyor belt so the weight can be start from 10 that is the maximum weight out of all the weights given and if we are shipping all the items in one go then the total sum of the given all weights is going to be the minimum sum we can send into the ship so 55 is the sum of all given weights so the actual minimum weight we needed is residing between 10 and 55 that is the heaviest weight in the conveyor belt to all the weights given in the conveyor belt so we clearly know there are limits that is the weight resides between some 10 and 55 that is from left to right limits given so in this case you can clearly figure out it is a binary source problem that is our answer resides somewhere between the sorted numbers 10 and 55 so as per the binary search logic we are going to consider a lower limit as 10 and higher limit as 55 and gonna find some mid weight and check whether if we can load the ship with that mid weight and export all the items within five days or given d days if that is true we are going to return the mid value as the weight or as the minimum weight we need to load the ships if not if we can if we cannot load the weight within the mid values then we are going to set our pointer left to after mid and check the range after mid to the highest value if not we can send all the packages within less than d days using this weight which means this weight its weight is more so in this case we have to set our right pointer this side and check the possible weights between the lowest weight and the mid and return the value so by using this logic we are going to code and get a result so let's go for a dry run and then get into our code so the minimum weight or the lower limit is going to be 10 and the upper limit is going to be 55 first we are going to check the mid value that is 32 and whether we can using 32 we can ship all the items within five days so in our day one we can ship items one to seven which sums up to 28 if you add 1 8 to that it will become more than 32 so we are sticking to 1 to 7 and shift the rest of things on day 2 we can send eight nine and ten all together as a single package so in instead of five days within two days if we use or if we send weight maximum weight of 32 we can ship all the items which is actually very less so we can have rest of the three days to ship items with lesser weight so we are shifting our upper limit to 32 and the weight somewhere reside between 10 and 32. so now the mint is going to be 21 so we are going to check by using 21 whether we can ship all the items within d5 sorry day 5 so considering on day 1 we can ship up to six weights that sums up to 21 and then on day two we can ship up to seven and eight on day three we can shift nine and ten so here we have finished within three days but we have still two more days left in this case this is also extra weight so the limit again exit between 10 to 21 in this case we are again going to determine our mid value is going to be 15 so we are going to check on day one we can send one to five on date two we can send seven and six because if you add eight it will exceed fifteen so on day three you can send only eight because if you add nine it'll exit fifteen on day four you can send 9 on day 5 you can send 10 so by using 15 as the weight you can send all the packages in five days so 15 is going to be the minimum weight we need every day to ship the packages so this is going to be our output let's see how we're going to put it so as i said i'm going to have my left and right pointers and i'm gonna calculate the maximum value in the given weights and the sum of given weight so once we calculated the limits of left and right i'm gonna loop in and calculate my mid so i'm gonna have a variable days to calculate the number of days we are sending the packages i'm initializing that to one and a variable current which is gonna hold the current weight we are sending so i'm gonna i trade through my weights array and add my current value that is if my current weight plus one more weight is greater than mid then that is the case we are done for that day and we are shifting the rest of the packages to the next day so we are going to increment the days to one more day and then setter current containers weight is equal to zero because once we shift the weight we are getting our empty container to fill in the rest of the items so we are going to add current weight every time we i trade so once we iterate every time the current weight and if it goes greater than the mid value or the weight we estimate we are going to add days and ship the items once all items are shipped we are going to check if it is done within the days given or took more days than the given days greater than d which means we took the lesser weight so we have to make a lower limit more so in this case we shift our left pointer to mid plus one if not we have done everything within the given days then our weight was higher so we have to reduce our right pointer to mid so finally once all that is done our left will be having the exact weight which is needed to ship all our items within given days so we are going to return our left let's run this yes so let's submit yes the solution is accepted and for more binary search videos check the link in description so thanks for watching the video if you like the video hit like and subscribe thank you
|
Capacity To Ship Packages Within D Days
|
flip-binary-tree-to-match-preorder-traversal
|
A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days.
**Example 1:**
**Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5
**Output:** 15
**Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
**Example 2:**
**Input:** weights = \[3,2,2,4,1,4\], days = 3
**Output:** 6
**Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
**Example 3:**
**Input:** weights = \[1,2,3,1,1\], days = 4
**Output:** 3
**Explanation:**
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
**Constraints:**
* `1 <= days <= weights.length <= 5 * 104`
* `1 <= weights[i] <= 500`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
807 |
cool so hey everyone back again to make the second video the secondly code solution or secondly code problem I wanted to first make my first video get some feedback see if it would be useful to anyone and from there like see if I want to continue making them so I got quite look good quite a good amount of feedback saying that these gonna be useful it's just another medium love like seeing people's thought processes so cool let's just dive into the second one so here I got we could open I'm gonna start with problem number eight hundred seven max includes to keep city skyline it has a seventy nine point nine percent acceptance rate and it's medium so in a two dimensional array grid each value grid IJ represents the height of a building located there we're allowed to increase the height of any number of buildings by any amount the amounts can be different for different buildings height zero is considered to be a building as well at the end of the skyline when viewed from all four directions the grid bottom left and right must be the same as the skyline of the original grid the city skyline is the outer contour of the rectangles worn by all buildings when viewed from a distance and then they gave an example so I need a minute to like read this again because I didn't really digest what the problem was asking so we're given a grid a 2d array with the height of the buildings located in each index we're allowed to increase the height of any number of buildings by any amount and then the amounts can be different for each building height zero is a building at the end of skyline in viewed from all four directions of the grid top bottom left and right must be the same as the skyline of the original grid a city skyline is the header contour so a city skyline is the outer contour of rectangles from the help of the instrument of you from a distance see the following example alright and what is the maximum total sum that the height of the buildings can be increased so they gave an input where we have I'm just going to start writing this out I have a screen share with my iPad open here and I'm going to try to draw this out because viewing the 2d array like this won't really help well actually they have this so we have 3 0 8 4 2 4 5 7 9 2 6 3 0 3 1 0 and the outputs 35y the skyline viewed from the top or bottom from the top or the bottom is 9 4 8 7 okay and this skyline view from the left or right is 8 7 9 3 so it's taking the largest number from each row or column depending on where you're viewing it from and the grid after increasing the height of buildings without affecting the skylines is 8 4 so 8 the increases by 4 8 7 they increased to these would be 7 this one they increased be okay and then everything became 3 here ok so I kind of see what's going on because now when you go from the top it's still gonna be nine four eight seven which is what we had here and from the left of the right it will be eight seven nine three yeah cool so they gave some I guess constraints one is less than the grid length or the amount of rows one equal to okay and then this one the amount of columns gonna be less than or equal to 50 okay so never mind I read this wrong so the it's gonna be a squared to the array with a length greater than one and less than or equal to 50 mm-hmm the less than or equal to 50 mm-hmm the less than or equal to 50 mm-hmm the numbers inside are in the range zero to a hundred all buildings in grid I and J occupy the entire grid saw so what does that mean all buildings in grade I J multiply the entire that is air one by one I rectangular prism okay so like if you have four it's like taking up the school index as a building cool that means that they got one went under stayin the problem like if I were to ask a clarifying question in an interview I might ask if any other numbers could be negative and what are the boundaries stuff like that but that stuff's already given so on - I guess we already given so on - I guess we already given so on - I guess we already understood the problem the maximum face I'm thinking there's not like an external data structure we can use for this problem but we would have liked I guess pointers pointing to each index that we need to see I still in my head I'm not really sure how we'd go about solving this so I want to think about it so when reviewing it from the top and okay we want to keep these to be the same so I guess the first pass we can do a first pass through the 2d array and see what our arrays are gonna be like let's see that makes sense because we want this one to stay nine and then this one to stay eight so we take the lesser of the two and we can increment all these other ones is that true no it's not because this one is four and if we made this a and this road would become eight let's see once assuming we have this let's assume we have that what can we do you'd have to do a check every time can this one be incremented because is it greater than four so we try drawing it out that way I can mess around with it I'm gonna take this uh disarray that was given so we have three okay cool my opinion wasn't working now it is three zero eight four two four five seven nine two six three zero three one zero all right so we have this given to us and when we go through it we know that from the left and right it's gonna be nine four and eight seven I mean the top bottom it's gonna be nine oh and from the left and right when you view from the left on the right it's gonna be eight so I mix the two up this is gonna be top bottom this one's gonna be left right so from the left and right it's gonna be eight seven nine three so from a messy handwriting I'm just kind of scribbling so when we start off here what can we increment this to we know that it can't be greater than eight because we have an 8 here and it can be greater than nine because we have a knife here but we're gonna take the lesser of the two so we can add five here and then we'll keep a counter as we go along so like counter it becomes five then we go to this index we see we move this way so we keep this we keep eight in our I guess like point of view but we also then take the next greatest element which is here 4 so it can't be greater than 4 and it can't be greater than 8 so we can implement this by 4 to become 4 so plus 4 and now we can remove these circle and we added 4 here let's just keep it counter 8 we can't increment this because we it's our greatest so we can't go higher than 8 so that one's done now read the four it can't be greater than 8 it can't be greater than 7 because this is here so what we can do is add 3 and then we move on to the next row so now we're the anthis to when we have 2 in consideration and to keep into my 9 and we have to keep 7 in our minds so here we can you meant by 5 to make it at 7 plus 5 moving along we will move on to the 4 so 4 is the largest here we don't want to increment by anything so zero is there it's the largest for this column five here can be larger than seven and it can't be larger than 8 so we can add two to make it seven so plus 2 and then 7 since is the largest in this column we can increment B leave it alone moving on to the next row we have 99 as the largest in this column and we already know that so we can continue on moving to the two we want to keep this for in mind as well as this 6 so we can add 2 to this because we can make it a 4 so plus 2 let's go ahead and erase this and now we're at the 6 so here when sorry anything in circle there's 6 earlier but it was after 2009 that we had to keep in mind because it's the largest but now we're at the 6 so we have to keep this 9 in mind and we have to keep this aid in mind so we can add 2 to make it an 8 moving along to the 3 we have 7 and 9 so we can add 4 to make it a 7 now I'm starting up the 0 we want to keep this name in mind because it's the largest column and we want to keep this 3 in mind because it's the largest for this though so looking at 0 we can make it a 3 so we can add 3 to it to make it 3 this 3 is the largest for this dispro so we'll move along we can't do anything here let me just go ahead and I think I added plus 4 to make this a 7 this one was a plus 2 yeah I forgot to write these in this one is a plus 3 so plus 2 let me just go 5 4 where's this 3 so I believe this one was passed three five two four my dad wrote +7 I meant to make it a seven two plus +7 I meant to make it a seven two plus +7 I meant to make it a seven two plus four here plus three now we're looking at this three is the largest of this row we can't do anything with it when we look at this one it can't be greater than three and it can't be greater than eight so you can just add 2 to it and finally this zero can't be greater than seven it can't be greater than three so we can just add three and yeah three so let's go ahead and sum these up so this is gonna be seven this five and five is gonna be ten this is 6 plus 4 is 10 this is 5 and let's leave this 3 here we'll take the 7 over 3 negative 10 plus 10 is 30 plus 2 5 is 35 and when we see that's actually the output babe you wanted 35 and that's what we got where we see right here is 35 here so it seems like we understood how they got the solution we can also check if our grid matches so our let's see let me put this here so here we have three plus five is eight which is the 8 here 0 plus 4 is 4 eight seven four seven nine four eight seven three okay cool so yeah we got what you wanted the new grid and we see that here this function or method is returning an int so I'm guessing that's just the output this how much we incremented by so cool we have understood the problem there's not really an axillary data structure we can use I mean I guess thinking about it when we're incrementing index by index we're incrementing the number and that index we'd have to do check every single time to see what the greatest is for the wrong column and that's pretty inefficient we can maybe do one pass the first time to store that somewhere and then we can just view it later on such as in this way where we have where we got this that might be a good idea that way we don't have to keep on looking up every time we just if we're moving left to right so for this 3 we'd is 0 you look at this 0 so you want to look at yeah and then take the lesser of it and then move along and then 0 1 2 index 0 1 we want to look at this one I'm gonna take a lesser of it some it and then when we're here we want to take a look at 8 and 8 so it 0 2 that would be you'd look at 8 & 8 when we were at the 4 so 0 3 index 0 & 8 when we were at the 4 so 0 3 index 0 & 8 when we were at the 4 so 0 3 index 0 3 we're gonna look at the 8 & 7 take the 3 we're gonna look at the 8 & 7 take the 3 we're gonna look at the 8 & 7 take the lesser and do the subtraction seems like this is working and it saves us a lot of time in checking what's the top and bottom so when we're at finally index 1 0 we'll take a look at the nine and a seven yeah sounds good umm let's create the pseudocode for this so what we did first was we're in the pan Kofi's now let's create the two arrays of the get top bottom and left right views skyline views next would be basically the high level overview would be get those views and then in chromatic 2min of the two indices and these can be broken down even more how we do that so the skyline views we just how would we do that let's see so given this 3:08 for do that let's see so given this 3:08 for do that let's see so given this 3:08 for when you're here you want to go row by row so first you do the top bottom you'd go to iterate through the thing through the array and for this column you just see that's nine for this column it's poor for this column it's a for this column at seven okay so it seems pretty for that simple and then for this column it'd be a this column would be seven it's calling it be nine and it's ultimately three so by doing that we save our subs the time of like traversing through the 2d array to see if it's bigger or smaller and actually it you know instead of like doing end by end big o time we get an N plus end all the time because it's just n and n bigger obviously that's what we're talking in here can't write it cool so by doing that we save ourselves the time and it allows our solution to be more efficient okay so pseudocode for this the keep track of largest for each column table squeaking and then I do the same for each row and we can maybe like modular Isis by having a helper function that will just return it to the array with like two rows and then whatever at the amount of columns is and then for this one increment to the min we kind of saw how we did it here where as you're incrementing it or as we're moving along each row so 0 2 0 1 0 2 you're gonna keep your left right view the same but you're going to increment this top bottom view and then when you move down the row you want to implement this left right cool so let's try it I'm connecting this I'm going to close this little make some space for myself and so the first thing we did was get the top bottom and left right view here let's just say int this is gonna eat cool and that's quick nurse really bother me you see what I can do about it cool hopefully yourselves so we get this view skyline views is equal to get styling is get styling these so this would be a private integer every entertaining it to trim it sky long okay you see if I move to this side of the table gets kind use with this will pass in the grid so we'll take an integer array a 2d array called grid and then let's initialize the we want to return to say skyline view is equal to Y and the size is gonna be two rows and it's gonna be good doubling columns and then form and iterate through the here will iterate through the let's see what we did first here we did top and bottom first so TV to do top bottom to use it's gonna be alright cool so we're going to go through the columns um red dot or grid let's just say 0 thing and we'll say skyline view 0 I is gonna equal although we want to keep the count letter the Samba the largest number so largest is equal to zero yeah because the range is 0 to 100 so as we're iterating through if grid 0 I mean I see I did it then we arrived I guess but that's fine this is gonna be left to right for you so basically this it has to be a 2d array for good darling okay is the grade 0 dot Lee JT plus this goes in here let me just make sure why I'm doing what I'm doing I kind of lost myself in fact all right so we're going through the row each row and getting the largest okay yeah so it's not gonna be a 2d is less than bread and we want to do this or every so for every column you want to have a largest county fair largest variable to keep track of the largest and then for every one of the columns am i right zero length okay so for every column then go through okay yeah cool and if the value from this index so the value @j i you know i kind index so the value @j i you know i kind index so the value @j i you know i kind of flip-flop them from like standard of flip-flop them from like standard of flip-flop them from like standard ways we use I'm going to use I and J but the time so if this is greater than the largest set largest equal to grid J I um let's go ahead and just swap these so that we're like used to normal convention because I know that we'll probably throwing it off soon enough I forgot the I plus here change this to J so the largest is equal to this and then finally you want to set let's just keep this alright actually here skyline you 0i is going to equal gorgeous we want to do the same thing for the left right view so let me just go do this now seeing how this would work so 4m i equals 0 I is less than the number of columns I plus so I yeah and then J is equal to 0 and change lists and the number of rows J plus so if I J is greater than the largest set largest equal to that so we'll stay largest at 0 I'm going through this third 20 at 0 on the column and then 3 is greater than 0 so set it equal to 3 continue to do so we've implemented the rover on so 2 is not greater than 3 9 its greater than 3 0 is not greater than 3 so we're done with that one and then we'll set skyline view of index 0 because that's the first one equal to 9 and then we'll continue on so just to make sure my two arrays are gonna be this is my top bottom of you and then this is my left right view no one write that down so I'd if I remember for later on you know we do the same thing for the rows so we'll just flip these around grid okay so now it's equal to this for J is equal to 0 J is less than a number if it's going to largest said this one equal to one alright cool so now that we've got that we want to return skyline view so with this as we will now this is where we increment to the middle of the two indices increment to mean for the two indices of use right so keep track of amount incremented totally so let's just call it in counter here now that we have these you can basically write do the grid good that Lang I plus J is equal to 0 J and we can do is square matrix J plus what we'll do is keep a left-right and a top bottom Powell left-right and a top bottom Powell left-right and a top bottom Powell County so here we'll have into our CTR it is equal to 0 int TV CT all right it's equal to 0 and we want to actually have this TV be reset every iteration of the second loop I'll have this our so now let's take them in of the tube so here well at the end of these we will do TV plus and we will say counter plus equals the difference between the two so grid by the minute I believe it's math dot min and then we put the two so passing skyline fuse and we set that TV and then L R so TV actually zero and then so zero was the TV Connor TV counter and I use one this penknives this TV counter - whatever we have back this TV counter - whatever we have back this TV counter - whatever we have back grid I J so if we have when we went from 8 minus 3 is 5 and we'd add that and eventually at the end we just return so let's run through this with a smaller array then this large one that was given to us let's run through it with our code alright so that's this thing we have a make this bigger let's just say we have a 2 by 2 1 2 3 let's say 1 so when we reduce in like pseudocode with using your code as a guideline our top bottom view would be 3 & 2 & the left bottom view would be 3 & 2 & the left bottom view would be 3 & 2 & the left right would be 2 & 3 right would be 2 & 3 right would be 2 & 3 yeah right so this is top bottom and left right so then we want to add the minimum of these two thread index 0 we'll look at 0 and we'll look at this one so I need to write this down and then we'll increment well the one to be the smaller the min of the 2 to a 3 so we increment by 1 and then we move on to the next we'll move on to the 2 so here we'll look at this 2 and the 2 and we'll see that F dominant of these 2 minus 2 is gonna be zero so we'll add 0 next one we'll look at this 3 so when we do that we actually move along to this one and we shall look at 3 & 3 one and we shall look at 3 & 3 one and we shall look at 3 & 3 so map that in - that it gives us 0 will so map that in - that it gives us 0 will so map that in - that it gives us 0 will move on to this one it will give us you can increment to 2 because it's the minimum of 3 & 2 so because it's the minimum of 3 & 2 so because it's the minimum of 3 & 2 so this one can just be incremented by 2 leaving us with 2 and 2 on these places where the one is using our code we can try to run through it let's see so assuming I'm going to assume we did the gets down line views like this and our code actually returns this as a 2d array so I'm assuming that this works let me send my County zero and then we have a left-right zero and then we have a left-right zero and then we have a left-right equals zero we have a top bottom equal to zero so we're gonna hitter eight through this mini grid that we have 2x2 grid so I is equal to zero okay we put a zero and we'll take the counter we're gonna add in math dot min skyline views zero pad TV counter which is right now 0 so 3 in 3 and skyline use 1 at T be counter so 1 and TV counter is zero so to just correct - whatever correct - whatever correct - whatever the index is - IJ which is right not one the index is - IJ which is right not one the index is - IJ which is right not one and that means we add distance 2 minus 1 plus 1 so I had counter now becomes 1 he incremented the TV counter so it's now 1 and we see that we do counter it plus equals the min of the 0 a 2 so in of 2 + equals the min of the 0 a 2 so in of 2 + equals the min of the 0 a 2 so in of 2 + 1 so 3 and it's that actually you know so here when we click this index we're comparing two and three but you should not be the case mmm and I kind of see why it's happening this is the left/right counter at our this is the left/right counter at our this is the left/right counter at our counter because we only want to increment the TV counter as we go along columns and the left right call the left right counter as we go along the roads so all right assuming I fix this properly let's take a look at this again now instead of doing two and three will do two and 2 minus 2 which is 2 minus 2 to 0 so counter stays the same TV counter becomes a 2 and we are at index 2 which isn't a it won't go and do the sleep again and TV counter because 0 and L are counter becomes 1 so now we look at this I is 1 this we look at in this 2 here sorry yeah this 3 here so we'll take a look at in of I mean of 3 area actually this is 303 minus 3 which is 0 and for this one we'll look at TV kind of becomes 1 we'll look at min of 2 and 3 and minus 1 which becomes 2 minus 1 to plus 1 and then counter becomes 2 and we return the two so it seems to I've worked when I write through in that mini example let's go ahead and try running the code so I got 32 instead of 35 let's see why so looking at my code I ran through this assuming that might get styling views was returning the proper like it worked properly but after taking a look at this code I realize I'm doing the same thing here essentially as I'm doing here so this skyline view a 2d array with the two rows is essentially just returning the left-right view on both row 0 + Row the left-right view on both row 0 + Row the left-right view on both row 0 + Row 1 and I realized after thinking about it's because I'm doing I to be grid uh index I enjoy both times so simply to fix that to do column instead of the row first it's J I and that should fix it so I had 32 35 I believe this one works as proper it was this function that actually was giving me like a little tricky causing it yes let's run it now and ok cool so 35 it's the same as 35 worked for this one um code works it's not pretty but it does work let's see if it accepts it cool so Christ submission was accepted that means we've implemented it properly we can go to the review so I started off you know not having these values stored and I was doing a look every time to see what the new or with the old and with the largest of the columns and the rover every single time by doing that we you've saved some time but in the end the big o-notation and this would still the big o-notation and this would still the big o-notation and this would still be Big O of n times n because we have to go ahead and touch all n by n elements but because we also cashed the these values we introduced some space which is gonna be bigger and there's just two rows which I mean I'm not sure how much better it is in that case like we noticed that it improves our time complexity not even Big O notation like a statically but just in the general amount of time it takes but now we've introduced a space so that's something like we can talk about with the interviewer I think that this would be what I would submit to like an interview in an interview a value there's a big no time what I can do to improve it let's see not really sure what I can do to improve it we can take a look at some of the solutions that were already like pushed so row and column maximums I believe this is what we did time with N squared space complexity of o of n it's the exact same one that we did actually there's this a lot prettier so bro maxes are and great hard to see ok I see what they did yeah there's just a lot prettier definitely that's something I want to work my way up to but they did the math time in same place I did and this ok got it I see what they did it's a lot prettier than mine something I want to work out to definitely I know this video took quite a bit of time silence problem even though it has a high acceptance rate I'm assuming also because it's a medium but I think I did it in 45 minutes which is the amount of time it would take an interview and I feel like I was pretty variable about like my thought process and I know I took a while I'm working it out but yeah I hope these videos like do provide some help to other people because I know it's definitely helping me you know I get kind of nervous when I have to talk my solutions out I'm talking video or in person but by doing these I feel like I can definitely get over that fear of being judged and like whatever so cool see you guys in the next video
|
Max Increase to Keep City Skyline
|
custom-sort-string
|
There is a city composed of `n x n` blocks, where each block contains a single building shaped like a vertical square prism. You are given a **0-indexed** `n x n` integer matrix `grid` where `grid[r][c]` represents the **height** of the building located in the block at row `r` and column `c`.
A city's **skyline** is the outer contour formed by all the building when viewing the side of the city from a distance. The **skyline** from each cardinal direction north, east, south, and west may be different.
We are allowed to increase the height of **any number of buildings by any amount** (the amount can be different per building). The height of a `0`\-height building can also be increased. However, increasing the height of a building should **not** affect the city's **skyline** from any cardinal direction.
Return _the **maximum total sum** that the height of the buildings can be increased by **without** changing the city's **skyline** from any cardinal direction_.
**Example 1:**
**Input:** grid = \[\[3,0,8,4\],\[2,4,5,7\],\[9,2,6,3\],\[0,3,1,0\]\]
**Output:** 35
**Explanation:** The building heights are shown in the center of the above image.
The skylines when viewed from each cardinal direction are drawn in red.
The grid after increasing the height of buildings without affecting skylines is:
gridNew = \[ \[8, 4, 8, 7\],
\[7, 4, 7, 7\],
\[9, 4, 8, 7\],
\[3, 3, 3, 3\] \]
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[0,0,0\],\[0,0,0\]\]
**Output:** 0
**Explanation:** Increasing the height of any building will result in the skyline changing.
**Constraints:**
* `n == grid.length`
* `n == grid[r].length`
* `2 <= n <= 50`
* `0 <= grid[r][c] <= 100`
| null |
Hash Table,String,Sorting
|
Medium
| null |
399 |
hey so welcome back and this is another daily code problem so today it's called evaluate Division and it's a medium level graph problem using that first search and so I'll just go ahead and hide this for now but basically you're getting a lot of different input variables and it can be really confusing just looking at this initially but I find it fairly intuitive once you understand it and so basically you're given a list of equations with their Associated like output values and with these equations you have different variables Like A and B for the first one and so the equation for the first one is basically just a which is the first variable divided by and it's just a division for the equation by the latter variable so B and then with the corresponding index so this is index 0 in equations so we look at index 0 for the values and so it's just going to equal 2.0 because it's just going to equal 2.0 because it's just going to equal 2.0 because it's like a float number okay and you can do the same thing here so B divided by C is n equal to 3. and so with these inputs what we want to figure out is what will the results be if we're given these queries we want to figure out basically the corresponding values here for these queries now some of these you won't be able to figure out and kind of using high school math to be able to drive um the values here you just say okay if I can't figure it out then let's just return negative one in that case okay and so to figure this out um just kind of using basic high school math say that we want to know what x divided by Y is oh my monitor or something's kind of lagging here so I keep messing up but say if you want to know what x divided by Y is but all that you know is say x divided by Z and say you also know Z divided by y we can actually figure out x divided by y by basically just doing x divided by Z multiplied by Z over y because these two cancel out and that would just give you x divided by y okay so by rearranging these problems you can actually figure them out so let's go ahead and kind of use that knowledge to go ahead and implement the algorithm and so typically in this kind of pattern for most graph problems is the first thing you want to do is reformat your input variables so you can have a better working data structure and so in that case what we're going to do is we want to iterate through all of the variables in our equations say we have X and Y to kind of keep it the same theme here with X and Y and then we also want to figure out okay what is their Associated values because that was like the first thing we want to do is map x divided by Y is equal to those values and so let's also get the corresponding value by just zipping these two arrays together okay and so what we're going to do is we're going to have like a lookup and it's going to be equal to like a default dictionary where at every single key it's going to have a dictionary as value and so what this is going to look like more practically is basically say we know like a divided by B is equal to 2 and then B divided by C is equal to three kind of like the last example what this will look like in this new mapping is we're first going to have a hash map and then within this hash map we're going to have key for a which is also a hash map which then says okay B is then equal to 2. so this just means for a these are the associated values that we know a divided by that value is and this is like the output and same thing for B here I think this is better example so for B we know the mapping to a because B divided by a is one over two here so 0.5 one over two here so 0.5 one over two here so 0.5 and we also know B divided by C which is three so then we'll have the mapping to C which is three and then finally same thing here but for C and so we know C divided by B is 1 over 3 which is like 0.3333 so forth 0.3333 so forth 0.3333 so forth okay so maybe pause the video and just make sure you understand the data structure that we're working with but it really helps simplify things we kind of did all this in our heads um when we were drawing like the high school math solution to it and so with that we just say Okay this look up for X is just going to be equal to for x at y since it's a nested dictionary is going to equal to this particular value but then y divided by X is going to be equal to like 1 over the value great and so from there what we're going to want to Output from our program is like an array of these or resulting values for these corresponding queries so let's just make a result array here and we're going to return it at the end we're going to want to iterate through all of these queries so for every X and Y in our queries let's iterate through them and find a resulting solution and so we're just basically going to append the result to this query by some function that we're going to create above and we're going to give it the X and Y variables as well as something just to keep track of and it's common to use it in depth first search what we've already visited before and so it's like a visit set and so once again X and Y and initially that set is empty because we haven't visited any possible solution yet great and so let's go ahead and implement this so in depth first search the first thing that you're going to want to do is kind of check your base cases and what basically that could be is okay what if we're trying to figure out what and like x divided by X's but we haven't even seen any equation yet with their corresponding values using X there's no way we can compute that and so we just want to ignore it so say if X is not in our lookup um and Y is not in our lookup we're just going to return negative 1 in that case otherwise um what if like we already know x divided by X and so in that case let's just go ahead and return the solution so if X is in or say if Y is in our lookup at X then we already know what the solution is and so let's just go ahead and return that solution otherwise we know in that case that we're going to have to compute the result and so let's just go ahead and do that so what we're going to do is we want to iterate through all the possible solutions that we know kind of using that high school math I showed you before and so we just say 4i in our lookup at let's see here at uh X since we don't know x divided by y let's see what we know x divided by something is we want to like basically figure this out but if we don't and we're not able to figure it out let's just return negative one at the end here okay and so the first thing that we're going to want to do is check okay have we actually visited this before because just to prevent those infinite Cycles so we just say okay if I is in uh visit let's just continue on and ignore this particular like formula otherwise let's go ahead and add it because we're now visiting it so visit Dot add this particular number and we're going to want to perform another depth first search from here and this is kind of templated code that I'm using here and so we just do depth first search on I divided by Y and that was the high school math I showed you where okay if we don't know x divided by y we might know x divided by something and if you know x divided by say C then we just need to know also C divided by y to figure out x divided by y okay I hope that makes sense um and so we just go on from here and we just uh include our visit set and so this is going to return something since we're returning like negative one if we don't find something and let's just return this in some temporary variable called uh temp and so then we say okay if our 10th is equal to negative one then let's just ignore this and naturally we haven't found anything of use so we just ignore it and we continue on to the next possible variable otherwise then we do know enough so we can actually compute our result until we just say okay then let's return the lookup at X at I multiplied by that result that we just computed okay so let's go ahead and run that it looks good and submit it and success so yeah I hope that helped um it's a challenging problem first reading it out and coming out with it but I think the key to solving this problem is I think knowing to use that first search is fairly intuitive but I think understanding how to figure out first like the high school math and is one part and then the second part is then just seeing okay building this kind of data structure making sure you know that not only to compute x divided by y equals this but also y divided by X is one over that value I think is the second part of this but yeah this is a great solution and I hope it helped thanks for watching
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
226 |
to solve the problem in what binary three so you are given the root of binary three in both the three and the returns root so let's see the example so root node is 4 and the root node has 2 children like 2 and 7 here and after inverted so we swapped so 7 should be a left side and 2 should be our right side and again so look at this subtree so since uh this node two to move to a right side so its children also move to a right side here but also its children we need to swap so i mean so one should be right side here and this three should be a left side here in the substrate so this program so we use deft devs first such we'll solve this problem okay let's write the code first of all if not root just return which means we reach to the end of the tree and then second swap left and right so first of all copy the left and then i update the left child with a light child and then i update right side right child with temp variable and then so we are moving to uh left side so blue we are going to move to right side this is like a devs first search process and then just return root okay so we got success and this is a pretty simple question but i think it's good to understand how we can traverse the tree with like a devs for such so i'll see you next question you
|
Invert Binary Tree
|
invert-binary-tree
|
Given the `root` of a binary tree, invert the tree, and return _its root_.
**Example 1:**
**Input:** root = \[4,2,7,1,3,6,9\]
**Output:** \[4,7,2,9,6,3,1\]
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,3,1\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
824 |
this problem is called note latin and here you will be given one english sentence and you have to convert to this fixes language called goat latin and there are some rules by which we have to make the conversion so let's look at an example so this is the input it's an english sentence and it consists of just lowercase and uppercase letters and words are separated by space so what we have to do if we encounter a word which starts with a vowel in this case i then we append m8 to that word in the end so you see m a here and if it's not a vowel for example this case then pick the first character put it in the end so this is the word and then add this m a so this m a is added to everything but here in the case of vowels we don't change this word but in the case of consonant we pick the first character and put it in the end and then we append m a and then we append another suffix which is for first word it's a so you can see m a here then here the suffix is a third word it will be a fourth word it will be a so these things are irrespective of a vowel or consonant so m a plus some suffix which starts from a and each time we increase by one so this should be very simple uh only thing is that you can it will give you some familiarity with the language construct for c plus we will use string stream to tokenize the words for java and python we will use split so this will give you just some exercise of these functions how to use them and now let's see the time complexity here so what we are doing we are going through the character by character you can think of that so let's say there are n characters in the word in this uh sentence not word it will have different words so what is the time complexity we have to scan through this words and uh we have to pick first character remove it and put it in the end of the word so that will be of the order of word length that thing removing the character and putting it to the end so let's say word length is w i am talking about average word length so it will be of the order of w uh then what else we need to do uh so we will build this result from scratch so result is initially empty we picked the first word in the worst case let's take the worst case we inserted it in the end so w is added then we added m a which is constant time then we added suffix which will depend on which word is it so it will be one for first word two for second word three four third word and let's say there are uh k number of words so it can go up to this so just for the suffix part total time will be this much so k square it's k multiplied by k plus 1 by 2 so this is for suffix part and for other things m a is constant and uh then the sum of each word that is n so it should be n plus k square the time complexity and space we are using this as the result so again it's n plus k square so n is the original number of characters and then we add these many characters and plus 2k in the end for m a for each word so still it remains n plus k square so let's write the code for this so we create this string stream from this string so this is string stream lets you uh it lets you treat this string as stream so you can read from it and you can also write to this string then we will need one result so initially it will be empty we will just keep appending it so we will pop word by word and then append suffixes to it and then append to the result with a space so we need a result we will also need word so we will read word by word and then we will have one suffix where it will be just uh some is starting with 1a and then 2a3a4a then we need vowels so since it con consists of both lowercase and uppercase letters there are total five bubbles so 2 times that 10 so it would be bad to compare with all the 10 values with or operator so better keep them in a set a e so this is the set of vowels so this is the way to read word from it and there is the other operator also if you want to insert into it so suffix each time we will increase append extra a to the suffix and if vowels not find word zero if first is not vowel then this will be vowels not end it did not find it so it's not a vowel so we have to pick the first character and append it to the end so word equal to word dot sub string from second character till then plus first character and then result we append the word uh then we append m a plus suffix plus one extra space so we will have one extra space when we inserted the last word so we will need to get rid of that and this matches with this so submit and the solution is accepted now we will write this in java and python where we will use the split function so we will use string builder and suffix is initially empty and then we need this vowels and then we can create a set from this array we will convert it first to set so this array we converted to list and then create asset from that and we split on the basis of one space so here we don't need result this string builder we will convert it to string and return we can also take substring to remove the last space so take substring from beginning till last minus one or delete care at okay incompatible so we need to pass a string here and finally it's matching so let's submit and the java solution is accepted finally we will do it in python 3 so let's copy this first so result is empty suffix is also empty so we need to get rid of the last space so we are taking one less character and the python solution is also accepted
|
Goat Latin
|
number-of-lines-to-write-string
|
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:
* If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word.
* For example, the word `"apple "` becomes `"applema "`.
* If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`.
* For example, the word `"goat "` becomes `"oatgma "`.
* Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`.
* For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on.
Return _the final sentence representing the conversion from sentence to Goat Latin_.
**Example 1:**
**Input:** sentence = "I speak Goat Latin"
**Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
**Example 2:**
**Input:** sentence = "The quick brown fox jumped over the lazy dog"
**Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
**Constraints:**
* `1 <= sentence.length <= 150`
* `sentence` consists of English letters and spaces.
* `sentence` has no leading or trailing spaces.
* All the words in `sentence` are separated by a single space.
| null |
Array,String
|
Easy
| null |
334 |
Hello, how are you guys? Welcome to week one of the Weekly Lead Code Challenge of L. I hope you have registered for it on L's website. If you have not done so yet, then quickly track your progress. This will help us in doing so let's move towards the solution. Yes, so let's start with our A question. Ch is increasing triplet sub sequence. Okay, let's see the question. The question is saying given n integer array numbers return true if there. Ass a triple of indices i j k you are given an array names you have to return true if there are three indices eg i j k in which i is less than j and j is less than k. That is, both I and J are smaller than K and the numbers placed on I and K positions also have a similar relation, that is, the number placed on I is smaller than the number on J and the number placed on J is smaller than K. If it is smaller than the number, then you have to return true. If you are not able to get even a single triplet, then you have to return false. Okay, we understand this. Let's understand how to do the question. Suppose you have an array. Has it happened? 2 3 4 5 If I have placed here, if I have placed here, then the position of a lesson j is being fulfilled, I have numbers of a less than numbers of j less than numbers. The off condition is also being fulfilled because lane 1 is 2 lane 3 but on the flip side if you have given er 5 4 3 2 1 and now if we keep i j k then aa le j le condition is also fulfilled. But your condition of numbers of less than numbers of names of less than numbers of is not being fulfilled. It is okay because there is not a single pair on which this condition is applicable. Not a single pair. Let's take another example, as if you have an array 1 5 2 4 3 6, you have this array, then you have this condition, where is it true in one four, is true in 1 2 3, is true in 1 2 6 and where else is it true? There are 5, 1, F and Six, it is ok, Th and Six, there are 2 fours and six, so you are getting a lot of pairs in this case, so here I have to return true, if you get even one triplet. Set, you have to return true. Let us understand how to do it. Okay, look, when I add an item to the array, I always have to move it from left to right. Right from left to right is fine and when I go from left to right. If I am moving, then according to the condition given to us, the right most person should be my maximum. The right most person should be my maximum, that is, if I am moving from left to right, then my answer is if I say that you are maximum. If you start looking for a person, then I can keep the two previous ones as this one, this is the minimum one and this is the middle one. Okay, that means, if you do it now, you will understand. It is possible that right now you may be feeling that you do n't know what I have said or something. No, you will understand, don't take tension, so what have I done, I have assumed that the one who has numbers of I will always find a person with max for me, who is the biggest i.e. element of K and who I have, who is the biggest i.e. element of K and who I have, who is the biggest i.e. element of K and who I have, numbers of I have and two we are integers. Let's create, let's say an integer create int smollet, so it will find the smallest person near me. Create an int, say int middle, so it will find a monkey who is bigger than smollet and smaller than names of I. Okay, now we know one thing. When we compare with something, in small case, that is, I have to see a number smaller than one of its numbers and have to compare the entire array, then I initially list any integer from the largest number. I treat any number with the largest number so that when I compare it becomes smaller and smaller. If I compare it with the smallest number, it will not get smaller. If I treat it with the largest number, then the largest number will become an integer. What is int max in the case of , What is int max in the case of , What is int max in the case of , so I equated both of them with int max, till now you guys have understood, there is no problem, after that what did I do, nothing is added, then where is it equal to zero? From where it should go till n i.e. till its size, From where it should go till n i.e. till its size, From where it should go till n i.e. till its size, whatever is its size and what to do in that, if my numbers of i which is an idolator, if it is bigger than the middle one, if it is bigger than the middle number, then it is obvious that It will be bigger than Smollett's number because now when we will write the condition further, that thing will be understood. If it is bigger than the middle then obviously it will be bigger than the smallest. If we assume a hypothetical situation, then if it is Smollett. I have got the middle one which is bigger than that and I found the condition in which the number of aa is bigger than the middle one. If it is so, then I get a true return here. What is the reason for the true return that I get a triplet? Gaya who is present in this sequence Right in which sequence Smollett is bigger than him Medal is bigger than him Numbers of I is bigger than the number with I K is bigger than the number with J So much we have understood that if he is not bigger than the middle then I What to compare, if it is not greater than the middle, then I check whether it is not the middle itself. How to check the middle itself, if the number of aa is greater than then it is smollet, that is, than the number of smollet. So the one who is bigger and the one who is smaller than the middle one is the one who is smaller than the middle one. So, what is the one who has got the middle one? What is the one who is smaller than the one and is bigger than the smallest one? So I do one thing. Na, I assign the numbers of I to the middle that this one is the middle one, we will look for the bigger one, this one is the medal, we will look for the bigger one, okay here Els will come otherwise else the third condition else if the numbers of I is mine than the smallest number. It is smaller, it is smaller than Smollet, so it means who is this, the smallest number is Smollet, okay, so what should I do, Smollet is equal to two numbers by coming off, okay, you guys are understanding this, after that if this whole thing goes on. And in this entire array, it could not return true, but it did not find such a situation that if a bigger number comes out from the middle then nothing should be done or return false, this is the work that has to be done, let's move on to the quote. So I made an int a e equal to two numbers dot size ok and I said look the first condition is one more we will add that if I want to get a triplet means three numbers so there should be at least three numbers in the array Okay, this is also important for us, so I said that if there is not only three numbers, but there are less than three numbers in the array, if there are less than three numbers in the array, then return false in advance that triple at does not exist and the number becomes a triplet. No, there are no three people, after that then we run the same for loop, take our a e 0 aa n aa p and what to do inside this, we say brother a first you make middle int and give it g int. Make the value of max an int smollet and give it an int. The value of max is the largest. In this case, now the possibility of getting as small as it can be will increase with me. Okay, they will be reduced, so I said that if you have names of a The one you are getting is bigger than the middle, that is, it must be bigger than the smallest, so return true here, else if the numbers of aa, the one you have got is bigger than the smallest and smaller than the middle, then what in this case? Yes, middle is equal to two numbers of i, middle e is equal to two names of a, middle is updated, okay, that much you have understood, then the third condition is l only names of i, which is smaller than Smollett. So, we have seen the condition of the biggest one, we have seen the condition of the middle one and we said, if it is smaller than Smollett, then update Smollett, brother, the name of the name is Smollett, now I understand the thing and if this condition is not there then update it. But it could not be true. It was not found anywhere that the number of I is bigger than the middle one. If such a situation could not be found anywhere, then it would return false. Just this much work has to be done, you can run it once and see. Yes, it's accepted, let's see after submitting. It's done, it's great. Yes, I hope you have understood this question well. You will also find its code and a detailed explanation on our website in the editorial form, so you can check it out as well. You can like the rest of the video, share it with your friends, they will also get some benefit and also subscribe to our channel till then thank you for watching this video as time goes bye.
|
Increasing Triplet Subsequence
|
increasing-triplet-subsequence
|
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
| null |
Array,Greedy
|
Medium
|
300,2122,2280
|
1,013 |
hey how dare so today I'm talking about questioning a thousand inserting partitioned array into three parts with equal sum we have an integer array and we want to determine if we can partition the array into three non-empty parts the array into three non-empty parts the array into three non-empty parts with equal songs so formally this means that we need to find two partition index i + 1 + J such that if we some elements i + 1 + J such that if we some elements i + 1 + J such that if we some elements from 0 to I that's going to be equal to if we sum I plus 1 to J minus 1 also equal to front J and all the way back so since that this 3 is a division of the totality that means the son has to be the you know the three part sum has to be equal to 1/3 of the total sum so if be equal to 1/3 of the total sum so if be equal to 1/3 of the total sum so if we just do one pass to calculate this total then we can starting from zero and find the first location that sum up to one third of that meaning that we find I then from there we just try to find another continuous chunk that's sum up to one third of the target value you know the total so one-third of the total know the total so one-third of the total know the total so one-third of the total we just know our target that tell us we find J minus 1 and if we still have elements left to there right that means the remainder part has to sum up to one third because the previous two they sum up to 2/3 so if we still have things up to 2/3 so if we still have things up to 2/3 so if we still have things going on that part remainder part has to sum up to one third so two paths calculate the sum divide that by 3 to get the target and the front left to right we do accumulation to find the target increment a counter for the number of times we find that and we said to the accumulation if the counter hits 2 and we still have a elements left to the right that means the third part is going to be something up to the target so to pass and that's pretty much it just kind of do a really quick demo with example here this guy is some up to nine how do I know this so fast I'm looking at here zero to one so that's the first apart they sum up to three so multiply three by three we get 9 so that's why this guy's has to sum up to 3 so just by eyeballing I find that I can put I here we get a 3 and J has to be Jew has to be here to zero one day has to sum up at two three so but in reality my algorithm is just gonna starting from left zero to one they add up to three so I increment this counter by one and then reset to zero negative six positive six that go back to zero negative seven nine go back to two and I have a one their back history again so once that history I can you come at the counter and we do find we still have element stone on the right so the remainder has to be equal to three I don't even need to look at this to zero one I know that they has to sum up this week so at that point time point when I am actually at the J I can return true so yeah so that's a critical illustration about how this to pass over isn't is going to work so we get this total equal to this sum and the target value is just going to be this total divided by three and we can actually check if the total is not a multiple of three we can return false because there is no way we can partition this into three parts after that we're just gonna initialize a accumulator and also a counter the they are zero in the beginning and starting to iterate over the numbers from left to right so if we hit the target we increment to the counter and reset the accumulation one tricky part is that we want to make sure that when the counter hits two we still have stuff on the right so it's not the immediate time when the counter hits two we should return true it's in the next generation so we do a checking here the reason for this is that there could be case where when the counter hits two we are at the very last element in the array so there is no next iteration there's no chance we have a third part if we do this counter check and return to after this update we might return rather than we might return to when we actually shouldn't so that's a slightly tricky here so that's the code to pass
|
Partition Array Into Three Parts With Equal Sum
|
fibonacci-number
|
Given an array of integers `arr`, return `true` if we can partition the array into three **non-empty** parts with equal sums.
Formally, we can partition the array if we can find indexes `i + 1 < j` with `(arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])`
**Example 1:**
**Input:** arr = \[0,2,1,-6,6,-7,9,1,2,0,1\]
**Output:** true
**Explanation:** 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
**Example 2:**
**Input:** arr = \[0,2,1,-6,6,7,9,-1,2,0,1\]
**Output:** false
**Example 3:**
**Input:** arr = \[3,3,6,5,-2,2,5,1,-9,4\]
**Output:** true
**Explanation:** 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
**Constraints:**
* `3 <= arr.length <= 5 * 104`
* `-104 <= arr[i] <= 104`
| null |
Math,Dynamic Programming,Recursion,Memoization
|
Easy
|
70,872,905,1236
|
931 |
hello hi guys good morning welcome back to a new video this has been asked by Amazon Google Bloomberg visa and Goodman Sachs in the last one to 2 years that's not frequent but yeah that's a good question it says that minimum falling path sum we are given n cross n array of integers called as Matrix now we have to return the minimum sum of any falling path again the sum needs to be minimum of any falling path now what they mean by a falling path is that a falling path starts from any element in the first row and it chooses the element in the next row that is either directly below or diagonally left or right so let's say if I start off with this first row I can choose any of the left down or right element for example for if we start off this first element as the first row then he could only choose the left down because the right is not even there and he cannot choose this because it is not even in the range so he just have to fall down and find the minimum part sum so you can see one of the following parts can be like this and this after trying for all the falling paths our minimum falling path is as you can see 1 148 which is 13 which is a sum of this falling path now in this if you just go and see many falling path sum is nothing but - 90 and - 40 now one nothing but - 90 and - 40 now one nothing but - 90 and - 40 now one obvious approach which comes to your mind is Arian um like okay we have okay if I am at specific node let's say I have at Max three possibilities either he can go left or down or right if I at this node left down or right at this note left right my left down and right so for every note you will see okay for this note also he will go left down and right although if the left is not possible then we will not go if the right is not possible we will not go but still we will have these possibilities okay for this left down and right okay again it's not there so it will not go so for sure we can see that okay we will have three possibilities for every of the row so basically I just know okay for every Row for every element I will have three options so if I just try to plot it okay for this again I'm just taking one row in the very beginning but I will have n rows like these M rows actually in the very beginning but let's take it as one row just to understand the time complex that how if I just try to just do a Brute Force then how it will actually work so for one I will have three op options to go to then for other I will have again three options then for this also again three options again three so you will see okay my three is actually being multiplied at every level I have n levels because I know I have n rows so in total my time will actually roughly be n into 3 power n multiplied with also initial number of row which actually equal to M but it is less than this but yeah at Max ballpark number will be near this m by n which is the initial number of uh cell else in the first row now which for sure is way too much according to our constraints because if you go back and see our n is actually 100 so explanation will never work so let's see that if we can figure out a pattern in this or basically something if actually we can see if something we can reduce so let's say if I take okay from two I can go to five again I can I could have also gone to six but yeah let's take example okay from two I'm going to five from one also I can come to five from three also I can come to five now if I ask you okay from five I can go to S from five I can go to 8 from five I can go to 9 now if you just imagine this entire stuff I have just bifurcated two levels into two different patterns which means if I just come back and see okay from two I could have gone to five and then seven from two I could have gone to five and then eight from two I could have gone to five and then nine as same from one I could have gone to five and then seven from one I could have gone to five and then N9 from I could have gone to five and then eight and the same way from three I can go to five and then seven from three I can go to five and then 9 from three I can go to five and then eight so you can easily see that uh this specific part above part you saw okay it is exactly same okay for this part again it's exactly same right for this part again it's exactly same so we know okay uh our upper portion is exactly same so basically if I'm coming from this path my minimum sum will be six and then I just have to try on this minimum sum with this cell and with this cell okay and the same here be eight 8 try two 7 8 and n and the same goes okay for this cell which is 7 7even and try for this cell so basically what I can do is I know okay my problems are actually repeating which means above pre-computed part can actually be like pre-computed part can actually be like pre-computed part can actually be like already be computed which is already same and then I can pre-compute this same and then I can pre-compute this same and then I can pre-compute this above part and can store it and use it to compute the next answer this is what I can actually do so what I tried out okay I know that okay I can try for this value so I will just store it okay at this what is the minimum value I can store okay now the minimum value if I am saying okay store the minimum value up to at this point D of I comma J so either that value would have been coming from the cell here or the cell here that's the only three parents which this cell I com can have right and I wanted to show okay what's the minimum value that could have been stored at this point so I know that okay I'm pre I know that okay I am storing the parent values also so whatsoever minum would have been there would have been stored here whatso minum would have been there up till so far let's say his parent would his parents would have also have been there so for sure minium would have been stored up till that point say same for up till this point so I'll see okay DP of I comma J which is this I comma J this IA J it is my DP of I comma J DP story minimum path sum up to this point if I take my all possible parents now what is my all possible parents are I -1 J-1 i -1a j and I - 1A J +1 so are I -1 J-1 i -1a j and I - 1A J +1 so are I -1 J-1 i -1a j and I - 1A J +1 so I'll take my all possible parents and when I have taken all of my possible parents I know that okay minimum I have taken from all of my possible parents let's say here minimum is 2 1 and three again that is the values right now but my DP values will sure okay minimum path some up to this point up till this point and say okay I know minimum has actually one I'll add my current value which is for sure add because I am going onto this I comma J so for sure I comma J value will be added so I'll just simply add Matrix of I comma J this will actually give me okay minimum path sum up to this point because I can considered all of it possible parents which are at Max 3 but by what about these cell for this cell there will be no J minus one so yeah for that you have to add a condition that okay if G minus one should actually be greater than equal to zero but Aran what about this cell like it's also like it's right is also not there so yeah for this j+ one should also less than less this j+ one should also less than less this j+ one should also less than M so this condition you will have to add so as to make sure and again uh you have to also add a condition that okay IUS one should be greater than equ Al to0 and same for IUS one should actually be greater than equal to Z so basically you'll have to have a base case that okay you'll start from the like this cell is the base case and then you start from the first cell which is the I equal to one so with this what we will able to achieve we will be able to actually compute the answer for every row just once because we are just taking the parents which are already having the computed values minimum pass some up till that point minimum so I'll just have to propagate that and see what is minimum for my current cell I comma J and thus I can just simply do it same like let's say for this I have to compute the I comma J minimum I will get my parents okay parent is i - 1 J-1 i - 1A j i - 1A J + parent is i - 1 J-1 i - 1A j i - 1A J + parent is i - 1 J-1 i - 1A j i - 1A J + 1 whosoever is giving me minimum I'll just get the minimum I'll add to my value will be the minimum path sum up till this I comma J so if I just write finally my answer will be okay minimum paths some up on all these points because you remember right I can start off from any of the point in the top row and can end at any of the point so my answer would have been stored at any of the leaf nodes so I simply check uh my DP of n minus1 comma J where I have to go on my J from like J from 0 to M which is I'll go on to All The Columns of my last row to know what is the best or sorry minimum best which means minimum DP value if I see the code it's pretty simple as what we have discussed so we will need to have a 2d DP array like just a matrix same replica then I'll have a base case where my first row my DP of Zer will be initialized with the same Matrix element because it's a base case I'll start on from my I = to 1 why I equal to start on from my I = to 1 why I equal to start on from my I = to 1 why I equal to 1 because I know that I need to access my IUS one so I it's good to actually start from I equal to 1 so if you want you can actually skip this condition also IUS one because it will for sure be equal more than equal to Zer because you are always starting from I equal to one right so you can also skip these conditions now coming on that if you start from start off from the like XY any row you are at you will go on to All The Columns of that row because you remembered right if this is a matrix and you are at this row so you have to compute the answer minimum path sum to all of these cells now to compute the answer for path for one of the Cs I comma J you have to go on to all of its previous period and that can be at Max 3 so for this specific cell I comma j i initialize my minimum value to in Max and then go on to all the parents which is i -1a j which is I -1 comma J I'll go is i -1a j which is I -1 comma J I'll go is i -1a j which is I -1 comma J I'll go on to I -1 J-1 I'll go on to I -1 comma on to I -1 J-1 I'll go on to I -1 comma on to I -1 J-1 I'll go on to I -1 comma jus1 which is nothing but I have to check okay I -1 should actually be more check okay I -1 should actually be more check okay I -1 should actually be more than equal to Z and I also go to i-1a J than equal to Z and I also go to i-1a J than equal to Z and I also go to i-1a J +1 which is the cell right here and with +1 which is the cell right here and with +1 which is the cell right here and with this I will be able to achieve my TP of I comma J will be the minimum Value Plus this again minimum value will be my parents whatso I have got minimum that will be propagated here and the Matrix will be the current because I am at the Ia J so that will for sure be added this value so I'll simply add that and that will be my DP of I which means minimum path Su up till the I comma J point and when I have tried on for all the possibilities which means for all the rows My ultimate answer will be actually at the final row but again final row it just say Okay ending at this cell I just have to know okay which cell is actually least so either I can just use an STL which is minimum element uh how we write minimum underscore element and have the vector end like this I can also do but uh if you want to do a simple oneliner for this easy understanding one so you can just go to all the elements of the last cell right all the elements of the last row so I'll go ENT trate on from 0 to M and then I'll get the minimum value and that will be actually my answer now as you can see I'm going on to all the cells so it's O of n² and also uh my space of n Square because you remembered I like you can say okay it's n into M or n into M but you if you remembered my cell here right here so the N is Matrix do length and like it's a square Matrix so it will be actually same now if you go and check back then it's O of n square and here also it's O of n squ as a space can we optimize it if we go back and look like obviously we can because for any DP of I because you remember DP for accessing my DP of I just look at this I'm only trying to access my DP of IUS one that's it no other previous state of DP is required so if my DP Matrix is like this I am at this specific cell I only need the previous cell all these cells which I have made are not at all using any space so I can just simply remove them so I'll use the same thing that I know one thing that for sure I don't need any of the space so I just simply do a very small modification and you will see the modification right here itself that here I had this DP Vector a 2d Matrix rather I will now make two vectors let's say Vector of int called as prev DP which means okay previous state of DP and Vector of end as let's say DP so this is a current state of DP which is the like this is the current row like DP and this is the previous row P DP now when this is the case then you can simply go and iterate on all of your rows it's just that before even going onto my next row I will just assign okay prev DP should actually become my DP right so as okay like PR DP is containing my previous state now DP will be calculated here itself so I don't need all these cases which will fall sure previously also like not needed here I will use prev DP because of DP of IUS one I use a prev DP here also I use a prev DP okay prev DP I'll use prev DP here also I use a prev DP p r v DP prev DP and ultimately in this answer I'll use a simple DP because that is coning my answer and this is the minimum value which is used by the prep DV and that's a matrix and ultimately here itself I'll use a DP itself not a prep DP and that's going to be my answer this is the only change you required for doing a space optimization if I look go and look back so I initialize my DP and prep DP exactly same as we discussed we will just initi just assign my PR DP to a DP so as to iterate on DP now um if you go back and look then you will have this assigning simple PR DP of j p DP of J +1 and simply ultimately of j p DP of J +1 and simply ultimately of j p DP of J +1 and simply ultimately you will assign that to a DP of J and here also you on DP of J because DP of J will actually contain the last values and that's how you can simply return the answer with space optimiz as o of n because you just using o of n for PR DP and O of n for o of n for your uh like new DB so which is O of n plus o of n which is actually o of n now your task is okay you saw that okay it is actually o of 2 into n right I can also reduce to O of n itself your task is how can you actually reduce to O of just n comment down below and yeah thank you so much for watching see you byby take care bye-bye
|
Minimum Falling Path Sum
|
maximum-frequency-stack
|
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`.
**Example 1:**
**Input:** matrix = \[\[2,1,3\],\[6,5,4\],\[7,8,9\]\]
**Output:** 13
**Explanation:** There are two falling paths with a minimum sum as shown.
**Example 2:**
**Input:** matrix = \[\[-19,57\],\[-40,-5\]\]
**Output:** -59
**Explanation:** The falling path with a minimum sum is shown.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 100`
* `-100 <= matrix[i][j] <= 100`
| null |
Hash Table,Stack,Design,Ordered Set
|
Hard
| null |
350 |
all right so this is intersection of two arrays two in javascript they're asking given two arrays find write a function that pulls out all the common numbers that are in the first array and the second array so the common numbers between array one and array two here are the twos here the common numbers in this array between uh the first array and the second array here are four and nine and uh you're supposed to return each element in the result as many times as it shows in the arrays so if this had a couple of extra fours and nines in here then those are also supposed to appear in the answer so how i approach this um i'm going to make a hash map for the first array and then i'm going to loop through the second array and see if the hash map has a count of that value so to make a hash map first i will i declare an object and then i'll also declare a resulting array for us to return so let's see we want to make first array of nums so make a hash map the first array of nums and then so step two is loop through the second array of the nums right and see if the hash map has a count of that value so to make a hash hashmap here we're going to do for loop and then how we do this is we're going to check to see if the object i exists so if it does not exist then we're going to create it and set it to 1. otherwise if it does exist increment it so as this goes through here this will build up a count of all of the numbers let's uh let's grab this one whoa let's close that there so this is going to make a hash map of all the numbers uh in numbers one let me show you what that looks like get a second here so this is a hash map that we built uh one has a count of two also has a count of two because there are two ones in here and there are two twos in here okay so now that we've done that we need to loop through the second array okay so we have a loop there and then what we're going to do is we're going to check to see if this hash map has that value greater than zero and if it does we're going to push out that number not the value but the actual key so push out that number out of the hashmap that we have and then decrease the hash map value like this so after that's done we'll have a result populated oops that needs to be returned there we go we'll have a result populated there after that's done make sure i type that right okay great i did uh so to show what this looks like uh we can just do let's do a console log here of the object and we run that right we've taken out all the twos out of this object and pushed them into the result there okay let me uh let me zoom out of this case you want to look at the entire solution here let's get rid of that all right don't forget to subscribe see in the next one
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
535 |
hey everyone today i'll be doing problem number 535 on leak code and decode tinyurl so the description might be confusing for some people but basically too tinyurl is some service where if we go over here you'll get like um some url that's like and then some gibberish and then some gibberish and then some gibberish and then this will resolve to whatever url you want so the user provides this it could resolve to google it could result to anything and basically so you encode it so you give it google and the output is some hash code like that and then when you do this and you decode it by typing it into the browser it resolves back into so basically we want some way so basically we want some way so basically we want some way where we have some unique id generation for a url that's passed so they're going to pass the long url we encode it and then we spit out that encoded string and then when they give us that encoded string we need to resolve it back into the original url so there's a lot of ways that we can do this but what i'm actually going to do is let's go ahead and let's originally just have some arraylist so originally it's going to be just a list of integers and we're going to call this uh array and basically what this is going to do and i'll explain this in a second but this is where we're going to store our url mappings so what we it's very simple all we want to do is we're just going to add this long url to our array and what we actually want to do is we also want to have a pointer so the pointer is originally going to be 0. so we want this url to be stored at the current pointer so basically just by adding it just by appending it's going to be at this pointer and then what we also want to do so this must return the encoded string so we want to uh basically return the string of the pointer and then also increment that pointer so that the next one that gets added will be for pointer one and then the next one too the next one three so we're going to return pointer which at this point is zero and then increment it so then at this point all we have to do is just simply return whatever url is at the current pointer they pass now it's in string so we have to go you know we have to do integer. parseint short url so that's what they're going to send here so basically what this looks like let's go ahead and run this um sorry and this has to be an end let's go ahead and run this and so and we want this to be a list of string let's go ahead and run this and then let's submit it and this is going to work but basically so what this would look like as a real service is when this is encoded it would be like and then it would be tinyurl.com1. so and then it would be tinyurl.com1. so and then it would be tinyurl.com1. so that's what we're going for here just very simple i just wanted to show my way of doing it and there's a lot of other ways you can map these to some randomly generated string like tinyurl does so like some hash code but it's however you want to do it so yeah i hope you guys enjoyed i just wanted to go over this really quickly thank you for watching
|
Encode and Decode TinyURL
|
encode-and-decode-tinyurl
|
> Note: This is a companion problem to the [System Design](https://leetcode.com/discuss/interview-question/system-design/) problem: [Design TinyURL](https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/).
TinyURL is a URL shortening service where you enter a URL such as `https://leetcode.com/problems/design-tinyurl` and it returns a short URL such as `http://tinyurl.com/4e9iAk`. Design a class to encode a URL and decode a tiny URL.
There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
Implement the `Solution` class:
* `Solution()` Initializes the object of the system.
* `String encode(String longUrl)` Returns a tiny URL for the given `longUrl`.
* `String decode(String shortUrl)` Returns the original long URL for the given `shortUrl`. It is guaranteed that the given `shortUrl` was encoded by the same object.
**Example 1:**
**Input:** url = "https://leetcode.com/problems/design-tinyurl "
**Output:** "https://leetcode.com/problems/design-tinyurl "
**Explanation:**
Solution obj = new Solution();
string tiny = obj.encode(url); // returns the encoded tiny url.
string ans = obj.decode(tiny); // returns the original url after decoding it.
**Constraints:**
* `1 <= url.length <= 104`
* `url` is guranteed to be a valid URL.
| null |
Hash Table,String,Design,Hash Function
|
Medium
| null |
554 |
Hello guys welcome to agar problem the series according to devi sharda problems call break and sudhir and fennel tree subscribe and vertical lines from top to bottom important subscribe to subscribe the 1234 you to you think of this particular example2 275 for all You have one to three little difficult example You have three losses and think about the great You will have one to three and you have three idiots-2 Total number of and you have three idiots-2 Total number of and you have three idiots-2 Total number of you can always be equivalent to subscribe 12345 subscribe in as a representative to minimize the se G equals to six - CO2 minimize G equals to six - CO2 minimize G equals to six - CO2 minimize CCSU that decreasing will keep on increasing 6 - Serial key point increase increasing 6 - Serial key point increase increasing 6 - Serial key point increase in rates to assure maximum number of deaths where is the number of this particular let's get all the latest number nine maximum number of deaths from The First Not The Best Software For Example First Number One Two Three Inch Width Subscribe Futile Spy Snacks Affair Question Number 5 Letters To This Type Of Structure Let's Notice Were Getting A Job To Maximize The Number One Number Three One Number One Side Key subscribe and subscribe the Channel Please subscribe and subscribe the Open Play List Sunao Admission Schedule Fat For One Who Gives Us Are Not Told In Amazon 2221 Ok Not Go To The Next You In Next Etc Position One By One Side End Position OnePlus 3 4 Neck Blouse Video Position 181 Year 2017 This Question And Will Be Coming Into A Here Let's Go To The Next Login In A Truly First President Of Width Next Cutting 1112 Number To The First Time For The Next To Go To The Number 3 Number 323 342 Subscribe Last Not Computing with you that all so then next week is back portion number five question one plus 6 plus one is equal to file co withdraw from the number 1434 245 is equal to two the number for so long as you have the maximum number of this That Anderson Alarms This is the maximum number of years before you will have minimum number of process only Arundhati Research and Lakshmi Market share to subscribe and subscribe this Video give total number of crisis and return subscribe to 220 yes so initially question let's go into storage account for Solving Indian Map In Random To Debit The Account Statement To The Position Radhe-Radhe Recorder Temple Statement To The Position Radhe-Radhe Recorder Temple Statement To The Position Radhe-Radhe Recorder Temple Shegaon It's An Order Of The Neel Point To Be Ordered Situation And Dances Are On Let's Get Started Vibration To Back To Cigarette And Inter Exam Select Declare It Matter Is Nancy E Saw Your Will Govardhan Number of Columns in ICC Twenty20 Is Lesson Wild Side Se Paun Inch 10 - 151 - The Video then subscribe to the Page if you liked The Video Qualification Report Handed Just One Three Times The Riot Cases Product Free Number Of Gadgets 32022 You Can See The Element Elements Of Obscuritism 20 - 4 - Elements Of Obscuritism 20 - 4 - Elements Of Obscuritism 20 - 4 - 1800 To Ki And Robot You Into Every Time Ear Bsc In Element And Decorations For Treatment And Subscribe To The Whole Of I G S Every Time The Element Arrested For example in research initially and dissolve vaccine excited the native place to visit in the election commission will be 323 506 b id maximum volume maximum value notes20 ago second is you can use that condition we check share it just volume maximum valley between the real Name of which is the value of the volume to be equal to what the value of world outside the maximum number of written test example2 Subscribe to check fine leg mein zamindar celebration on ki chapter solution thank you for watching patiently
|
Brick Wall
|
brick-wall
|
There is a rectangular brick wall in front of you with `n` rows of bricks. The `ith` row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.
Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.
Given the 2D array `wall` that contains the information about the wall, return _the minimum number of crossed bricks after drawing such a vertical line_.
**Example 1:**
**Input:** wall = \[\[1,2,2,1\],\[3,1,2\],\[1,3,2\],\[2,4\],\[3,1,2\],\[1,3,1,1\]\]
**Output:** 2
**Example 2:**
**Input:** wall = \[\[1\],\[1\],\[1\]\]
**Output:** 3
**Constraints:**
* `n == wall.length`
* `1 <= n <= 104`
* `1 <= wall[i].length <= 104`
* `1 <= sum(wall[i].length) <= 2 * 104`
* `sum(wall[i])` is the same for each row `i`.
* `1 <= wall[i][j] <= 231 - 1`
| null |
Array,Hash Table
|
Medium
|
2322
|
864 |
all right this is like my fifth time re-recording this re-recording this re-recording this is not as easy as it seems man all right i gotta make sure i have what i wanna say you know on the tip of my tongue all right so let's look at lead code 864 shortest path to get all keys so i'm not going to actually walk through any code but i'm going to just try to explain the algorithm as best i can in plain english so i feel like if you can understand the intuition behind how to do it in english then implementing in code shouldn't be too hard but um okay yeah let's get started so the question is as follows so we're given a 2d grid and our starting point is this at symbol uh these periods represent cells that are um walkable so that means we can walk on these cells a hashtag means we have a wall here so we can't walk on that cell and then lower case letters are keys and uppercase letters are locks so our goal here is to traverse the grid and find all the keys in the shortest number of steps possible and you know in this example here our best path is to go to the right so here we pick up the key the a key and later we can use that when we keep traversing once we come across this lock since we have the corresponding lower case letter key we can open the lock and pass through to get to the other side so yep we keep going until we hit this b right so if we were let's say if we wanted to go to the right and then go down uh and then hit this b here you know there's no reason to be going to the right at this uh crossroads but you know just hypothetically we wouldn't even be able to open this b because we don't have the b key for it all right so our goal here is to traverse in some sort of route where we pick up the keys that will allow us to cross through the locks that we need to cross in order to find the shortest path and so first of all we need to do one initial pass in order to first see how many keys there are total because otherwise how we know once we've you know how would we know when to stop traversing so in our first pass we have to first count the number of lowercase letters so that'll be our key count right and then once we actually do our actual traversing then we can you know accumulate you know a current number of keys and then once we our current number of keys reaches our key count then that means we've found all the keys and we should stop traversing and so also in the first pass it's not guaranteed that our starting point will be at this zero index so actually in the first pass since we're looking at all the cells anyways we can just we can record which cell the starting cell is supposed to be at and the reason we need to do that is because we need to uncue something into our queue in order to get the ball rolling to have like an entry point into to start searching the grid so um if you guys have done any other sort of breadth-first search types of sort of breadth-first search types of sort of breadth-first search types of problems um you know this is a pretty standard breadth-first search breadth-first search breadth-first search grid algorithm where you know we kind of just have a queue and then we on uncue all four directions you know obviously it has to be a valid um index right you know you can't go out of bounds and stuff and um you know you don't want to be unqueuing any uh um hashtags as well so pretty much you know it's a pretty uh standard breadth-first search algorithm standard breadth-first search algorithm standard breadth-first search algorithm and the reason you want to use breadth first search on these kinds of uh um well i guess in this particular grid problem is because you know when you find the shortest path um you know with a breadth first search you can count the number of steps you've taken level by level whereas with depth first search you kind of you know depth first search searches in a way where you first explore one specific path all the way until it reaches like a roadblock or something right so that individual path will have its own step count whereas a breadth first search everything is kind of synced up right like let me give you an example if we're at the zeroth step here we're at the starting point the first step is these two valid cells right and then the first step is all the valid cells that we can reach from the first step right which would be this cell so all these three cells that i just highlighted those would be the second step so you can see how we're um keeping track of the number of steps uh in sync and in that way the first time we find all the keys you know we can just immediately return that number of steps whereas you know if you're doing a duck first search maybe the first time you find all the keys it might not actually be the best option there might be other routes that you haven't even started exploring yet which could be a better um a shorter path so yeah so with a breath first search um grid type of algorithm you know you should keep a visited set as well and the idea behind the visited set is just that you don't want to be infinitely looping between two certain cells right so let's look at if we started at zero and we unqueued all the valid cells right we would on cue we were just on q zero one right and then once we're at zero one here uh you know a valid cell would be to go backwards to go back into the zero cell the starting point right but that would be pointless we'd just be sorry we'd just be looping back and forth infinitely between these two cells so that's just a waste of time that's not going to help us achieve you know finding the rest of the keys so typically in a breadth first search algorithm we would mark whatever we've already visited and put it into the visited set you know basically how you would denote that is just you would have like a tuple and then you know have the ij coordinate and then just put it into a set and um so i'll mention later that in this problem you know that's not enough for the visited set we actually have to take into account a third variable in our in each visited tuple we can't just look at the ij coordinate we also have to take into account our state and so i'll explain that later that's what makes this problem hard compared to other breadth first search grid algorithms and so yeah so let's take a look at this last example down here right so this is actually the one that gave me a lot of trouble when i was doing this and so essentially let's just take a look at the best optimal approach to finding all the keys here right so we have a key of e we have a key of b we have a key of f key of d key of c and a key of a so once we've collected all of those keys we can say that's our shortest path so let's actually look at the shortest path right so either we can go down we can go to the b here or we can first go to the e it doesn't really matter either way we're gonna have to uh you know we're gonna have to revisit some cells that we've already visited so you know typic like i mentioned earlier typically you don't want to revisit the same cell again if you've already put it in the visited set but in this problem um so let's see why you would actually need to revisit a certain cell more than once right so the best approach we can go b then come down here and then get the e key and then we go back over here to past the e lock then we go get the f then we come up to get the d then we pass back again to f pass a pass back again to this e and then come down uh and then get this c key and then we can go left or go down doesn't matter and then get the pass through the f lock and then get our final a key right so along this path we revisited several cells that we had already initially visited but let me start off with the first time we revisit a cell right so the first time we revisit a cell let's say we get the b let's just start from scratch again we get the b from the starting point we get the b we come down here and then we get the e right and then once we have the e we have to come back again we have to cross this cell again right but the reason we can cross this cell again is because we've picked up a new key so the first time we've the first time we came to this cell we had only picked up a b key so you know what we can do in our visited set is we can denote this by saying we visited the cell one three you know this is the cell one three with the state of just one b key all right we can use a string and then just keep appending to this string all the keys that we find so then the second time around so you know the first time we're here then we get the e then we come back here a second time you know it's still the same location but we've come here with a different state and what i mean by state like i've said is we have two keys now right we have the b and the e key so um if the state changes then we should be able to look at this key we should be able to look at this uh location again because these are two different tuples that we're putting into our visited set however if we were to um you know let's say we're here though right let's start from scratch again right so we go to the b first and then we come here for the first time once we're here for the first time we don't want to revisit the b that we just came from right um you know that would be pointless because then we would just start infinitely looping but if we were if we had a different state then we could go back to the b again and so you know so you have to make that distinction you can only revisit a cell if you're coming to that cell with a different key string right this is our key string which is our state if you have a different state you can come back to this cell again otherwise if the state did not change then you should not be going past the cell again so that's the key trick here for this problem and so you know there's another test case where um you'll actually have to pass through the origin again right so um you know i guess you have to account for that as well so maybe um i actually that would just fall under the case of having a different state as well so yeah you just don't want to be passing the origin if you have the same state but if you have a different state then it'd be okay to pass the origin as well so those are just some things to consider um let's see how long has this been so far this has been 12 minutes all right so i guess that's the general gist of it i mean i don't want to actually um go into writing the code because i feel like if you if people look at the code then they'll be too reliant on just trying to memorize the lines of code i think it's better if you can just you know really grasp what you have to do in english in an english algorithm and then you'll be able to implement it pretty easily so um i think yeah i think that's pretty much all there is uh all i have to say about this problem um you know it says return the lowest number of moves to coil keys if it's impossible return negative one so you know basically if you've you know if you've explored all the options of all the things that you've put onto the queue you know that means like at the end like maybe if all the um possible neighbors that you want to on cue have already been put in the visited set then you know then there's absolutely no options left to traverse then you would just output negative one um yeah so the reason i'm doing this problem in the first place is because i actually saw this i actually legitimately saw this in a tick tock online assessment and you know it wasn't the exact same problem but um there was some variation to it and it was very tough i actually could not get it and um you know even though i had studied this exact problem on leak code before the online assessment i still struggled with the variation of it on the actual assessment so hopefully you guys learned something in this video if you actually want me to implement the code next time and then walk through the line by line of what each line of code is doing i could do that but i mean ideally i want you guys to be able to just try that on your own because that itself is you know another um i mean i guess that's also another good learning experience if you can um just take what i've said here and then turn it into code so that'll help you grasp the problem even more as opposed to kind of just you know visually memorizing the lines of code and like where the indents are and stuff you know that you know it's better for you to recall what i've said so that you can kind of just work with what i've said in english and put into code so yeah if you guys have any other questions you want me to attempt i'll try to keep it only to le code hards um i think there's you know ma unless there's like some um tough mediums that have that don't have many resources online then i can try my best to explain some of them so yeah um that's about it hope you guys learned something uh yeah
|
Shortest Path to Get All Keys
|
image-overlap
|
You are given an `m x n` grid `grid` where:
* `'.'` is an empty cell.
* `'#'` is a wall.
* `'@'` is the starting point.
* Lowercase letters represent keys.
* Uppercase letters represent locks.
You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.
If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.
For some `1 <= k <= 6`, there is exactly one lowercase and one uppercase letter of the first `k` letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.
Return _the lowest number of moves to acquire all keys_. If it is impossible, return `-1`.
**Example 1:**
**Input:** grid = \[ "@.a.. ", "###.# ", "b.A.B "\]
**Output:** 8
**Explanation:** Note that the goal is to obtain all the keys not to open all the locks.
**Example 2:**
**Input:** grid = \[ "@..aA ", "..B#. ", "....b "\]
**Output:** 6
**Example 3:**
**Input:** grid = \[ "@Aa "\]
**Output:** -1
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 30`
* `grid[i][j]` is either an English letter, `'.'`, `'#'`, or `'@'`.
* The number of keys in the grid is in the range `[1, 6]`.
* Each key in the grid is **unique**.
* Each key in the grid has a matching lock.
| null |
Array,Matrix
|
Medium
| null |
1,217 |
hello guys welcome to algorithms made easy today we will be discussing the question minimum cost to move chips to the same position in this question we are given n chips with the position of ith chip as position of i now we need to move all the chips to the same position and in one step we can change the position of the ith chip from position i to position of i plus 2 or position of i minus 2 with a cost of 0 and position of i plus 1 or position of i minus 1 with cost 1. we need to return the minimum cost needed to move all the chips to the same position now at first the question looks a bit tricky if we are given three chips which are positioned at one two and three we will first move the third chip to for the first position without any cost and then move the second chip at the first position with one cost so we written output as one now if the chip structure is like that then in this case we can move these two chips to the second position one by one with the cost two now coming to the hints given with the question is the first move keeps the parity of the element as it is what it means is if we see over here the parity of three is an odd and parity of one is also odd and the first move that we made for three is at one and the parity is still is odd for the chip that were positioned at three so that means the first move will keep the parity as same now the second hint is the second move will change the parity if we see the chip at position two when moved with cost one changes its parity from even to odd so that is a change now the third hint given to us is since the first move is free if all the numbers have the same parity the answer would be zero yeah that means if all the values are at even position or all the values are at what position then there won't be any cost involved and the answer would be zero now we need to find the minimum cost to make all the numbers have the same parity now what will be the cost coming back to the approach what we need to do is we need to first find how many values are in the even parity and how many values are in the odd parity to do so we will have two variables even and odd once we have these variables we'll iterate over the position array and find how many are even or odd now as a third hint suggests that if the numbers have the same parity then an answer would be 0 that means so if all the values are even or all the values are odd then we simply return 0 otherwise we need to return the minimum of the 2. now how do we know that the minimum will be answer as we need to find the minimum cost involved and we can apply this logic on this example we see that instead of moving these three chips to the third position it will be better if you move these two chips at three position to the two and this will involve cost which is the minimum of this two which is two when we run this code we get the right result now let's check for the second example as well it is also giving the right result let's submit this so it got submitted the time complexity of this algorithm is o of n as we are traversing over all the position array and the space complexity will be of 1 as we are not using any extra space thanks for watching see you in the next one
|
Minimum Cost to Move Chips to The Same Position
|
relative-sort-array
|
We have `n` chips, where the position of the `ith` chip is `position[i]`.
We need to move all the chips to **the same position**. In one step, we can change the position of the `ith` chip from `position[i]` to:
* `position[i] + 2` or `position[i] - 2` with `cost = 0`.
* `position[i] + 1` or `position[i] - 1` with `cost = 1`.
Return _the minimum cost_ needed to move all the chips to the same position.
**Example 1:**
**Input:** position = \[1,2,3\]
**Output:** 1
**Explanation:** First step: Move the chip at position 3 to position 1 with cost = 0.
Second step: Move the chip at position 2 to position 1 with cost = 1.
Total cost is 1.
**Example 2:**
**Input:** position = \[2,2,2,3,3\]
**Output:** 2
**Explanation:** We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.
**Example 3:**
**Input:** position = \[1,1000000000\]
**Output:** 1
**Constraints:**
* `1 <= position.length <= 100`
* `1 <= position[i] <= 10^9`
|
Using a hashmap, we can map the values of arr2 to their position in arr2. After, we can use a custom sorting function.
|
Array,Hash Table,Sorting,Counting Sort
|
Easy
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.