id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
1,845 |
hi everyone Let's uh start with the today's lead code challenge which is seat reservation manager so in this problem statement we'll just have to implement the seat manager class so as a Constructor to this class we will be given a number n which is the number of seats and we'll have to manage N seats which are numbered from 1 to n and all the seats are initially available and the other two functions are resered and unreserved so if the reserve function is called the smallest number unreserved seat is reserved and then we'll just have to return that number and if unreserved function is called on any seat number that seat number will be undeserved let's try to understand this problem using an example so in this example like we are given uh let's say m number of queries the first one is seat manager and the query value is five so we will be having five seats numbered from 1 to 5 so then uh two Reserve function call are made and then one unreserved call and then further four Reserve function calls are made and after that unreserved function call so let's try to simulate this example so uh so after the seat manager function is called we'll just uh maintaining an array of five size you can consider them as a as our seats so after first two Reserve call when the first Reserve call was made we will just reserve the first seat okay and then after um after that call on the second Reserve call we'll just reserve the second number of seats because we will just have we will have to uh reserve the smallest number seat available so now which is the smallest number seat available we have three as uh available seat so but we will just have to call uh undeserved function so we will just undeserved the seat number which is given with the query which is two so we will unreserve the two and Mark it as a minus one after that uh four Reserve call are made so these four seats will be reserved 2 3 4 5 so all the seeds are reserved now so now they have called the unreserved function call with the value five so we will unreserve the seat at uh number five okay so this is the state of the array after uh after completing all the queries so let's analyze the function calls for reserve and unreserve so here in this example we are tracking it using an array so if we try track that using an array so for every Reserve call we will have to check which is the smallest number that is available for us to reserve so for that we'll just have to iterate the array and if there are M number of calls uh for the reserve function so and the number of seats are n so our time complexity will go to n into M let go to quadratic form the UND deserve is simple because we can just directly Mark the seat to minus one if we have to un reserve it so this Reserve function is very costly for us if uh we have a very large number of n okay so now let's try to move to the next approach so here if we go with the Brute Force which is our array approach so our Reserve function is going to take a load of time which is of n cross M let's try to think of a better approach here instead of taking a array why don't we take a Min Heap because every time we have to get the minimum seat available from our set of seats and um when we have to just uh so let's say if we have to call a reserve function over number of seats from 1 to 5 what we will do is we will just initialize the Min Heap uh in the Constructor with all the seats available so initially all the seats uh from 1 to five was available so we will add all the items in the Min Heap so if we have to reserve a seat we'll just have to prq do pole the first element from the priority CU so which would be the minimum element which is one so if we have to call unreserve function we can just directly add that seat number to the priority Q okay so this is the template which is given to us we'll just have to fill the template so here we decided to go with the priority Q so we can initialize the priority q and add all the elements upon reserving we can just directly pull from that priority q and return to the caller and upon unreserve we can just uh add that seat number in the priority que guys let's try to write the code for this problem here we can uh take a q of integer we will make it a priority CU priority Q initializing the priority CU okay and initially we decided to fill up this priority CU with all the number of all the seats which are currently available I less than equal to n seat numbers are from 1 to n seats are available and we are adding all the seats to the priority Q do offer seed value and when we have to call the reserve function we can just directly priority Q dot pole so PQ do pole will give us the smallest number from the priority queue and as well as it will be removed from the priority queue and upon making the unreserved call we can just offer the seat number okay let's try to run the code then we will further try to optimize it I'm just submitting the problem okay it is submitted but is it is not that improved version so let's try to think of a scenario where uh the seat number is very large and the number of queries are very small let's say seat number is 10 power 7 and we have to just make a couple of queries let's say two three queries in that case it is of no use that we are initializing this priority queue in this in the Constructor that is very computational heavy now let's try to think of a scenario where uh value of n is very large let's say 10^ 7 and we have to large let's say 10^ 7 and we have to large let's say 10^ 7 and we have to just perform 10 queries or maybe just uh Reserve queries no unreserve query is there so in that case uh there is no need to maintain a priority queue and prefill that priority queue using all the available seats so instead we can just directly take a variable and make and keep on incrementing that their value let's try to understand that using uh code that would be more clear so we are not uh prefilling the priority Q instead we are making a marker variable and initializing it to the one because first the first our seet number is starting from one so in that case um our unreserved function will look like the same way priority Q is offering a seat number so in the priority Q we will just add that seat number that we have just unreserved so now we have two possibilities either the marker uh is pointing to the undeserved seat or maybe any unreserved seat is available in the priority q and the priority Q seats will always be less than the marker uh check for the priority Q value we will check if the priority Q is empty if our priority Q is empty it means that priority Q is having some seat which is uh which was unreserved later on after getting reserved so in that case that unreserved seed will definitely be less than the value the marker is pointing to so in that case we can just directly call the priority Q dot Pole and the case where priority Q is empty in that case we can just directly return the value of marker and then after returning the value of marker we can just increment it to the next available seat let's try to run this solution and then we will make a dry run accepted trying to submit that problem okay now it beats 94% of the users so it is uh it beats 94% of the users so it is uh it beats 94% of the users so it is uh better optimized now okay I'm trying to run that on the same example so here uh in the starting we are given seed manager with five so our marker is pointing to one the one is the first sheet available for us and the priority Q is empty okay the market is pointing to one priority is empty our seat manager function is initialized now Reserve call is made so we will check whether there is any available cat in the priority key or not if there is no available seat in the prq we'll just increase our marker and um we'll just return the marker value and increment its value so we will just return one then the first seat is available and the marker value will now point to2 and for the further Reserve call we will just return two and the marker value will be increase to three and upon undeserved call it is asking us to unreserve two so in that case we will just uh add the two add two in our priority Q now we received the reserve call and in that case what we have to do is we have to reserve the shortest available seat so we see that the priority Q is not empty so it means there is always a smaller seat available in the priority Q than the marker variable so we will Reserve that second seat by just uh removing it from the priority q and then upon the further Reserve call Priority is empty our marker will move to four three will also be reserved and then uh after two more iteration four and five will also be reserved now we will get the unreserved call for five so in that case we'll just add 5 q 5 to over priority Q I hope that is clear to you if do you have any doubt you can comment down below thank you guys
|
Seat Reservation Manager
|
largest-submatrix-with-rearrangements
|
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`.
|
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
|
Array,Greedy,Sorting,Matrix
|
Medium
|
695
|
1,406 |
hi guys good morning and welcome back to the new video so basically in the last video in the last yesterday's video we saw Stone game two for sure last video also I told you that stone game one and stone game three are much easier than the stone game too although song and two was medium marked but still it is actually like if you have done that then I'll for sure recommend that try Stone game three it's a high chance that you would be able to do it maybe some optimization stuff I'll show you the entire recursion tree as you know other people just like just say okay it's the recursion but we actually make the request entire version and show you then actually go and memorize it then bottom up then actually optimize that before let's add the problem statement itself um I'll keep the energy low as you guys want and let's have it quick cool Alison Bob continues their game with the pile systems okay Alice and Bob are the two players who have the piles or stones and uh stones are arranged in a row cool uh the card is done and they have to play and I'll start it first now the player he can choose he or she can choose one two or three stones cool uh the score of each place is the sum of the values of the stones there um they the objective of the game is to end with the highest score will everyone like anyone they wants to end the game with the highest score and the winner is the player with the higher score cool uh the game continues under all the stones have not been taken so all the stones will get exhausted when the game ends uh assume that both Alice and boss plays optimally which means both will try to maximize their score and return Alice if thallis wins which means Alice have a higher score than Bob written box with the Bob wins which is which means that Bob has code analysis if both have them both of them have same score just written a time as we see in the first example we can choose one two or three stones so Alice will try to choose the starting three stones and then power will choose the last Stone then for sure no matter what Alice will have a score of six and Bob will have a score of seven still Bob will have a higher score Bob will win in the next example Alice will try to choose the starting three scores uh her score will become six Bob score is minus nine either score is more RS will win in the next example um yeah for sure we will take one two which means we will try for every possible options option we have the first player have the option he or she can take although it's Alice uh so she can take first like starting only one stone and the remaining it will leave on to Bob that okay how the Bob want to optimize which is maximized um his difference I'll say I'll show you what's the what I mean by maximizing the difference basically what I want is okay I want to choose to bring out the maximum score of me which means I will just try to bring out okay what is the maximum possible difference item bring from me and Bob which means Alice and Bob if this I will just increase and this degree so basically this difference part will force or maximize this rather than increasing this individually and decreasing this individually again just increase this difference itself and that will work so rather than operating on both of them I can just operate on the difference part of the scores thus I can just easily say okay if the at last the difference is positive which means RS 1 if it is negative the Bob wants if it is equal cool now what I do is initially when I have these Stones then for the first one Alice for the first one she has two options she can choose one stone which means take one stone she can choose two stones and she can choose three stones right and if she choose one Stones the remaining part it is in the hands of Bob now but Bob also will try to maximize his score which means if Alice get this Stone so her value will be added by this value her in total value will be at about this value minus what Bob will try to maximize by this difference now RN why this difference because see ultimately whatsoever if Bob let's say Alice uses this Bob chooses this let's say Bob chooses this and then Alex uses this if I just saying this difference so it is nothing but B minus a which is actually and this was a also so it is a minus P minus a so basically Alice's is being added and Bobs is being subtracted in recursion itself thus I can just simply do one thing I can just try for all three of possible options take one score one stone two Stone and three stone and what's your maximum difference I can get I will just grab that maximum difference cool so for sure I started with this initial array of stones cool then in the initial Alice has a chance she will take either one stone cool okay one stone two stones or basically Three Stones if she takes one Stones now remaining part is to be decided by Bob that he will try to maximize his difference cool if she choose two stones the remaining part will be decided by Bob if you choose three then the remaining part by Bob now remaining part by the BOB So for sure he has only one so he will take that one now Bob will get that one I will come back to the recursion tree but yeah right now we are going down which means we are trying to choose all the possible options we'll come back also wait a minute cool now in this option if we saw the game Alice choose one now Bob has again chance of choosing either one or two or three again Bob choose one Bob choose two Bob choose three again the part it went to Alice to choose again it went to Alice to choose and here it just exhausted so no worries here again Alice has two options to choose one or to choose two and let's choose one Alice choose two exhausted happy it has one options Okay just grab one cool then Bob grabbed one here also as we are here the Bob has two options choose one choose two Bob choose one Bob choose two exhausted cool no worries then again it's a chance of Alice choose one and thus it is done now okay it is how we saw that okay Alice in Bob's and that's the reason I just use different colors to show you okay what is Alice is grabbing and what is Bob is grabbing Alice is grabbing uh the blue ones and the Bob is grabbing the green ones now as we are going back what I wanted is to bring maximum from me so as it was the last chance for Bob so he will try to push in the maximum which is the seven now as it went up now it is the chance of Alice to maximize which means maximizes which means a which means R score minus the Bob score which came as maximum from bottom was seven so her score was three right now for this part so 3 minus seven is minus four that's the reason it will just can push in minus four but here this case RS can have a score of 10. so why not I if Alice is there at this point of time then Alice will choose a minus four or ten for short time right so Alice will just push in this 10. so from this point Alice pushing 10 because it is a maximum score she can get while in this case while okay let's go up the tree initially now while in this case if I just go on that okay here the maximum score pushed in by Alice is 10 but the Bobs want to maximize it so he has a two so two minus 10 it is minus eight thus Bob is pushing in minus it because it is a score he can get but if we just go on to the next tree then here we know okay it was the last chance of Alice it is the only score she can achieve so if she pushed in this seven now this seven got pushed but Bob has to maximize so obviously okay my score is five Alice bought her score maximum because it was RS chance next but RS bought her score maximum as seven so I can push in 5 minus 7 which is minus two okay it is my show which I can push it at this point when above all two 3 and 7 he can push in the 12 for sure cool then you easily see that okay now it was the Bob chance at these at this point it was a bob chance so out of minus eight minus 2 and 12 Bob will try to push in the maximum because he want to maximize thus Bob will try to push in the 12. cool if he just go on to the next street then what happened it was the chance of as simple as that it pushed in Harris portion is 7 maximum score Bob tried to push in three minus seven which is minus four um again Bob can also push in a three plus seven which is ten then out of this Bob can actually push in the 10 which is the maximum score and thus if it just goes up it is the Alice core it is above score which is coming up as 10 then it just goes up as 3 minus 10 as minus 7. sorry this is minus seven now as it goes up cool other has option it is six it is seven which is the Bob is bringing up the score as seven it is six and seven the score which goes up is minus one now at this point Alice she is getting either minus 11 minus 7 or minus one she will try to maximize hers that is minus one now ultimately the maximum difference which Alice can achieve is a minus one I'm saying Alice can achieve a maximum difference of minus one but the difference is minus one so which is Alice minus Bob is actually a negative number for sure Alice lost but for sure we tried to maximize the maximum Alice difference which means it is 6 minus seven six is the maximum score for RS which Alice can get cool that is how you can actually build a recursion which means recursion is going down while coming back it is Computing up cool now we easily saw what the recursion was doing and this is okay at this point I had to compete for three like starting from three and so on so forth right at this point also I saw that I need to compute from this part so we can easily see that it has a repeating sub problem for short and also here it just start had to start from this last part and he also that's from the last part so also you can see repeat is a problem and we can show okay for sure we saw the above recursion it has a repeated sub problem then for sure it's a memorization case which means I will just firstly try to build my recursion tree which means the simple recursion and then I will just try to memorize it by a simple three DP steps cool what we saw in the above logical intuition and logic just implementing the same stuff how simply asking for the value this value is nothing but the difference asking for the difference starting with the index 0 and passing in the stone value because we need the area itself now ultimately what I will do the difference if it is more than zero for sure Alice 1 less than zero above one same time now comes the main interesting particular version for sure I will start with index 0. now what will happen as I said base case simply okay let's is nothing but Stone value so Stone value is the n size so if it has not reached until then you can just move your eye cool now for sure I had three options take one take two and take three now if I take one which means I take the current element so I take the stone one stone I and then I just said okay bring out the other player just bring out the maximum score you can get if you just start from the next index because I grab die you just grab from the I plus one then bring out the maximum you can achieve because for sure other player will try to bring out the maximum he or she can achieve now if I take that 2 then I will just say firstly up standard condition that because you are accessing another element next to you so it should actually exist that's the reason I'm just having a small check okay if it is actually existing or not and then I will just grab the sum of the two value which means right now I'm standing at I and I plus one I have taken the stones two stones and then I'll just ask other player to bring out from the next Stone what you can get maximum and same for the if I take three then I just take the three stones and then ask the other play to bring out the maximum from the like the from the I plus thirds too that is how I will take all the Three Stones which means all the possible options you see stone now it is a recursion now while coming up which means when the recursion is done while coming up I just choose the maximum out of all the options I can have that is how I can just simply return my answer which means I tried all the possible options and grabbed the maximum difference but we saw that it was the case of recursion with memorization which means if you have a repeat this problem so for sure we will try to optimize it which we will try to memorize it how we will do it simple three-step DP steps firstly a dpfi we three-step DP steps firstly a dpfi we three-step DP steps firstly a dpfi we just firstly we initialized our DP now you will say I didn't initialize it with minus one because we saw the DP is storing the values and values is nothing but the difference now difference it can be negative also it can be minus 1 also so I can't initialize this with minus one I can initialize this is something which is not possible into max is not possible because I just want to grab the maximum difference possible and it can't go beyond the limits of which like the constraints limit it can't go beyond that cool so I just grabbed it with intermax you can also choose any other number which is you see it's not viable in this it's just to Showcase if that number has not occurred before now it is occurring so how you have to do it cool uh you should initialize your DP just check if that DP has not mined into max as the value which means it has been overridden which means it has come already so just dpfi and a simple return while returning just please populate your DP also and that will simply help you just memorize these steps and your complexity will become simply open and spaces over no that looks nice that looks great uh for sure the code is below for you guys to actually understand and copy the notes are also down below but can we optimize it is it possible but if you want to think of even optimization you have to actually convert this code to a bottom-up convert this code to a bottom-up convert this code to a bottom-up approach which means a tabulation approach then only you can actually think okay is it possible to actually optimize in browser I'll just copy paste the entire stuff I just copy paste the entire stuff see I will just entirely copy paste this stuff these are the three steps right entirely copy paste this part down below simple as that you will see I initialize my DP for sure as it's a linear so I just initialized with 0 as it is being grabbed no worries you can just have anything what do you want uh now as you saw it was going from index 0 and then going up till end and then coming back thus I know okay it is coming back because it needed you saw right it needed the value of I plus 2i plus t i plus 1 like this so it will go up to the n and then it will just bring this values from the end thus I know it has to go up till n and then because it's a recursive which means it goes to the length then come back now when it is coming back from n minus 1 which means I started recursion with I equal to 0 I will start my bottom up with I equal to n minus 1 because I am coming back now coming backwards from Ms one to zero first option as simple as that I just grabbed one I just grab two grab three exactly same code you will see exactly simple you will see exactly same code it's just that rather than recursion like recursion part I just actually write the DPS itself because DP has been computed TP has been computed DP has been completed I didn't have because you are going from back if you are Computing IE then I plus 1 I plus two and I plus 3 has already been computed that is the reason I am going backwards I'm exactly same code as it is entirely same and at last this code is also entirely same because we know our answer is actually stored at DP of 0 because you know in the recursion you are going from I equal to zero that is the reason your answer was stored at dp0 thus I can just simply exactly same code here also I can simply see I converted my entire question without even writing without doing modifying very much code like I just modified very few lines or like very few words itself and I just converted my entire code to the DB iterative DB or the bottom of DB same the time and space both are exactly same but if we just go back and clearly look then we can easily see for computing my DP of I just only need my DPF I plus one I plus 2 and I plus three no other DP state is being used right correct so why to actually store this entire dpra why to initialize this with entire DP right as simple as that so I can maybe reduce the space from o and of n to O of three which is constant which is over 1. I can actually reduce it yeah I can why because I am actually for this DPF I am only using dp5 plus one I plus three I can just have a simple DP array of three size and that would work or I can have a three variables and it will also work so you can have anything just three variables a array of size three anything but it's constant space thus I can easily say that okay I just did a very small modification I just made a DPR of size three because I know it should only required three then every point I know okay it needs to compress to a size three I compress everything because see you saw it was I plus one I plus two I plus three I can press it into a three size which is mod 3 as simple as that and also I is also not three just these modifications just these three simple four simple modifications actually converted your space from o of n to actually o of one that is how you optimize your space from o of n to O one and that is your time finally optimize DB is actually of a space of over and code of C plus Java and python is down below I hope that you guys liked it I try to keep it short and simple um but like actually for sure uh we actually make every VC the only difference between us and others is that we make the entire recursion tree we explain the entire question tree I would have just spoken okay just have the recursion okay it is the one period it is another pair and then make the version but if you just make that question entirely then it actually shows that okay how the things are working that's the reason we just spent time on that part that is all uh thank you
|
Stone Game III
|
subtract-the-product-and-sum-of-digits-of-an-integer
|
Alice and Bob continue their games with piles of stones. There are several stones **arranged in a row**, and each stone has an associated value which is an integer given in the array `stoneValue`.
Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take `1`, `2`, or `3` stones from the **first** remaining stones in the row.
The score of each player is the sum of the values of the stones taken. The score of each player is `0` initially.
The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.
Assume Alice and Bob **play optimally**.
Return `"Alice "` _if Alice will win,_ `"Bob "` _if Bob will win, or_ `"Tie "` _if they will end the game with the same score_.
**Example 1:**
**Input:** values = \[1,2,3,7\]
**Output:** "Bob "
**Explanation:** Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.
**Example 2:**
**Input:** values = \[1,2,3,-9\]
**Output:** "Alice "
**Explanation:** Alice must choose all the three piles at the first move to win and leave Bob with negative score.
If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.
If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.
Remember that both play optimally so here Alice will choose the scenario that makes her win.
**Example 3:**
**Input:** values = \[1,2,3,6\]
**Output:** "Tie "
**Explanation:** Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.
**Constraints:**
* `1 <= stoneValue.length <= 5 * 104`
* `-1000 <= stoneValue[i] <= 1000`
|
How to compute all digits of the number ? Use modulus operator (%) to compute the last digit. Generalise modulus operator idea to compute all digits.
|
Math
|
Easy
| null |
1,887 |
hello everyone today we will be solving the lead code daily challenge problem 1887 reduction operations to make the array elements equal so we are given an integer array and our goal is to make all the elements inside that array equal to complete one operation we have to follow the given steps we have to find the largest value inside the array we have to find the second largest value inside the array and we have to reduce the largest value to the second largest value and we have to return the number of operations to make all the elements equal in the given example one we have the array as 5 1 and 3 so in order to make all the elements equal we have to perform the operation we have to find the largest element and we have to reduce it to the second largest element so in this array our largest element is five and our second largest element is three so we reduce 5 to three our new array after first operation will be 3 1 and 3 in the second operation during the second operation we have our array as 3 1 and 3 so the largest element here is three and our second largest element is 1 so we reduce 3 to 1 so we get our second array after second operation as 1 and 3 for the third operation we find the largest element as three and the second largest as 1 so we reduce our largest element 3 2 1 so after the third op operation all the elements inside our array are equal in order to solve this problem we have to sort the array first after sorting the array we get our array as 1 3 and 5 so our first operation would be so our first operation would include finding the largest value and finding the second largest value so our largest value is five and our second largest value is three so we have to reduce our largest value to second largest value so we have to reduce this 5 to 3 so we will get our new array as 1 comma 3 for the next operation we have to find the largest value our largest value is three and our second largest value is 1 so our new so after the second operation we will get our array as 1 comma 3 1 comma three so after the second operation we get our new array as 1 and three so for the third operation we get the largest value as three and the second largest value as 1 so after the third operation we will get our array as 1 comma 1 so all the elements inside our array are equal so it took three operations to make all the elements inside the array equal to find the total number of operations to make all the elements inside the array equal we have to follow the following approach so uh in the given array we have 1 2 and 3 so as our steps involve finding the largest element and converting it to second largest element at the end we would have to convert all the elements to the smallest element inside the array so our so we have to perform operations to convert all the elements inside the array to the smallest element step by step so in our first step we would take three and we would take two as the second largest element we have to convert three to two so uh it becomes 2 and two so in the second step we will conver convert 2 to 1 so we will get 1 2 so it took one operation to convert this two into one and it will take two operations to convert this three into one so as we saw it took one operations to convert 2 into one and two operations to convert three into 1 so now for solving this problem we will initialize our temporary variable to minus one and our count to minus one and our result to zero so in the first iteration we will check if the nums of uh if the element is equals to Temporary variable if it is not equals to Temp we will convert it we will assign temp to I variable so we will assign temp as one and we will increase our counter by one so we will get count as one so for converting one to the smallest element we need no operations so our count is zero in the second datation it will check if temporary is equals to 1 if it is not equals to 1 then it will increase the counter so here the temp is equals to 1 so we will continue the operation so when we come to the second index I nums of I is equals to 2 here our temporary variable is not equals to 2 so we will assign our temp to two and we will increment our count by one so C equals to 1 so now we will increment our result by count so in the fourth iteration when index 3 we have nums of I equals to 2 so here our temporary variable is equals to 2 so we will just increase our result by C for the fourth iter for the fifth iteration we have temporary not equals to three so we will assign temporary as three and we will increment our counter by one so we will get our c as two so now we will increment our result by C let's code now so first of all we will sort the array using do sort function now we will initialize our result to zero our temporary variable to minus one and our Count 2 - Count 2 - Count 2 - 1 now we will iterate through our array now if we will check if the temporary variable is equals to nums of I if it is not equals to nums of I we will assign nums of I to Temporary variable and we will increase our count to one and then we'll increase our result to count result by count and then we'll return our result so our example test cases are accepted so now we will submit our code yeah so our approach for solving this code is correct
|
Reduction Operations to Make the Array Elements Equal
|
minimum-degree-of-a-connected-trio-in-a-graph
|
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`.
3. Reduce `nums[i]` to `nextLargest`.
Return _the number of operations to make all elements in_ `nums` _equal_.
**Example 1:**
**Input:** nums = \[5,1,3\]
**Output:** 3
**Explanation:** It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\].
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** 0
**Explanation:** All elements in nums are already equal.
**Example 3:**
**Input:** nums = \[1,1,2,2,3\]
**Output:** 4
**Explanation:** It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\].
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 5 * 104`
|
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
|
Graph
|
Hard
| null |
343 |
hi my name is jason we're going to be going over this problem integer break um the goal the main question of this problem is you're given an integer how can you break the integer up such that it sums to the target n and how can you maximize the product of those integers so let's say for example you have the integer six whoops let's say for example you have the integer six right dp of six okay so here's how you can sum to six you have five plus one you have four plus two we have three plus three on and on one plus five and we can then calculate the product of six and the product of six the largest integer break would be nine that is one case of it and that is the dp of six which is nine the second case is let's say we have the number eight how do we calculate the integer break of eight well we have seven plus one six plus two five plus three four plus four on and on one plus seven and when we calculate the product of these right we have 7 12 15 16. now this is one case remember we can also split up more than just the integer so what i mean by that is let's focus on six plus two right what's another way of writing this we can also write this as three plus two this will sum to 8 and if we write it as such we now have 3 times 2 which is 18 and thus the product sorry the integer break of 8 is 18. now there is one question i have which is okay so we know we can split up this six right well because this is dynamic programming we realize hey we've actually solved this sub problem before where have we seen this three times three or three plus three is equal to six right well if we look right here 3 plus 3 we realize we already solved it for dp of 6. and we know that dp of 6 is 9 and what i'm basically saying is we can actually plug in dp of 6 right and multiply that result by 2 and we get 18 and that is integer break of 8. so knowing that how can we actually code this let's start with an array starting from zero and what we can do is we can actually calculate all of the integer breaks from the bottom up so i'm going to initiate the array to n plus 1 as there are we want n plus one indexes that we can access if we do this you'll realize you have one two four and five which is three times two the energy break of five is six and finally we have six we can calculate using this which is nine and finally we have seven which we can say is four times three or 4 plus 3 which is 12 we have 8 which is as we calculate below 18. so what we can do is we can initialize dp of 1 to 1. when we get to dp of two we can calculate okay using this method right here i'm going to call this method a where we just simply iterate through and we calculate how many different calculate the sums of six and the products and from the products calculate danger break i'm going to call b this case right here where we actually look at the previous dp solution where we have dp of 6 well we have 6 plus 2 or dp of 6 plus 2 and we calculate 18. now when we get to actually coding it let i represent the index of the array that we're currently on as we solve this from i to n plus one and finally let j represent the divisor sorry let j represent the subtractor right here now that we have those two things why don't we go ahead and actually start coding it right so we would have let me just emphasize again we have i represent sorry we have i represent this n right here the target that we're trying to do and we have j represent this one two three what we're subtracting against so how can we actually implement this well notice here real quick this number right here this 5 is actually calculated by i minus j times j 6 six minus one times one six minus two times two six minus three times three on and finally we have the exact same case for case b right here where we have dp of 8 minus 1 times 1 dp of 7 sorry dp of 8 minus 2 times 2 and on until we get to the point where we reach it and finally we can also rewrite this as 7 dp of sorry so let me just emphasize once again this is our j this is our i minus j times i and now we can actually start coding the solution go ahead and start coding our solution we have dp of zero is equal to zero plus sorry zero times n plus one the length of the array for i in range 1 to n plus 1 this will be our nth number that we are calculating remember we're calculating this from bottom up so we're starting from 0 1 2 3 4 5 6 7 8. so then we say for j in range one two i y i because we're this j we're indexing it from one two three all the way up to five so that's why we're going from 1 to i then let's go ahead and write our cases right we have a is equal to i minus j case a times j we have case b which is equal to well remember how we said the previous number so i minus j which is this case right here where we have dp of 6 which is also written as 8 minus 2 where 8 is i and 2 is j like so we have dp of i minus j times j and we have the final case which is if we've already calculated and we have the final base case just for um if we're calculating the integer break for one and what we can do is we can say take the max dp of i is equal to the max of these three conditions and finally once we've solved this bottom-up approach bottom-up approach bottom-up approach we can just simply return dp of n and as a base case we have dp of 1 is equal to 1. my bad this should be dp if we run this code let's just make sure it works and let's go ahead and submit as you can see this is a solution for this integer break problem
|
Integer Break
|
integer-break
|
Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers.
Return _the maximum product you can get_.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** 2 = 1 + 1, 1 \* 1 = 1.
**Example 2:**
**Input:** n = 10
**Output:** 36
**Explanation:** 10 = 3 + 3 + 4, 3 \* 3 \* 4 = 36.
**Constraints:**
* `2 <= n <= 58`
|
There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
|
Math,Dynamic Programming
|
Medium
|
1936
|
946 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem let's get started uh problem is validate stack sequences so we are given two integer errors pushed and popped each with distinct values we have to 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 what does this mean this means that this c these are some elements which are in push delay and there is popped area also so we need to have some sequence of push and power operations let's say some push operation then one pop then some again push then pop so some sequence if there is some sequence between these uh two errors ah so then we have to return true otherwise we need to return false let's see what this is so i'm taking this test case first so this is pushy array which is given to us and this is pop array so if we say if we take a stack so let's say initially i am pushing one in it then i am pushing two in it then i am pushing three in it and then i am pushing four so then what i am doing i am popping four so this first operation in popc why i'm not why i have not popped three because see first up first we are popping is four this is a pop area right pop sequence in the uh this is a pop sequence means uh the sequence in which pop operations will be done so first of all four is popped so that's why i have pushed all these elements till four so that when four comes i can pop four out so let's say i have popped four i have popped 4 so now what next element should i have i should have popped i should pop is 5 right but right now 5 is not there that means what i can do is i can add 5 so here we have pushed till here right now we will push this five so i push five now five is five so we got five now we can pop this five so uh we can pop five and this will go here and from the stack i have pod 5 fine then we have 3 and luckily 3 is at the top which means this is correct right so 3 and three is at the top and the next pop operation is what we have to pop three so we will pop three so three will go from here and this pointer will go forward now again two needs to be popped and two is at the top of the stack so we will pop two and pointer this will go ahead and one needs to be popped and one is at the top so one will get popped so see after this whole traversal we see that stack is empty so when stack is empty it means that these push and pop operations were correct these were correct so that's why output for this is true let's see let's take this example so in this example just the difference is 3 is before 5 and 1 is before 2 okay so let me do one thing let me just change this test case a bit so what we have is four three five one two four three five one and two uh four three five one two yeah so see first of all the c first element is four right now we have nothing in the stack so first of all we need to have all the elements and we have to have till four so that we can pop four because first element which can be popped is four we have to follow the sequence right we cannot go till go and pop five like that we cannot do so we have to follow the sequence so first what i'm doing i'm pushing one then i'm pushing two then again i'm pushing three then i'm pushing four now this is equal to this so what i can do i will have this pointer here i will pop this four remove it from the stack move the pointer to the next element so now three is needs to be popped and luckily three is at the top of the stack so we can pop it three gets removed three is removed from the stack and we go forward now five fine now five is there but uh this is not equal to the top of the stack so what we can do is we can push we can again push the element so right now we push till four right initially now we can push this five so in the sequence also four after four five is there so we can push five so five is equal five needs to be popped and it's at the top of the stack so we will push it out oh sorry we will pop it out fine and this will go ahead now one needs to be popped and this array is uh completed right so we cannot pop anything else we cannot push anything else five was the last element but uh we have to pop one and one is not at the top of the stack so this is a error case this is error which is that we need to pop one according to the sequence we need to pop one but it is not at the top of the stack 2 is at the top of the stack so this is a error case hence false will be the output for this so these this is not a sequence this is not a proper sequence of push and pop operation fine so here output is false and because we have to get the empty stack at the end right so i hope you understood this approach let's see once this is encode i will highly recommend just code uh dryron this code once on a test case so what we are doing we took a stack right we took a stack so we are taking a stack and we have taken two variables i j we are where i is the pointer like variable which will be pointing to this push array and j will be initially here at zero index of the pop array and i will be zero index of the push area uh and i less than push size so we will go till the last element is pushed and i plus fine we will push the element in the stack so when see when we pushed 4 right when we pushed 4 after pushing 4 we checked whether this is equal to the uh just j element of pop area or not that is pop of j if it is equal to push of i right i is here so if these are equal means this can be popped four can be popped so if not stack empty and s dot top is equal to pop j so this push i you can take it as s dot top also fine so s dot top not is equal to if it is equal to pop j just keep on popping from the stack and j plus that is we keep on popping four we pop from the stack and we do j plus fine similarly this will go on so at last if the stack is empty then only we will uh we will return true if stack is empty will return true otherwise we'll return false s dot empty if stack is empty so this will return true s dot empty hence return to true will be returned so i'm not dry running this on a test case why because i want you to dry run this code on this test case one two three four five and this test case and the other one which we saw earlier uh so that you better understand right so that's your task you have to dry run it on this uh drain and this code on those test cases those two test cases which are given here now see in this approach what we are doing we ha time complexity is fine it's o of n fine we are taking this for loop so it's often uh this while loop will uh see this while loop uh in will not be contributing it will be some amount of loop so we can take it as o of n only this could be some constant time for this while loop so that overall will be of n only space complexity is also o of n fine so this space complexity will reduce we will reduce now so how we will reduce this how we can eliminate the use of this stack how we can do that so how we can do that is let's see let me write the test case again so test case was one two three four five was the push array and pop array was four five three two one four five three two and one fine so see now this is the push area and this is pop what we can do is we have to eliminate stack right so what we can do we can use this area only as a stack what does that mean so basically let me take another variable i is equal to 0 this i will be initially here so this i will be you can say representing our stack this will be the i will be the place where top element goes fine so this is the let's say we have taken i variable and that will be representing our stack let's dive in also as well as with the code so that you better understand so see a variable we have taken this i variable which is initially here and j variable we will take as such j variable we were taking for this power period right that we will take as such just that in the first approach we have taken extra stack here we are just using this push array as a stack that space we are reducing so j will be here fine now what we are doing is we are going to each element in the push array each element in the pushed area and that is our what that is our val or you can say x that is our x right so uh we have taken x and initially x will be one now what we will do is what we were doing here we were pushing whatever element was there right we were pushing it in the stack similarly here what is our stack is this i right and this push array is the stack so we will have to store this x in the stack so we will write push i at the ith index push this element like add this element so this is like earlier what we were doing in the stack we were pushing elementa in the stack same thing we are doing here so we are pushing our element in the stack and we will do i plus meaning next element will go at the is index because at this index this element is there fine because so x1 is currently here only so one will get stored here and i will go forward why we are moving i because the next element will go at this index fine because this index is already taken by one so now whatever the next element will be that will go here that's why we are doing i plus so this is the step of pushing in the stack pushing in stack same thing which we did earlier using a stack push function right so this is one thing after that what we were doing if the top is equal to the power value array element in the pop area we pop it and we increment the pop array in this variable same thing we'll do here what we are doing here while i is greater than 0 and pushed i minus 1 is equal to popped b so let's do one thing first let's uh dry run this so i'm raising this thing now see what will happen here pushed i minus one so zero one two three four i minus one variable uh is this index right so that is one equal to four no so what we will do will not go in this inside this while loop and again this for loop will continue and x will now be 2 and this will store here so already it's here only similarly i will go ahead 2 is also not equal to 4 so i will go ahead and this will become 3 is also not equal to 4 so again i will go forward it will go at 4 so we will store 4 and i will increment here i plus we are doing right now we are checking if push of i minus 1 here i is 4 minus 1 index is 3 so push of 3 what is push of 3 it's 4 right 4 is equal to 4 which is right meaning this element we can uh pop we can pop right we can pop so what we will do will decrement i because we have popped the element and increment j because this element is already popped i minus j plus fine so if you continue this dry runs this once uh why i'm not dry running is because i want you guys to dry around so that you know how to dry if you are getting any trouble enjoy uh in doing iron let me know in the comments and basically once after this for loop is completed if i is at 0 meaning if the sequence is correct right i pointer will finally reach here at 0 fine because see here i will reach at zero so then if it is at zero meaning this operate this sequence was correct because we there were like same uh push and pop operations were in sync and if i is equal to 0 yeah i can return this will return true and yeah that will be the case so uh yeah this is the uh problem let me know in the comments i'm facing any doubt do dryer in it once what we are doing in the second approach is we are eliminating the use of stack fine so using this pushed only we this pushed area only we have taken as a stack so i hope you found the video helpful uh time complexity for this is o of n and space complexity is over one no extra space if you found the video helpful please like it subscribe to my channel and i'll see in the next video
|
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 |
279 |
alright welcome back to another discord question then now this question is perfect squares let's read the question given an integer n return the least number of perfect square numbers that sum to n a perfect square resin integer that is the square of an integer in other words it is the perfect product of some integer with itself for example 1 4 9 and 16 are perfect squares while 3 and 11 are not for example one out the input is 12 and the output is 3 because we cannot write the inputs in this format the which have three numbers so the output e3 for the example 2 this is the input and the output is 2 we can because we can write the outputs in this format 4 plus 9 which is 2 numbers so now let's see how we can do it i already write numbers and their squads our input is 13 the squares if of 13 is 3 points numbers we are just interested in integer parts three we have three so we take the first three numbers we don't say 16 because 16 is already bigger than 13 and it cannot be in the sum we can write 13 in this form in this format 9 plus 4 but we don't always take the bigger number because in this case if we have the inputs to a 12 if we take the biggest number which is nine plus we cannot take four because that is thirteen is bigger than twelve so we take once ten eleven and 12. we have here three number four numbers but we can also write 12 in this format plus three fourths and this is basically three numbers which is smaller than four so the right answer is three to solve this problem we need to do a dynamic programming boots on up in order to do dynamic programming boots on op we need to calculate all the numbers from 1 until we reach our input with e13 now for to do so we need to do a for loop for numbers and other for loop for squares we start by number one the outputs is one this case four two one plus one is true for three we have three numbers for four one numbers just four five we need two four six we need three four seven we need four for eighths we need two four plus four nine we need one for ten we need two nine plus one for 11 we need 3 now how we can find this number in algorithmic way let's calculate output of 12 the output of 12 should be we can do we have number one so we can do one plus we still need 11 num le we should need 11 to reach 12 so we can do one plus output of 11 or we can do let's see four plus output of eight or we can do 9 plus output of 3 we took the main results for one plus outputs of 11 after 11 of 11 is three so all the output is four plus four class output of eights is three four nine plus output of three is three so three plus one number is four this is the mean so we took the mean and this is the right results we already talked about it here and for 13 we can do the same and find the right answer is to i hope this makes sense to you now let's talk about time complexity the time complexity is square n multiplicated by n because we do this for loop which have o of n and this for loop which is square n and for the space complexity is of square n because we need to write this r i with half and elements let's start by initializing our variables we need squares and various limits e and our output the max of the output should be n plus one and the length it should be also n plus one okay let's in the best case it's when we have zero the output should be zero and now let's have our squares while a multiplication by the same is smaller or equal than n then squares will append our squares and a equal to a plus one now let's make a for loop for what's am i doing okay for k in a range of one until n plus one and for ace because we don't we have to go in all squares for s and squares outputs k okay let's check if k plus s is positive because you don't have a negative numbers output k is truly v the mean of output k and output k minus s plus one okay that's it i guess now let's return the outputs minus one the last output let's run the code now let's submit it takes some time okay and that's it i hope this video was useful for you i'll see you soon
|
Perfect Squares
|
perfect-squares
|
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.
**Example 1:**
**Input:** n = 12
**Output:** 3
**Explanation:** 12 = 4 + 4 + 4.
**Example 2:**
**Input:** n = 13
**Output:** 2
**Explanation:** 13 = 4 + 9.
**Constraints:**
* `1 <= n <= 104`
| null |
Math,Dynamic Programming,Breadth-First Search
|
Medium
|
204,264
|
490 |
hello so this question is the maze and basically uh you're giving a 2d array and then there's a starting and there's the ending and then you can only move four different directions and when you roll the ball and this ball will only stop at a point where it hit the wall so it will stop at this point like when you go down so when you go down then you will stop at this point right now uh basically like uh we need to find our line is this for uh can this bowl reach the uh richard uh original destination all right so um this question is a little bit easy using a referral search so just think about this you need to know like uh where you visit before so imagine you're rolling down right and then you have to know this cell is already visit and this one no because you can still rolling back right so this style is still active when you hit the wall like this and then you will be able to know this cell does not work right so i mean just imagine like when you hit the ball right over here right you can actually have three different directions uh ones go left the other ones go right and then ones go up right so you have to just push three different direction uh to your queue so you want to just make sure like how many uh how many possible way you can actually goes from here all the way to here i mean something like this right so uh basically uh this is going to be super easy so i'm just start coding and uh you'll be able to understand so uh here we go so uh so we start giving uh i mean we start initialize the n equal to mess.length initialize the n equal to mess.length initialize the n equal to mess.length and then we start giving the m equal to miss zero that lens and then we need a boolean which is called a visit and end by end so we already know this the first starting position zero and then star one is equal to true right so basically this is pretty much uh the visit starting and also in the queue and then we push uh we only push one d array so which is x and y uh starting this is x and y right so it's two uh two index in array right so i'm going to say q in new linked list i'm gonna just offer the star into the queue right away right and then uh what do you need uh else you need a four different direction right so i'm going to say direction new in and i'm going to negative zero and then pause the zero and then and this is zero negative one zero positive one all right so this is going to be what this is going to be uh left this is gonna be right this is gonna be dumb and this is gonna be up right so once i push the starting position i'm just going to keep traversing until the q is empty so you need to keep traversing until the queue is empty right so you have to say well q is not empty then you keep doing this right and then i need a current so i will say q double and basically um you just keep pulling when you push right all right so uh i was uh i will mix uh i will make a return if current is actually equal to the destination but i'm not going to code this part yet i'm going to just keep traversing keep finding uh the possible way you can achieve to other uh that's a other point like other cells probably this is better to understand so i'm going to just try out the four different directions and then you'll definitely get a new x and y so i'm going to say direction zero plus the current zero because when you pull out the q dot pro right you're pushing the star so you're getting the star index 0 and then direction 0 which is this one this is going to be your new x right and then you need a new one so exactly the same thing but different index all right now you have an x and y so you have to roll right so imagine you want to roll let me keep thinking one more second so imagine you want to rolling down right so uh at some point right you'll definitely hit a wall right but in these cells this is still this one is still empty so you want to go to this place right so at some point we need to uh decrement by one to come over here right so uh once again you need a you will be able to say well so rolling x is y greater than or equal to zero which is in the bound right and also y equals y equal to zero and x is less than n and y less than and so look at this if the uh if the m uh okay if the mass is empty then represent zero right so mass x and y it's actually equal to zero right then you just keep adding your direction all right now when you break out the value uh this is actually meant like you are in the wall so you need to decrement by one so just decrement by one all right so now you're at this point right now you're at this point so you was so it was here uh you was here and then you decrement by one so you got uh you got to this position right and then we need to check do i uh do a visit or not right because if i do then i don't have to what i don't have to add that to the queue right so if not visit if not this i need to just add the uh the coordinate into the q right so new in x and y and then once i add it and i can actually what i can actually just say visit x and y equal to two right okay so you just keep pushing and then at some point where you pull that current is definitely equal to destination right and then you have to know the current equal to that destination doesn't work so you have to say index by index current 0 equal to destination 0 and also current index 1 equal to destination in this one so this is how it works so your version i saw you will return true uh right over here and then you can pause all right so i might have a typo of oliver so let me run it oh i don't have it all right so this is pretty much the solution and so this is one one of the solution you can achieve using a preferred search so let's talk about the time and space so this is a space this is a this is also a space right boolean cue right space so the worst case is going to be earned by m right the number of space you generate for visits to the red boolean and uh for the time this is actually about the worst case i do you stop at every single cell right so this is still all of n times n and this is pretty much a solution and don't worry about the of the inner for loop because it's only one it's only constant although four f4 is a integer right and just i mean for the worst case that you stop at every single cell right so this is all of m times n for the timing space so here's a quick note and this is the solution and i will talk to you later bye
|
The Maze
|
the-maze
|
There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the `m x n` `maze`, the ball's `start` position and the `destination`, where `start = [startrow, startcol]` and `destination = [destinationrow, destinationcol]`, return `true` if the ball can stop at the destination, otherwise return `false`.
You may assume that **the borders of the maze are all walls** (see examples).
**Example 1:**
**Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[4,4\]
**Output:** true
**Explanation:** One possible way is : left -> down -> left -> down -> right -> down -> right.
**Example 2:**
**Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[3,2\]
**Output:** false
**Explanation:** There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
**Example 3:**
**Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], start = \[4,3\], destination = \[0,1\]
**Output:** false
**Constraints:**
* `m == maze.length`
* `n == maze[i].length`
* `1 <= m, n <= 100`
* `maze[i][j]` is `0` or `1`.
* `start.length == 2`
* `destination.length == 2`
* `0 <= startrow, destinationrow <= m`
* `0 <= startcol, destinationcol <= n`
* Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
* The maze contains **at least 2 empty spaces**.
| null |
Depth-First Search,Breadth-First Search,Graph
|
Medium
|
499,505
|
209 |
hello everyone I hope you're doing well in this video we are going to solve problem 209 minimum size sub array some in the Le code Series so let's see what's the problem wants us to solve So based on the description of the problem give us the array that has contain the list of integers and the target number and we need to find the minimum length of the numbers that the length of the number that the sum of the sorry the sum of the numbers is equal or greater than the target so assume that we have these numbers as a input let's analyze it and see how we are going to solve the problem so I'm writing the numbers here 2 3 1 2 4 3 this is the array that the problem gave us and this is the target number seven so we want to we need to find the numbers in the minimum length that the sum of the numbers is equal to the top Target or greater than to the Target for example think I'm starting from two I'm just using two then adding three then adding one we have five then six and if I added two it equal to eight it's greater than a Target but I use 1 two 3 4 four entities I need to find the minimum size of sub array so let's try with three 3 + 1 + try with three 3 + 1 + try with three 3 + 1 + 2 + 4 then this one get five six and 2 + 4 then this one get five six and 2 + 4 then this one get five six and this one is 10 this one is greater or equal than a Target but the length of this array is four let's move one more one 2 and then four 1 + 2 + 4 is equal to 7 2 and then four 1 + 2 + 4 is equal to 7 2 and then four 1 + 2 + 4 is equal to 7 this one is equal and greater than seven but this one I think is the better choice because this the length of this array is this sub array is three previous one was four let's try to use this one 4 + 3 this one get to seven so this one 4 + 3 this one get to seven so this one 4 + 3 this one get to seven so we achieve our Target and the Seven is equal or greater than the target but the length is minimum because the length is two so let's see how we want to solve this problem when we are going to code this problem so this is the type of the problems that we need to handle the window as you see we I have I've started from two then I moved to three then I moveed to one so and each time we have a window that I'm going to move the window or maybe sometimes increase the window sometimes decrease the window and if I want to work with the windows I always need two pointer so all the problems that we need are going to solve with the windows solution we need to have a two-p pointer one pointer to have a two-p pointer one pointer to have a two-p pointer one pointer point to the start of the window one pointer point to the end of the window okay think that I have a two-p pointer okay think that I have a two-p pointer okay think that I have a two-p pointer the first pointer that I named s point to the first item the last the pointer that I have and I name it e point to the sorry the S point to the first item the E point to the last item so think that the pointer is here and I'm just using S equal z e equal Z then I need to have a sum to know okay the numbers that I have in the window get to the which number for example right now both of them point to the two so the sum is equal two so the two is less than Target so I need to increase the window size so I can move a to this item so I increase I move n to the position one and I get some to the five okay five is less than Target so I need to increase the window I'm going to move the end pointer to here so when I'm moving this I'm adding one to five so the sum get to six so I need to increase the window again I move the end to this here so and move to position three and then we have five six seven8 good so the sum right now is equal or greater than a Target and the window size that I have here is one two three four so I can have something like a result or wind size and Windows size right now is equal to four this is the minimum that we find right now so after what should I do I need to increase the window no I need to decrease the window but how I need to move the start one step ahead so I move the start to this position if I move a start here I need to calculate the sum so the sum is 3 1 2 so the sum get to six is less than seven so I need to move the end again so I move the E to this position and so let's calculate the sum 5 6 10 some gets to the 10 and how many item I have in this window 1 2 3 4 this same as size as the minimum size so I need to move the start again I move the start to here so start get to two and I'm just calculating the sum again 1 + 4 = 5 + 2 again 1 + 4 = 5 + 2 again 1 + 4 = 5 + 2 = 7 how many items do I have in the = 7 how many items do I have in the = 7 how many items do I have in the window I have three items so I can decrease the window size because I'm looking for the minimum one to three then I need to move the start one more time I move this start to the here five 0 1 two three oh I made a mistake sorry 0 one two 3 I move it to the three and end is mve point to four 0 1 2 3 4 yes so right now what's the sum is equal six it's less than zero so I need to move the end one a step to the right so e point and point to the five and the some will get to six 6 + three some get some will get to six 6 + three some get some will get to six 6 + three some get to the nine is equal and greater than set Target yes and the minimum size is still three so same as the things that I did previously I need to move start one step ahead so I move this one to four and calculate the sum 4 + 3 = to four and calculate the sum 4 + 3 = to four and calculate the sum 4 + 3 = to 7 oh great so and I have two items here and the two is less than three so I calculate the M size again and set the minimum size to two and return the two and this is the result of the problem so let's implement the same things in the code okay let's do the same here so this is the method that you will see in the lead code when I start implementing this problem in Java you will see different stru name or a structure if you use different languages but the structure the implementation will be the same it's not related to the which language that you are going to implement sub array L and as you see we solution give us the Target that we need to find the minimum window that then the sum of the minimum window will be equal or greater than the target and we will receive the list of integers so first thing first you saw that I defined some pointers because I told you this is a problem that you're going to solve it with the window and always for window we need two pointer one of them point to the start of the window one of them point to the end of the window so I need to Define 2 point and initially these two pointer point to the first item in the array then I need to Define variable to keep the some of the wi items that we have in the window and because currently we are setting the start and end of the window to the first item of the first item in the array sorry the sum will be equal to the value of the first item in the array and then I need to have a variable to keep the minimum window size I name it minimum window size and initially this one is zero because if you will not find any window that some of the items in that window be equal or greater than the target we should return zero at the end then we need to have a while and we need to always make sure that the start of the window will not pass the end of the window as long as the start pointer is less than equal the end pointer I'm going to run this Loop why I put this criteria here as I show you here for example think about this one again think that this is the a start pointer and this is the end pointer a start pointer should never pass the end pointer if a start pointer passed the end pointer it means that we couldn't find any window that match the criteria and it will not be equal or greater than the Target that we have and that's the reason that I put this criteria here so after this I need to check something if for example the start item that right now the start pointing to that one is equal or greater than a Target we don't need to check the other things we can return those result if the numbers that the integer number that the start pointer point with be equal to the Target equal or greater than the target so that's something that we are looking for so immediately we can return one for example think that the target is six and the array that we are processing be something like this and the start pointer point to the seven is greater equal or greater than the Target that was six so we know that the minimum array will be the size of one and we can immediately return one in the other cases we need to check if some greater or equal than a Target yeah we need to check if result equal zero because we have a started okay sorry I name it here as a minimum window if minimum window equal zero or n minus star part less than minimum window we going to set the re minimum window equal end minus start + one this is for this one in the other case if find okay it's greater than equal Target but minimum window that we find by subtracting end to the start is greater than the minimum window that we previously found as I show you we need to move start pointer one step to the right so I need to just calculate the sum Again by reducing the value of the numbers that I have currently in this start then move the start one step to the right why I'm reducing the value of this um from for the start first for example think that we have this array 2 3 1 2 4 3 a start point to here end point to here and this sum is 1 + 2 + 4 the sum + 2 + 4 the sum + 2 + 4 the sum is seven I want to move the start one step to the right so I want to move the start from this position to this position so I need to remove one from the sum that I was calculated so that's something that I did here so I first remove the one from the sum that I calculated then I move this start one step to the right else if the sum was not equal or greater than the Target and the sum that we found is less than a Target what we should do here so first thing that we need to do is just we need to as I show you we need to move the end pointer one step to the right but we need to always make sure that the end pointer will not pass the end of the array lens so I need to have some check here and make sure that the end pointer is always less than the length of the array and if it's less than the end length of the array I can increase it and just as I show you I can increase the sum by add that numbers to the sum and What's happen if the array that end pointer sorry point to the last item of the array we should not move the Left End pointer we should move the start pointer and I need to do the same thing that I did here to move the start array one step to the right so this is the solution okay I'm just trying to and then we are going to return minimum window and that's it this is our solution and as you see this solution is really easy we just create the window we just move the start and end of the window to find the minimum length of the window then the some of the numbers that is that are in the window is less than is greater or equal than the Target that we have okay as you see we discussed the solution how to solve this problem but one things remain and it's about the time complexity and space complexity of this problem as you see we defined two pointers and we have started from the first element to the last element we didn't have any inner loop so because this problem was solved with the windows and we have a pointer to point to the point that point to the start of the window and we had a pointer that point to the end of the window this problem time complexity is o n because we visit each element of array one time through the window and by just increasing the window or decreasing the window we just move the window from left to the right what about the space complexity did we Define any addition array no we didn't Define any additional array we use the same array that we received we just Define two or three variable to keep the pointer to the start and end of the window and keep this value of the sum and minimum value that Define for the sub array so we didn't Define any additional array so the space complexity for this one is one so we solve the problem with the time complexity of o n and a space complexity of o1 so I hope you like the way that I solve this problem you can always find this solution in the GitHub repository that I put in the description see you in the next video
|
Minimum Size Subarray Sum
|
minimum-size-subarray-sum
|
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
| null |
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
76,325,718,1776,2211,2329
|
303 |
alright guys welcome back to study plan program is the last day and the last problem it's time to get our patch so arrange some query image problem so given an integer array norms handle multiple queries of the following type calculates the sum of the elements of numbers between and these left or right inclusive where left is smaller than our tunnel later basically amply moves the normal array class the number items in snobs it's a it's an ri so initial is the object with the integer array number so in some range in select into right to resolve the sum of the elements of the numbers between and this is left hand right and closing super easy i guess okay so let's do that we just have unknowns subsequent numbers equal to arms and let's make answer equal to zero what we want to do is to calculate the numbers between left and right so for k in orange of the of left and or right or it is i is a it's called plus one to account for the right so the answer should be increased by self dot number of k i guess that's it let's return answer let's run the code yep so we'll click submit why it took so long okay it's work i hope this video was different for you and see you soon
|
Range Sum Query - Immutable
|
range-sum-query-immutable
|
Given an integer array `nums`, handle multiple queries of the following type:
1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`.
Implement the `NumArray` class:
* `NumArray(int[] nums)` Initializes the object with the integer array `nums`.
* `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`).
**Example 1:**
**Input**
\[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\]
\[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\]
**Output**
\[null, 1, -1, -3\]
**Explanation**
NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
**Constraints:**
* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`
* `0 <= left <= right < nums.length`
* At most `104` calls will be made to `sumRange`.
| null |
Array,Design,Prefix Sum
|
Easy
|
304,307,325
|
965 |
hello guys welcome to code directory today the problem statement is uni valued binary tree a binary tree is univalued if every node in the tree has the same value okay return true if and only if the given tree is uni valued actually they will given the binary tree if the binary current binary tree contains all the values are same you will return true okay in this example all the nodes contain the value one so this is true okay let's go and get into another example in this example you have two five here we have the five so you will return false okay here two these four are same but this node has a file so you will return false okay i am going to solve this code this problem by traversing the binary tree in order okay so what i'm going to do is first i will create an global variable then i will check the edge condition if root it will be equal to null you will return false right because it does not have any nodes to check so you written simply you written the files okay then um i will create the function called fun then i will pass the root node okay i think that's enough then i will return the answer okay let's do our function actually this is the tree node sorry renault star route okay i think you all know what is in other driver cell in other traversal first you will traverse the left node then you traverse root then you will finally will traverse the right node so if root left not equal to null then you will call our function then you pause the root left right then you check the root value if the value is same you will ignore if the value does not match with the other values so you will do you will return simply written the false root value so for this i'm using the i'm passing the initial root value as a data okay so this data is the root data okay so if the root data contains one element so all the elements should contain the one right so if root value so one might know this will cause some error okay here root value equal to data sorry if the root value does not equal to the data you will set as answer equal to zero so it will simply make a false right then you will travel the right tree if you look right then you will pause the data okay first you have to check whether it is null or not then you call the function put command data not root right you have to call it right okay root right and i paused the data and then finally you written the answer okay this is the recursive function i think you all know in order to drive itself a tree so you got some mirror okay root and okay this is a small error okay not error it's a typing mistake yeah output false expected true so functioned it in the false right okay you have to assign to one because you're checking the false condition so how to assign our global value as now calculated submit my code okay it's accepted it takes only four ms of time complexity and around 10 mb okay guys thanks for watching please do subscribe for latest programming interviews
|
Univalued Binary Tree
|
unique-email-addresses
|
A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `0 <= Node.val < 100`
| null |
Array,Hash Table,String
|
Easy
| null |
775 |
Okay so hello everyone this is Akshay year today's question which we are going to discuss is global and local inversion lead co 775 this question is very famous by the name of counting inversion if you write counting instead then definitely similar to this You will get any question, let us understand the question and then we will talk about some of its pre- understand the question and then we will talk about some of its pre- understand the question and then we will talk about some of its pre- requisites, how to tackle this question, what will be the code, everything will be discussed in detail here, you stay tuned to the video, the question says, you have an array named length n. Which represents the permutation of all the integers in the range 0 to n - 1. Okay, we have to find the global inversion and the local to n - 1. Okay, we have to find the global inversion and the local to n - 1. Okay, we have to find the global inversion and the local inversion. It is very easy to find the local inversion, so first let me explain that all the indices i traveling from 0 to n - 1 Such an index that the index next to it 0 to n - 1 Such an index that the index next to it 0 to n - 1 Such an index that the index next to it i + 1 i + 1 i + 1 should be greater than the number next to it. If so, then calculate the number. That's it. Local inversion is very simple, okay, I will show its code here too. Look, local. Here's the code for the inversion, the story is over, okay, now one thing is over, let's see the next thing. Okay, what does Global Iverse say, that for all the eyes is right and this gun has come, so definitely see, now what will be the possibility here. If we stand on one index and accept it, then all the right indices are all the possibilities of j or not. We have to check the numbers of y and the numbers of j, meaning if there is descending order then it is ok right. No, if there is descending order then there is global inversion. If there is ascending then it is ok. Right, let us understand the input output of this question. Once after that we will understand how to do this question. AI is now clear. Just find AI once. For everyone, for 102, here I am, the number next to me is not bigger than me, right, so A will not count, this number is big for this, so A is its one, two, so it is the only element, so let's check. There is no need of 'He is poor'. no need of 'He is poor'. no need of 'He is poor'. What will we check again for 102? If it is 'i' What will we check again for 102? If it is 'i' What will we check again for 102? If it is 'i' then all the possible judge would be this because the question had said that 'i' should be smaller than 'h' so question had said that 'i' should be smaller than 'h' so question had said that 'i' should be smaller than 'h' so if I put 'i' on this one. if I put 'i' on this one. if I put 'i' on this one. Fix so definitely all the right elements aa j similarly problem will come when the numbers of aa which is gun numbers of j become right then we will call the global issue count plus correct ok so let's see ok friend let's take out so For this index, this is the possible judge, okay, we have to see where the descending is, that is the problem and 0 is not a problem, is it a problem? Yes, it is a problem, and 0 is a problem because it is descending similar to ascending, so it is not a problem, now it is zero. If we check for ' not a problem, now it is zero. If we check for ' not a problem, now it is zero. If we check for ' I' here, then it is ours, ' I' here, then it is ours, ' I' here, then it is ours, ' Right', it is sending, there is Right', it is sending, there is Right', it is sending, there is no problem, 'Right', similarly, now we no problem, 'Right', similarly, now we no problem, 'Right', similarly, now we set the last index 'to', so this is the only set the last index 'to', so this is the only set the last index 'to', so this is the only element, if you check whose right, then the count of 'G' is here. Done, one which count of 'G' is here. Done, one which count of 'G' is here. Done, one which is equal to A and G, both are equal and for two, you solve it yourself, I will write here, what will be the problem, which is A, where will it be counted from, this is bigger than its neighbor, this is right, so and so. It is definitely done Global Evaj What will happen friend Global Evaj I am seeing Vanma No no what do we want Descending should be right So one is visible to us 0 One is visible to us and which one is visible friend one is visible to us 0 Right, this is also descending, so two global equals are not the same, hence false is returned. Okay, so now let's start or we take out the global in, so see friend, one way is that we write in our right for all the elements. Traverse J pointer, write it right and check the given condition. If you copy the result from the plot, then it has become O. This also has become O. Id for loop is off, so what is the total? To extract the complex TGE, it will be in the form of AI, but can we do better than this, can we optimize it, I say we can, we will do it with dedication, it is a pre-requisite, do it with dedication, it is a pre-requisite, do it with dedication, it is a pre-requisite, merge sort, if you want to merge. I don't know how its code and everything is working, so you pause the video here, first go and read the article video of Merge Sot from someone's video, friend, I have not put the video on my channel, otherwise I would have mentioned it in the description. Would have given the link, read it from anywhere, right, continue back to this video, so what are we going to do, we are going to divide the given array recursively, we are going to divide the given array into left half and right half, then what can we say if we divide it into left and right. If given then you will get two sorted arrays right and you will get a resultant array in which you have to program right here there will be an i pointer this will be a zth pointer this is your left array this is your right array now this is so big Can you see the code? This is exactly the quote of the murder sort. Exactly the only change I have done is this one. This is an additional statement which let me explain to you how it is working. Okay so 2 and 3 are so tutu and th. Which is smaller in two, then the balance of i and j is being created, now there is no problem in the right ascending order, write two, right and move it forward, again four and th, now look friend, it is not ascending, it has gone right. If this is the three, it means that a conversion has taken place, first of all, the 4th is a conversion. Now this is the three, it is only smaller than the four, so the inversion was right or in other words, it was greater than the 4th, so if the third is than the four. If it is small then definitely all the elements ahead of it will be smaller than four, right, so that means I can say that 5 3 will also be converted, 8 3 will also be converted, so I can manually see that three is the answer, the problem with right four. So there is a problem with all the elements ahead, but this one I have problems with, that is n1. Look in the code, I have written n1, if I do n1 minus where the problem occurred, at this index, which is this index and n1 given that is nothing but. 4-1 which is this index and n1 given that is nothing but. 4-1 which is this index and n1 given that is nothing but. 4-1 Chach gives me 3 So my work will be done So this is what I did here in the else condition Right is ok The answer is still our 3 And what will we do Now who was the smallest Th So write Thi and move J forward. Now look at I and J, where you have picked small element, four and Si are ascending, there is no problem, then move 4 and Aa forward, F and six are ascending again, there is no problem, move Aa forward again. Increase it, now it will increase further, then it will become 8 t and this is the problem, the descending has come right, so that means the next inversion which is ours, right for 8 s. Now again look at this, how many were the assisting inversions, th 3 ps n1, how much is 4 minus this. What is the index? This one index right 4 - 3 1 So look at the total what came one which - 3 1 So look at the total what came one which - 3 1 So look at the total what came one which represents this so 3 P 1 4 Total I count four so far for now come move forward now which one has moved forward J has been moved forward to the right, it was small, it was correct, so J has been moved forward, now again 8, 9, there is ascending order, no problem, write t and move Aa forward, now Aa is out of bounds, meaning n1 left array is finished. It has happened that in that case we had two probes, either the left one ends or the right one ends, so for that we wrote these two void loops. To handle the remaining elements in one, brother, iterate over it and put a wall loop. Paste all the elements of K and all the elements in the answer R. This is your answer R. So, what is left? 9 and 13. If you look, this is actually a sorted array on the right and this is actually the Mars algorithm. We have just used the Mars algorithm. I did a little smart move to find out the number of inversions and wrote this thing inside the else condition and that's it. Okay, now let's look at a diagram for the given test case where two global elements were two to 0. Right, our Antays shot. How will the right work, how, actually, the division is being done, so T is 0, first divide it will become one side will become zero, there are still two elements, division has become one more, one has become two, one side has become two. Now when it returns from here, what will happen, you know, that is, at the smallest level, only one element is present on the right, this is our left array, this is our right array, this is our aa pointer, this is our j pointer and this. Our resultant array will be returned, right then i which is one and two is small, so there is no problem in ascending order, then write one here and move i forward, if it is out of the box, then the second while condition will take it the same and This two will come here, what exactly did it return, when this level is over, it returned to right, so whatever it is, it has changed to this, it is the same but we have to use it, if it is 21, let's From to two, still the same returns, count energy increases by one. Right, this is two and what is its level par, zero then again. Now between whom to compare, do you know this one and two, sorted rays will come again in our field right. This is done, this is done, now we can clearly see that descending order is being maintained, right, so one answer will be formed first, zero will be in it, now this zero is creating our problem for this, descending b, so definitely as many as next to it. The element is made for everyone so what can I say and 0 both so how much are its inverses again minus this index g 2 mine 0 f will give you right what is its advantage know what if let's say this element has 1000 There are more elements in all the writes and I know that there is a problem on this index, so do I need to travel for the remaining 999 elements? No need. Once I know that there is a problem here, then definitely move ahead. The elements are going to be greater than ours right so that is the way this n1 - Aa which right so that is the way this n1 - Aa which right so that is the way this n1 - Aa which is very smart plays right okay so how far were we this thing is done count e count inversion to is done j pointer will move forward again out If it goes off bound, the Y loop will take care of it and push the rest of the elements to its answer box and this is the level that will be returned from here, we will actually have 0 1 and to the edge of our updated array and your GE s to right and definitely you see. It is possible that Jitu was also there for this, it is okay here or I hope you have understood the dry run, then you must have understood the dry run, this is a guarantee, at one place you may have a problem in understanding the code, now this is The problem will arise only if you have not understood the merge set code well. Right, because I have shown you the entire left half and right half by opening it. Right, let's see it immediately. We created an AI and handled the AI. It was very simple. Made a GI in which count is equal to code is being called, count is nothing but you are getting killed, it is a simple thing, divided into left half, divided into right half, when the turn came to merge both, then one of count and merge was done. Created a function which is exactly merge function for short, an additional line has been inserted in it, this one which counts the emergences and gives us the right, that is it, what is the time and space complex merge, what is the complexity of a log n, so its also Log n what is the space n right then this code is done and if you liked this question then definitely you must have liked it, the question was good if you liked the video, you liked the solution and if you have understood the tuition then Definitely support the community by subscribing to the channel and social media links are available Lincoln Bye and Take Care
|
Global and Local Inversions
|
n-ary-tree-preorder-traversal
|
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`.
The number of **global inversions** is the number of the different pairs `(i, j)` where:
* `0 <= i < j < n`
* `nums[i] > nums[j]`
The number of **local inversions** is the number of indices `i` where:
* `0 <= i < n - 1`
* `nums[i] > nums[i + 1]`
Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_.
**Example 1:**
**Input:** nums = \[1,0,2\]
**Output:** true
**Explanation:** There is 1 global inversion and 1 local inversion.
**Example 2:**
**Input:** nums = \[1,2,0\]
**Output:** false
**Explanation:** There are 2 global inversions and 1 local inversion.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `0 <= nums[i] < n`
* All the integers of `nums` are **unique**.
* `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
| null |
Stack,Tree,Depth-First Search
|
Easy
|
144,764,776
|
1,042 |
hey everybody this is larry this is me doing a bonus question so let's do one together i haven't done it yet uh let's see how many problems do i even need i don't even know but all right let's do a random one and hit the like button hit the subscribe button join me on discord and let me know what you think about today's bonus question as i always do uh i might end the series soon i mean it was a good month i do it seems like no one is really uh not no one uh if you're watching this i appreciate you uh of course but i feel like uh maybe this isn't the best use of my time so i don't know let me know in comments if you really enjoyed the bonus questions and if you're doing of me or and if you want to see more anyway today's problem is 1042 flower planting with noah jason a lot downwards anyway you have n gardens labor from one to n and away perhaps oh yeah it's august 18 by the way i don't know i just feel like in the future i may forget it so this is more for a future larry okay so you have one to end uh you have a garden from one to n perhaps where paths of i is x about the div what does that even mean oh okay so it's just showing that uh yeah what does x and the y mean that's weird okay so please for example has one two all guardians have at most three paths in and out you're trying to choose a flower type for each garden such that any two guns gonna have to have a different type of forest return any such choice okay so they want adjacent ones to have different flowers um i think this is because they're only at most three paths coming in and out you can just greedy you know you could use the pigeonhole principle right meaning if this is one then you just choose the one that um you haven't done it before and technically speaking if you want to think about it's greedy with uh what's it called the max which is um maximum x current something like this i don't know if i spelled that right um or is it max minimum mixed current of course um minimum excluded uh not maximum because maximum can just be infinity but yeah um and that's basically it really so you have paths for to do we could implement something like the way that i always do is just have edges is equal to i like edge list instead so i always convert it to edge list you know you may do it in another way perhaps uh it's these one indexed you update that one index so i'm just gonna i'm gonna convert it to something like that right um and then now it's what we said so we can do a breakfast search um what are the colors just one two and three and four yeah i mean that's fine so yeah um let's see so we just set the do they always have a thing i guess not so okay so then we have colors is equal to let's just say none times n i like pick n um and then now we just go one by one so for i in range of n if colors of i is equal to none or is none then we want to break but i want to refresh search you could run anything you like really um yeah i'm going to want to breakfast search i think yeah that's fine and that's pretty much it and then we turn colors afterwards i think is probably the idea and then or start maybe and then here we this is just standard reference search uh or you know we just have to be careful because we want to define the colors when we relax them i guess so because you can't really uncure it afterwards at least not in an easy way i mean maybe you can but yeah maybe we can actually but um yeah and then colors of start is equal to what's one two three four one and then yeah for a while length of q is greater than zero current is equal to that pop left and then here we go for v and edges of current right what do we do um well if colors of re is equal to is none then we do color things to it um yeah and then yeah uh q dot append v next and that's pretty much the idea we have to do some color things though so colors of reason code two maybe we just do a max of v or something like this um and yeah and then here we go we have a node and here we just look through edges of node so as is you go to let's just say the set of this now we well we want all the um colors of v for v in edges of node something like this um where we want to filter out the none uh if we is not or with colors of re is not none something like that right and then now we want to see the smallest number in there right so for i in range from one to five just if i is not an s then we return i that's pretty much it um someone like this but let's run it real quick you might have typos of it hopefully this is right okay this is not right at all why is that okay so we set colors to one and then here let's see node and then s maybe i messed this up yeah i don't well this is not calling this at all so why was this not calling this at all oh because i forgot to append store it okay that's a silliness okay so that looks good uh i feel like i did get most of it right recently but still a lot of like just silly typo things um so this looks good so let's give it a spin i mean the answer is not gonna match directly but you can prove by pigeonhole that this is going to be correct just because any solution that where you don't have conflicting edges kind of correct because it's at most three paths right so yeah uh so this looks good what is complexity here well each node is going each node and each edge is going to be processed once so this is going to be o of v plus e or n plus e i guess depending on how you want to say but yeah so time is over we plus e and also space is also we plus g so yeah uh that's pretty much all i have for this one so yeah uh it's a very standard e graph problem not sure all the downwards to be honest um i think i guess it's easy to miss this and if you miss this is a ridiculously hard problem but if you do see it and it came up a few times but i don't know i'm not sure about the downloads but uh yeah that's all i have with this one let me know what you think stay good stay healthy take a mental health the weekend is almost here so stay good and i'll see you soon bye
|
Flower Planting With No Adjacent
|
minimum-cost-to-merge-stones
|
You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers.
All gardens have **at most 3** paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return _**any** such a choice as an array_ `answer`_, where_ `answer[i]` _is the type of flower planted in the_ `(i+1)th` _garden. The flower types are denoted_ `1`_,_ `2`_,_ `3`_, or_ `4`_. It is guaranteed an answer exists._
**Example 1:**
**Input:** n = 3, paths = \[\[1,2\],\[2,3\],\[3,1\]\]
**Output:** \[1,2,3\]
**Explanation:**
Gardens 1 and 2 have different types.
Gardens 2 and 3 have different types.
Gardens 3 and 1 have different types.
Hence, \[1,2,3\] is a valid answer. Other valid answers include \[1,2,4\], \[1,4,2\], and \[3,2,1\].
**Example 2:**
**Input:** n = 4, paths = \[\[1,2\],\[3,4\]\]
**Output:** \[1,2,1,2\]
**Example 3:**
**Input:** n = 4, paths = \[\[1,2\],\[2,3\],\[3,4\],\[4,1\],\[1,3\],\[2,4\]\]
**Output:** \[1,2,3,4\]
**Constraints:**
* `1 <= n <= 104`
* `0 <= paths.length <= 2 * 104`
* `paths[i].length == 2`
* `1 <= xi, yi <= n`
* `xi != yi`
* Every garden has **at most 3** paths coming into or leaving it.
| null |
Array,Dynamic Programming
|
Hard
|
312,1126
|
286 |
everyone welcome back and let's write some more neat code today so today let's solve another graph problem walls and gates so we're given an m by n grid where each position could have three possible values a negative one which represents a wall aka an obstacle that we're not allowed to visit these walls a zero which identifies a gate so this is an example of a gate in this case and the third value is infinity which basically represents an empty room and basically for every single empty room aka every position that's marked as infinity initially we want to identify what's the nearest gate to that room and then we want to take the distance uh from that room to the nearest gate and then replace that infinite value with it so and if it is impossible basically if an empty position cannot reach a gate in our graph then basically we're going to leave that position as infinity so for example let's take a look at this example uh the easiest one over here right how far away is this empty room from a gate well it can go in two directions it can go down which is an obstacle so we're not allowed to travel in that way we can't go up or to the right those are out of bounds but we can go to the left and of course right next to it happens to be a gate so what we're gonna place here is a one meaning this is one position away from a gate and similarly this one how far away is this from a gate will one two three positions right from a gate so we could put a three here we could put a two here and a one here uh what about this one we could go one two three so it's three positions from this gate but it happens to be that there's a closer gate if we go to the right and then we go up right so the closer gate is actually two places away so we're gonna put two in this position and now what happens if there was a gate over here what would we mark these two as well basically they start out as infinity and we would leave these two positions as infinity so any positions that cannot visit a gate are going to be remaining as infinity so the first idea that you might have for this problem is basically for every position we want to know what's the closest gate why can't we just run a dfs right basically a dfs until we reach the gate or you know we reach as many positions as we can when we return what was the closest gate to that position right and then do that for every single position in the entire grid now what's the time complexity going to be of that well a dfs is going to basically be the size of the grid and we're going to do that for every single position in the grid so basically it's going to be something like m by n squared so the question is can we do better than this big o time complexity well let's try out a bfs solution right we tried dfs let's try out breadth first search and see what that leads to us let's say we started our bfs at some arbitrary position like this one is it possible that we can eliminate repeated work if we do that well we're gonna start here and then visit in all four directions and see you know what's the closest gate that we can get to so starting here we have a distance of zero it takes us a distance of one to get to these positions and then finally we can get a distance of two to get this position right but since we don't want to revisit the same node twice the same position twice we're gonna you know do exactly that once we get to a position we're gonna leave it as visited so you know if we go from here to here it takes us two positions so you know then we can say okay for this position it took us two but when we go up right we get to this position you know we can't really go in any other direction so basically this is going to be remaining as a dead end we're never going to get a distance in this position right because we don't want to revisit the same position twice we can't go back in the direction that we came from so a bfs solution starting from the rooms is not going to work if we want to get an actual o of m by n solution it's not going to work if we do it from the rooms but let's reverse our thinking a bit why don't we do a bfs solution from the gates so for example from this gate we can say okay let's mark all adjacent rooms basically as saying okay all of the adjacent rooms are one distance away from this gate and then let's continue that so from you know this room doesn't have any other rooms adjacent to it but this room does so we can say okay for this room it's two in this room it's also two this is two positions away from this gate and we continue right we say okay this room is three and continue from here this room is four and from here similarly right we'd say okay this is three this is four and this is four right but is that actually true is this room four positions away well we forgot about this gate right so a better way of doing this would be to simultaneously do a bfs from both gates at the exact same time so in that case if we ever reach a position so let's see what happens when we do a bfs simultaneously so from here we're going to say this is one these two are one position and this is also one position now from all of our ones we're going to continue the bfs right so from this one we'll say these rooms are two away from this one we'll say this room is two away right now from this uh room right this is two away we're not gonna go to this position and say that it's three positions away because with this has already been visited we've already found the minimum distance that this is away from a bfs right so every time we expand one layer we're saying okay first let's find all the rooms one distance away from a gate next let's find all the rooms two distance away from the gate and three and we keep doing that until every single position in our grid has already been visited or we basically cannot continue and we know bfs solutions are implemented with a q so once our q is empty that's how we know we can stop so let's just continue a little bit more so from this to the only unvisited neighbor is this one so this is three positions away this one is also here so now we're going to do a bfs from the remaining threes we can see only this three actually has a neighbor so we'll say this one is going to be four and when you take a look at the actual output that they built our solution exactly matches what they did and we didn't have to revisit the same node twice all we had to do was initialize our queue with the two initial positions for the gates and then expanding outwardly basically incrementing the distance every time we complete a full layer of our bfs uh traversal and that actually led to us having a time complexity of m by n we're also going to have that as the memory complexity because we're going to have a visit set to make sure we don't visit the same position twice but once you kind of know that this is going to be a bfs from multiple sources at the same time implementing the code is pretty straightforward if you know how to do bfs so first things first let's get the dimensions of our grid so the number of rows and the number of columns i usually like to do this at the beginning so and we're also going to have a visit set that is going to make sure that we don't visit the same position multiple times and we're also going to have a q which initially let's uh set to being empty but we're gonna initialize that with the gates first of all right so now let's go through every single position and actually initialize our cue right and we know we're just gonna do that with the gate so we're going to go through the entire grid so iterating over the entire grid and even though we're doing this it's not actually going to change the overall time complexity so we're going to go through every position if rooms at this position is equal to a gate meaning it's equal to a zero then we're going to add it to our queue so we're going to say q dot append this position and let's make sure to add it to the visit set because we don't want to have to visit this same position twice and now we can actually start doing our bfs so initially the distance is going to be zero because we're gonna be popping the actual gates first of all so we're gonna say while q is non-empty we're gonna say while q is non-empty we're gonna say while q is non-empty we're going to go through every single position in the queue currently right basically this layer of the queue and so we're going to be popping from the q so pop left from this q we're going to get the coordinates of the gates that we initially added right that's going to be the first layer we're going to be popping are the gates that we just added right so for each gate we're basically going to say okay let's change this gate to being the current distance so since the current distance is initially zero and remember the gates start out as having a value of zero we're not actually going to be modifying the value of the gates but the reason i'm putting this line here is because after we pop the gate layer the next layer that we're going to add to our queue is going to be all the rooms that are one distance away so after this for loop let's make sure that we remember to increment our distance by one every time we complete a full layer of the queue and so basically for this room let's just go ahead and add room we're going to add every single neighbor of this room and you can see i haven't actually defined that function yet so let's do that up above once i actually write this out so basically what i'm doing is going to be adding all four adjacent rooms to the queue and we obviously know that some of these rooms might be out of bounds some of them might have already been visited that's why i'm going to put this in a helper function to basically abstract some of that logic for us so let's define the function up above over here so add room we're just going to pass in a couple coordinates so basically if this row is less than zero or if the row is out of bounds meaning it's too big meaning it's equal to the number of rows or the exact same thing for column if column is less than zero or column is too big or if this position row column has already been visited or one last condition basically if this room is a wall or an obstacle right because remember not every position in our graph is a empty room it's it could it's possible it could be a obstacle meaning it's equal to negative one so if any of these above conditions is true we're going to immediately return because this is an invalid room so we're not going to actually add it to the queue or the visit set but if it's not invalid that's when we can go ahead and say okay visit dot add to the hash set and go ahead and queue dot append to the hash set as well right so basically you can see why i'm putting this stuff inside of a helper function because we don't want to have to call that four times and i don't really want to put a loop in here because i just think it's kind of messy i'd rather just write it out like this but so with all of that done we can see that we have added the rooms we're making sure to increment the distance every time we complete a layer and we're basically going through rooms labeling what's the minimum distance from that room to a gate once we're done with that we don't actually have to return anything because we just have to modify the room's 2d array in place so this is all the code that we're actually going to have to write so you can see that this solution is efficient we're basically visiting the entire grid a couple times i think two or three times because of course we have this initial loop and then we actually have to run our bfs solution but it's still a linear time solution with respect to the size of the input array so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Walls and Gates
|
walls-and-gates
|
You are given an `m x n` grid `rooms` initialized with these three possible values.
* `-1` A wall or an obstacle.
* `0` A gate.
* `INF` Infinity means an empty room. We use the value `231 - 1 = 2147483647` to represent `INF` as you may assume that the distance to a gate is less than `2147483647`.
Fill each empty room with the distance to _its nearest gate_. If it is impossible to reach a gate, it should be filled with `INF`.
**Example 1:**
**Input:** rooms = \[\[2147483647,-1,0,2147483647\],\[2147483647,2147483647,2147483647,-1\],\[2147483647,-1,2147483647,-1\],\[0,-1,2147483647,2147483647\]\]
**Output:** \[\[3,-1,0,1\],\[2,2,1,-1\],\[1,-1,2,-1\],\[0,-1,3,4\]\]
**Example 2:**
**Input:** rooms = \[\[-1\]\]
**Output:** \[\[-1\]\]
**Constraints:**
* `m == rooms.length`
* `n == rooms[i].length`
* `1 <= m, n <= 250`
* `rooms[i][j]` is `-1`, `0`, or `231 - 1`.
| null |
Array,Breadth-First Search,Matrix
|
Medium
|
130,200,317,865,1036
|
111 |
Hello everyone welcome to me channel court story with mike so today we are going to do video number 28 of our playlist of binary tree such a question is quite easy and after quite a few two a good and easy question has been given by lying down number 111 but they Bill B Solving It Using Buffs Well Ahead of Binary Question is named and it has been asked by Amazon and this place you will already know I am available on Instagram Facebook with this name and on Twitter I am available with this name IF YOU ARE IF YOU WANT IF YOU LIKE ME CHANNEL YOU CAN DEFINITELY KNOW ALSO OK, I understand the question, it is a very simple statement, friend, you have to find the minimum depth, you must have given a binary tree, you have to find the minimum depth, you have given the definition of minimum, which helped a lot. To understand this question, the number of notes has to be found along the shortest path from the root note. You are the nearest leaf note. It means, look at this example, it is definitely correct. Which leaf note is closest to the root, so many are visible. This one is this and this one is this, brother, which one is the nearest leaf note, so how many notes are there in this lesson, both the people are one or two, that is my answer, if you are ok, then its solution is also very simple. This is because you must have already prepared such questions. In college too, the teacher must have given many questions on calculating height or height. In college, first of all, what did I find to be the most intuitive method? Actually, this is his BF. What is the reason? I will tell you as soon as I get the leaf first, which is sorry, as soon as I get the note first, I will tell you at this time, brother, the story is over, what am I saying, repeat again, remember, the labels are in order. What we used to do, we used to travel through one level at a time. Look at this level. Is this level one? Is it the root? Is it the leaf note? Is it the root? If not is it the leaf note, then its left. And go to the right side and then come to the next level. Okay, so these two modes are on the late level. What is the level? This is level number 2. So in this level, as soon as I saw that okay, I have found a leaf road, I did something. No, I will return from here only, blindfolded, value of level, you are ok, first of all I have got here, I will return here only, why will I go down, there is leaf road below too, I know, but first of all, I will get at the top because I am level. I am doing buy level travels. Okay, so any solution for this would also be very simple. You can write normal BFS, normal BF. Out of that, you got such a note which is the only fruit, at this time return the value of level. And the biggest confusion that people have is that there are two methods of BF. You must have read that one is a simple vile note off ke dot. Well, what happens in it is that the one which is in the front is taken out ke dot. After friending and popping it, okay, then let's see whether this time is left or right, then why I give pulses and there is an implementation, how much note is there now in my current level, the dot size is fine and after that there is a wire inside. Loops have to be written n - - so that all the roads in this level have to be Loops have to be written n - - so that all the roads in this level have to be Loops have to be written n - - so that all the roads in this level have to be processed at once. Okay, whenever I have always told you, even if I have not told you, then there is no problem. Learn today that whenever it is a matter of level. If you are talking about level depth in the question, then sorry on this formula, write this method in BF, otherwise this method is also fine. Whenever there is any information related to level, if you have level, then you have to write level in the solution. If it is going to help then you can simply write this BF in which we follow what we do inside as well. What is the benefit of this, ca n't you finish one complete level at a time, then you finished it completely in 3 steps in the beginning. I have just popped 3. Now look, is it three? What is its size? Only one element will pop, that is, this entire level will be over. I had popped three in level one. I pushed three left and right, that is, 9. And 20 is pushed. This is the next level. There are only two notes in this level. Look, there are two modes here, so I have to pop both the notes at once. N = 2, that is, there N = 2, that is, there N = 2, that is, there are two elements, both the elements. If I want to process the number at once, then there is no left and right side of the nine, otherwise I will return the value of the level from there itself, whatever will be, it is okay, that is why we will write this code of BF, okay and this is the BF now. If there is a simple DFS then that DFS is even simpler, I will tell you quickly then BF and BF will code both of them, why do I think it is the best because BF is a small wrecker of martyrs, see what can I tell you. I am saying that this is the root, okay this is the root, if this is not Leaf Note, what does it mean that it will start from here only, wherever you look, now wherever you go on Leaf Note, now either you go here or here, then talk to him. We will definitely have this route, meaning one note has been counted as one, after that whatever comes from the left side or the right side, let me add the minimum of the two because I want minimum depth. Okay, so the minimum is whatever comes from the left side. And whatever comes from the right side, which is minimum, will be my answer. Okay, so before the left side, let's try it tomorrow. I came to the left side and reached here. Is this a lip fraud, then what will be said in this that brother, I am a banda only. I am a single nodu below me, there is no one else, so I am returning one, so in this I have returned one directly, that is, what have I got from the left side, I have got one, now come to the right side, this guy on the right side will say, brother, under me. These are also leaf notes, meaning I am not a leaf note, so this will also say the same thing, this will also talk about recognition, this will say that I will get a note, this will be given to you later, but whatever will come from my left and right, I will minimize them and send it to you. This will also go to the left, turned to the right, this also turned left, turned to the right, this also made it 18 because this is a leaf note, so what is the minimum of left waist right, one comma 1 + left waist right, one comma 1 + left waist right, one comma 1 + minimum one comma one i.e. 2, so what will this return do, will minimum one comma one i.e. 2, so what will this return do, will minimum one comma one i.e. 2, so what will this return do, will you return? It is made from left of it, what came from its right, you came, if you add minimum of both then 1 + add minimum of both then 1 + add minimum of both then 1 + minimum one comma, you are one, that is, the answer will be you, remember the answer from BF was also mine, you were the right one, it was a very simple easy question. Let's quickly solve this and finish this question. So let's do it quickly. First of all let's finish its code from BFS. Okay, so what I told to BF that why would I take that if my root is equal to null. So I will not return anything, I will simply return zero. Okay, as long as we are talking about reverse levels, first find out the size, dot size and all the levels at once, level it, process all of them, okay, stamp. This is equal, you pop, okay, now what I said here is that if the left side of the temp is also null, it means that it is very simple and as soon as this level is over, submit it and see, it was a very simple question, okay, note, solve this question using Now let's solve DFS quickly. DFS is even easier. Let's clear it here and here again and put the same check. If the root which is mine is equal to null then it means there is nothing, there is no death. I have it, okay, now I told you that you can also write it like this, note of root, the root will be removed, you can also write this, okay, this is a shortcut, listen to one more thing and think, if the left side of the root is also null and so on. The right of the root is also null, which means simply return one and it will return two. I had told you in DFS that it is a leaf note, brother, it will return only one or not, I am a note, this is fine, what will I do now? What did you say, I will take it from the left, okay, I took it from the left, sent the left of the route, okay, I took it from the internet and sent the right of the route, okay, only then you will do it tomorrow because in the end, I have to send only the minimum, isn't it the last? It was said that OnePlus has to send the minimum of LCom R, this is what you have to send the minimum, otherwise I have made it international. Similarly, here too, if you send the right to root, then first check that the right to root note should be equal, only then it should be null. So you will do it tomorrow, is it okay, otherwise understand, if you remove the minimum international here, then I will return from here itself, I will not reach here, this thing is clear, so I have to say, always do dry iron, dry and doing it is much more than that. The thing is open caste, okay, simply submit it and see, hopefully they should be able to pass it in any DFS, also see, it was a very simple question, it was solved, but just for practice, make all these questions, don't miss it, okay Is able tu help normal this O of N is the same algorithm because every single note is being wasted only where n is equal tu number of notes is ok any doubt is there please read in the comment area tree tu help you next video Thank you
|
Minimum Depth of Binary Tree
|
minimum-depth-of-binary-tree
|
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
**Note:** A leaf is a node with no children.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 2
**Example 2:**
**Input:** root = \[2,null,3,null,4,null,5,null,6\]
**Output:** 5
**Constraints:**
* The number of nodes in the tree is in the range `[0, 105]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
102,104
|
1,631 |
how's it going so let's look at leak code 1631 path with minimum effort you are a hiker preparing for an upcoming hike you're given Heights uh 2D array Road times columns where Heights row column represents a height of cell row column you're situated at the top left corner and you hope the bottom travel to the bottom right corner you can move up down left to right and you wish to find a route that requires the minimum effort a routes effort is the maximum absolute difference in Heights between two consecutive cells of the route return the minimum effort required to travel from the top left to the bottom right cell I was initially going to say this is a textbook uh breadth first search pathfinding problem but this is a that's a little different the way they Define effort so basically it's going to be the maximum difference between two cells at any point this is one of those gotchas if you didn't actually read the text so let's say row equals length of heights and equals length of heights zero all right and uh so we're going to use a heap also called a priority queue I guess I can declare that in the same thingy but I don't know what I'm talking about um and we are starting in 0 and the max effort at that point is going to be zero so that's what we got so yeah so that's good okay while H man there's always going to be a path so while true um let's see uh Max difficulty I comma J equals Heap pop h and then where we can go four directions right so if I is greater than zero then we can go and then what is that left it's row so if the row decreases so that'd be going up I it doesn't matter uh so if it's yeah then Heap push um age and then it would be something I comma J and it would be Max of M comma absolute value uh this is getting kind of silly uh Heights I minus one J minus sides I of J oh that was the wrong button okay and then this has got to be minus one and we can repeat if J is greater than zero then we're subtracting from j instead of from I foreign oh first off if I equals R minus 1 and J equals c minus one then return M that's going to be our not base case that's the wrong word but you know what I mean Okay so if I is less than I plus 1 is less than rho if J plus one is less than column sorry being OCD isn't helpful in this uh instance but whatever now we're just going to go through and change these to pluses and I mean that should be it I mean that should work right assuming I didn't make a mistake which I never do all right run invalid syntax Heap push um oh sorry that was probably painful watching me type that oh this is taking longer than I'd like you're scared me a lot oh yeah this isn't gonna work it's gonna go around in a circle over and over again we shouldn't uh we shouldn't do this unless it's actually uh less so yeah we shouldn't drop it into the Heap unless it actually decreases I hate this okay we're gonna say uh death proposal I guess uh so we're gonna have the target destination and the value and then this needs to remember okay uh so we're gonna have uh best equals Infinity for J in range uh see for I in range um r and that it doesn't need to be Infinity that's a little bit silly so let's go 10 to the ninth that's close enough to Infinity close enough for our purposes so oh and it's also gonna need h actually let's switch and put the H at the beginning so if m is uh greater than or equal to best I of J and you know what that's not how I want to do it if it's less than it then we're going to actually add heat push uh um m i j and then best of I J equals m work so now instead of heat push we are going to have prop for propose uh there that should eliminate the infinite recursion sorry I had the original solution in my head with uh you know where it subsequently added things so beats 97.21 that's not bad I feel like 97.21 that's not bad I feel like 97.21 that's not bad I feel like they upgraded their VMS recently so we're artificially getting a boost Python 3 uh priority I don't want to say that keep Q Plus memory I don't know if anybody gets anything out of these 152 people like my comments uh I support I submitted right of course I submitted I wouldn't have been able to post a response okay that's it
|
Path With Minimum Effort
|
number-of-sub-arrays-with-odd-sum
|
You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**). You can move **up**, **down**, **left**, or **right**, and you wish to find a route that requires the minimum **effort**.
A route's **effort** is the **maximum absolute difference** in heights between two consecutive cells of the route.
Return _the minimum **effort** required to travel from the top-left cell to the bottom-right cell._
**Example 1:**
**Input:** heights = \[\[1,2,2\],\[3,8,2\],\[5,3,5\]\]
**Output:** 2
**Explanation:** The route of \[1,3,5,3,5\] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of \[1,2,2,2,5\], where the maximum absolute difference is 3.
**Example 2:**
**Input:** heights = \[\[1,2,3\],\[3,8,4\],\[5,3,5\]\]
**Output:** 1
**Explanation:** The route of \[1,2,3,4,5\] has a maximum absolute difference of 1 in consecutive cells, which is better than route \[1,3,5,3,5\].
**Example 3:**
**Input:** heights = \[\[1,2,1,1,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,1,1,2,1\]\]
**Output:** 0
**Explanation:** This route does not require any effort.
**Constraints:**
* `rows == heights.length`
* `columns == heights[i].length`
* `1 <= rows, columns <= 100`
* `1 <= heights[i][j] <= 106`
|
Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa.
|
Array,Math,Dynamic Programming,Prefix Sum
|
Medium
|
2242
|
278 |
Hello guys welcome back to take decision in this video you will see the first version problem system day one of the greatest problems will explain the problem in simple terms of problems in the production line producer product Thursday The Page if you liked The Video then subscribe to the Problem Hai You Can Rectify The Problem Here Volume Subsequent Problems Will Also Be Who 100 Goal Is To Find The First Version And Were Not Giving Here They Can Actually Make A Call To Give One Number Call to the number only answer and intuitive and subscribe and you can only for watching this problem very similar to rotate directly subscribe quote point to that is which will have in the starting point in the original software for this problem and this problem exactly The Same But Different Set The Problem Vijay Singh Subscribe Sure 1018 Unauthorized Test In The Number One Adhir Will Be No One Will Dare Attack You And You Can Just A Different Value Result In Order To Get Appropriate Answer So Let's Not Solve This Problem Solved Mit Pointer is this reel listen you see them with values and Pointer is this reel listen you see them with values and Pointer is this reel listen you see them with values and you can see the values and the you can see the values and the you can see the values and the results 12512 subscribe know what will they will update the - The Video then subscribe to the Page if you liked The Video then process and very simple question is that in This process will take orders of long and time to find the first version indishere so let's look at the code simple on Twitter The Amazing Id result in this question In the last words are you going back to know when the solution is different Languages Like Share and Subscribe Our Languages Like Share and Subscribe Our Languages Like Share and Subscribe Our Channel Like This Video
|
First Bad Version
|
first-bad-version
|
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
**Example 1:**
**Input:** n = 5, bad = 4
**Output:** 4
**Explanation:**
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
**Example 2:**
**Input:** n = 1, bad = 1
**Output:** 1
**Constraints:**
* `1 <= bad <= n <= 231 - 1`
| null |
Binary Search,Interactive
|
Easy
|
34,35,374
|
486 |
hello everyone welcome back to another episode of finance and uh coding today we are going to tackle a fascinating problem from the realm of dynamic programming uh titled predict the winner so this problem has a medium difficulty rating but it uh packed with a great concept so I will be explaining everything in Python but don't worry if you're using different language you will find the code for other languages in the description below so let's Dive Right In so here is the problem we are given an array of integer and two players are playing again and the rules are simple both players take turn Player 1 starts and they can pick a number from either end of the array so the chosen number gets added to their score so the goal is to have a higher score than the other player when the array is empty so your task is to determine if Player 1 can win the game assuming both player play optimally so let's walk through an example to make this clear let's say our input array is 1 5 2. so yeah that's even right so we have one five two so if we have this array player one as the first move and he can pick one or two because he can pick from ends of the array so both are the ends so now uh so no matter which one he choose player 2 can then choose a F5 because for example if player one uh take two uh RI will be one five after one iteration so it will be player one P1 and player two can pick then uh five and the remaining could be picked by player one so basically in both cases whether a player one pick one or two player two can pick the five that is bigger so we need to return uh that it's impossible so output should be false yeah so uh this leaves a player with a lower number so output is false so all right now that we understand the problem let's dive into the code so we will use a dynamic programming to solve this problem so the idea is to build a 2d DP table where each cell represents the maximum possible score difference a player can achieve over the other player so we start by initializing our DP table and each cell will be a dpij is filled by considering the maximum of two standards choosing the if number or the J number if the it number is chosen so the score difference will be just uh num I minus DP I plus 1 J so if J number is chosen the score difference will be then simply num J minus DP i j minus 1 so previous peaked score so we choose maximum of this two so let's implement it and explain so n will be uh line of nums and DP will be 0 times n or in range n and four I in range n minus 1 4J in range I and if I is equal to J d p i j will be nam I so else d p i j Max num IDP I plus 1 J num J minus DP i j minus I and we return DP off zero n minus 1 greater than zero so uh this is our implementation so as mentioned previously we started by initializing our DPT table and as you can see each cell in DP i j is filled by considering the maximum of two students choosing the if number or the J number and if I score is chosen the score difference will be uh the function provided so let's see this in action so let's run it for a given test case and see if it will be outputted as false so yeah oh good because uh we need to return the logic operation uh that is difference between uh two players so if it's greater it means that will return true because uh player one could win the game so let's see this in action with an example of uh one five uh 233 and 7. so player one uh can ultimately achieve a higher score by first picking one and then 233 so no measure watch player 2 does player one uh will end up with a higher score so as we can see our code is working for this simple test cases so we have fourth and true for second so now let's run it four and synthesis cases as well to verify everything working so we have successfully completed the daily challenge day 60 in a row and yeah our implementation is quite efficient it beats 91 with respect to runtime and also 70 with respect to memory and as we can see our code is working for various test cases and it's running in O and square time complexity which is acceptable given our input size constraints and that's it we have solved that predict the winner problem using dynamic programming so I hope this video helped you understand this problem and its solution better so remember practicing problems like this will make dynamic programming concept much easier to grasp and more intuitive so if you have any question or if something wasn't so clear leave a comment down below and always code uh as much as possible and the code is also available in the description uh in multiple languages so that's all for this episode so don't forget to like this video uh if it was helpful and you want to be a better programmer And subscribe for more coding problems uh explanation and tutorials and much more and happy coding keep practicing stay motivated and see you next time
|
Predict the Winner
|
predict-the-winner
|
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` or `nums[nums.length - 1]`) which reduces the size of the array by `1`. The player adds the chosen number to their score. The game ends when there are no more elements in the array.
Return `true` if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return `true`. You may assume that both players are playing optimally.
**Example 1:**
**Input:** nums = \[1,5,2\]
**Output:** false
**Explanation:** Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return false.
**Example 2:**
**Input:** nums = \[1,5,233,7\]
**Output:** true
**Explanation:** Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
**Constraints:**
* `1 <= nums.length <= 20`
* `0 <= nums[i] <= 107`
| null |
Array,Math,Dynamic Programming,Recursion,Game Theory
|
Medium
|
464
|
242 |
hey wassup guys think wider I did tacking coding stuff on Twitch in YouTube I doom the premium problem solutions on my patreon I appreciate anyone supports me if you want to reach out to me discord or patreon is a good place I try to get back to everyone this problem is called valid anagram very easy problem I can't believe I didn't even do this one well I did it I didn't make a video but given two strings s and T write a function to determine if T is an anagram of s so you got two strings s and T and we want to know if T is an anagram of s okay what is an anagram is just a rearrangement of the letters so this has to be a rearrangement of these letters a few things to note there has to be the exact same letters in the exact same you know if there's three A's in this there has to be three A's in this so the letters in this string have to occur in this string the exact same amount of times the only thing that's different is the they are rearranged in a different order so in this example there are you know three A's in this string there's an N in this string there is a G in the string there's a G in this string there is an R in this string there's an R in this string and there's an M and there's a now the only difference is they're rearranged so that is true in this string there is RA T in there CA are so this one has a T but this one doesn't and it has a C instead so this needs to have a tee and remove the C and get you know put a tee where that is and then it would be fine so how do we solve this it's actually you probably one of the easiest problems on this site you may assume the strings only contain lowercase alphabets so first of all they have to be the same length because it's the same character is the same amount of time so we could do a simple check okay if s dot length is not equal to t dot length well then it's for sure not an anagram so return false now the way that we're going to do this is using a char map to the number of a car what we really care about is the number of occurrences of each letter so if there's three A's in this string we want to find three is in this string right so we can do that by using an int array we'll call it char counts and we will say it's a new int of size 26 because there's 26 letters in the alphabet so it's not a huge on space or anything we what were what the strategy is we're gonna loop through this string and we're going to fill this into ray with the count for each character so when we see an a we're gonna be like okay we saw one a and every time we see an a will increment that so we saw we have will have the count of each character at the end in this string so we're going to be incrementing the count for each character in this string we're gonna be D commenting in this string so in the end if all of the counts for each character are 0 then it evened out and it's fine so you increment you do plus we see an a we go okay we saw one eight plus one plus two plus three we saw three days and when we see an A in this string we'll go minus one so all the characters if we increment in this string but we decrement in this string when we see them they should even out so that each character has a count of zero at the end and that is the strategy you could also you know just make an array for this one and then go through and make sure that the count is the same for this one but I think this is a lot cleaner and nicer so we're just gonna loop you can loop through either strings length because they're the exact same length we already checked that up here so we'll do a step length I plus will do char counts of s dot char at so that will increment for the string s so this gets the current character in s in this so this is the current character STR I the string at the current index so this gets the character will reference the index by doing this so this takes the current character subtract say so if the current character was a this would do a minus a and give us index 0 in 0 out of 26 would be the position of a in the alphabet so that's just a common thing in the char counts array and then for T our die we will decriminalize so this just takes the current character from each string subtracts a to get the index of that current character in the alphabet and then it increments it like I said for this string and D commence it for this string then at the end we just want to go through this array of char counts int count sorry in char counts and we will say if count is not equal to zero they should all be 0 then return false otherwise return true I'm a bad feeling about this oh there we go i oh I always make a mistake but this is one of those lucky occasions where I didn't make a mistake this time when I typed it up so that's the idea I think it's a very nice and easy problem especially to get warmed up with and yeah look at a while let me know if you have any questions I think I explained it pretty well but yeah that's pretty much it thank you guys for watching if you are a beginner and you really want to check this out it would be you know kind of like this char counts of we see an A in this string so we do a minus a because the current character minus a that gives us 0 because that's equal to 0 and then we do plus so char counts of 0 would be 1 because it's an initially 0 and then we see an N and it finds the AIIMS position etc that's just how the indexing works so thank you guys for watching appreciate you all appreciate everyone that watches the videos and thank you and I'll see you in the next one that's a
|
Valid Anagram
|
valid-anagram
|
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "anagram", t = "nagaram"
**Output:** true
**Example 2:**
**Input:** s = "rat", t = "car"
**Output:** false
**Constraints:**
* `1 <= s.length, t.length <= 5 * 104`
* `s` and `t` consist of lowercase English letters.
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
| null |
Hash Table,String,Sorting
|
Easy
|
49,266,438
|
67 |
hey everyone welcome to Tech Choir in this video we are going to solve problem number 67 at binary so given two binary strings A and B we need to return that sum as a binary string so basically we need to perform binary addition now we will see the logic and the code for this problem now let's dive into the solution so here I have taken the second example from the liquid website I'm going to apply two pointer approach in order to solve this problem so I will start from the end in my both of my string right so I will just start iterating from the end so now I will start iterating so I will pick 0 di 0.0 di 0.0 di 0.0 then I will pick one from the input B that is here then I will add carry to it so initially my carry will be 0 right my carry will be 0 so I will add 0 to I'm going to get 1 so my sum is going to be 1 now then I will get the quotient and the reminder from 1. from the sum that is 1. to get the quotient that is the carry here in carry means quotient right so to get the quotient I'm going to perform floor operator so one I will perform floor Operator by 2. right this will give me carry then I'm going to have reminder that will be obtained using modulo operation one modular two so here the carry will be zero my reminder will be 1. so carry will remain zero right my carry will be 0 only then I will have a result set then I will have a result list where I will add the reminder to it I will append to it so it becomes one assume this is the result and I am appending one right now I will move my inj pointer to pick the next values so this will be I and this will be J now so now I will add 1 and one again then we carry that is zero now I will get 2. right now I will perform operation on two so I'm going to get 1 here then my reminder will be 0. and I'm going to append this reminder to the result set so now it becomes 0 1 and 0 right and my carries one I'm just putting here one now I will move my i n j pointer here I so high comes here and J comes here now I'm adding the values from the input that is 0 plus 0 and carry that is one now so I'm going to get 1. now I will perform floor operation on one I'm going to get 0 then I will perform model operation on one I'm going to get one so I'm going to append this one to my result set so it is 1 0 1 now then I'm going to change my carry so I'm updating the carry now again I will move my I and J pointer so I comes here and J comes here so now I will add 1 plus 1 and plus carry right so this one and one comes from the input that is my in J pointer values right now my sum becomes 2 and I will do floor operation on sum so I'm going to get one has my carry and the reminder will be 0. right so I'm going to append 0 to my result set so now it has become one zero so my carry has been updated so I'm going to update my carriers 1. so now my inputs are I created successfully I cannot reduce my I and J pointer further since both are out of Index right now but still my carry is left I have one remaining to be updated in my result set so I'm going to update this one I'm going to append this one final in my result set so my new result set is one zero I'm gonna add the carry at the end right I have appended carry at the end when returning the result final result we need to reverse the result set so my final result will be 1 0 1. right it's just the same this is the reverse of result set right this is the reverse of result set and there is also another scenario what if my inputs are imbalance assume if I have only two values in b so when I have an imbalance in my inputs I will be using 0 as default value right so that I don't have an influence from the completed input right so the time complexity will be order of N and space will be order of n as well now let's see the code before we code if you guys haven't subscribed to my channel transcribe this will motivate upload more videos in future and also check out my previous videos and keep supporting guys so initially I'm having the result list then I am going to start with carry as 0 then I'm going to have my inj pointer which is nothing but the last index of the input a and the input B then I'm going to have a loop I will iterate until I have input and carry right so J is greater than equal to 0 or carry so I will it until I have my input and the carry right then I'm going to have the values so I'm going to make the values as integers using the input function so I will only append those values if my index is not out of range right otherwise I will make that value as 0 it is a default value if I done with my input but I still left with other input or carry then it will be 0 as default I will do the same for the input B using the int function and the pointer J is not out of index I will open the value else it will be zero so here I'm going to sum both the values D1 D2 that is the values from A and B then I'm going to sum the carry then I am going to have carry will be my quotient right so I will get the carry using the floor operator then I would get this reminder using modular operator right then finally I will append the reminder since it is an integer I will make it as a string using the string inbuilt function then I will reduce my in J pointer since we are traversing from backwards then finally I need to return the reverse of result list so I will just use join then I will robust I think it's fine let's run the code so the time complexity is order of N and the space is order of n as well thank you guys for watching this video please don't forget to like And subscribe I will see you guys in the next one
|
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
|
130 |
all right i'm trying on this problem called surrounded regions given an am cross and matrix board containing x and o capture all regions that are four directionally surrounded by x a region is captured by flipping all zeroes for all into x's in that surrounded region let's understand the example this example one uh flipping all zeros into axis in that surrounding region capturologies that are four directionally surrounded by x hmm i did not really understand so far so this guy x and x below so it's considering the region more than anything else for this zero there is no below so you don't uh eliminate this guy but if you look at this region in the top it's all x on the left it's all x on the right it all acts in the bottom also it's x hm if i look at individually for each cell right for this cell xxx it's right is zero but that's finally there is a and the right there is an x interesting similarly for this there's an x uh there is an x here though yeah this seems to me a bit tricky yeah for this guy xxx and there is an x above so certain region should not be on the border uh which means that only zero on the border of the board are not flipped to x any zero that is not on the border let's call it o any other is not on the border and is then it is not connected to an o on the border will be flipped two x two cells are connected if they are adjacent cells horizontally or vertically um let's read this explanation again surrounded regions should not be on the border so any zero on the border will remain zero that is clear which means that any on the border on the board are not kept works and you know that is not on the border and it is not connected to an o a and it is not connected to an o on the border will be flipped to x two cells are connected to the adjacent cells uh connected horizontally or vertically hmm so if you look at these all the o's is it connected to an o on the border no is it going to be an o on the bottom is that it ah that's interesting now if this was an o right then this is connected to an o on the border then this is connected to this so this is also going to be an o on the border this is connected to this which is connected to an o on the border yeah that so i'm not sure okay let's see this uh let's take this input i'll not do anything console okay let's import sd1 let's make this o and let's see what the output comes out as oh so none of them changes if this was an o that you would mean that all three of them are connected to this o because this is going to this isn't there so and this is going to do that so i'm getting some sense based on that can we do some sort of a connected component thing let's see data this entire remaining x is one connected component and this o is one connected component and this is another connected component hmm uh let's say i just simply walk through the array regularly i see this o is connected to this row that will really depend on whether this o is connected to pressing on the border so let's just first you go through the border hmm see if i go through the border first and this is the oi found then is there any o that is adjacent to it in this case it isn't one let's pick up this example do this and let's make this guy and go but okay now uh there is this guy has no actual nothing to do there is this guy is connected to this guy so do a bfs or a defense basically some sort of a traversal from all the nodes right from all the zeros all i want to do is get the uh get the connected components uh number for i think i can do that way so from this i go left right is nothing this is matching so for this i go all four directions other than the one that has been visited and wherever i find zero i go yeah so i do that so i do and that how much time will it take it will everything will be linear you won't you don't traverse any node more than once right so number of it will be o of number of nodes yeah and then we generate the number and yeah okay so let's try that out uh so basically what i'm saying is i connect all of these together and because they're all connected to a boundary node they cannot be so i'll call this right let's call component number or something um okay boolean array connect it to what you call connected to the o connected to boundary o right 92 border o if this is connected to border and we are only interested in all the hose right if this o is 22 border o then new boolean to board length and port of 0 okay let's get more space now only you want to you just have to walk through just the borders so i first go through this row then i go through this row note this one and i walk to this column when i do bfs traversal so i want to mark something called as visited okay so it's truly that's fine and now i want to do it four times right so uh yeah how do just traverse only the boundary uh maybe just four different loops it's okay doesn't matter all right then i equals to that is actually j right for j equals to uh 0 j is less the number of columns board of zero dot length let's do bfs on uh so we pass a specific element oh we only do bfs if uh board of i j 0. when you do bfs um okay fine just call it bfs and pass iej so bfs needs board bfs needs connected to this guy visited and the index is zero comma j okay this is automobile similarly uh we also check this for the last guy uh last guy would be board dot length minus one and we'll call here length minus one and this also needs to be done for the these two columns so i equals to 0 is less than 4 dot length i plus if from zero is zero or then you do this and i comma zero and here it would be uh row and column is the last one which is and same would be passed here okay so we do this traversal now what uh okay we like the bfs code but after that essentially what you have to do is we have to walk through all the inner elements so i'm avoiding the uh first and the last row similarly in the columns as well j equals to one j is less than minus one because even the last one is not nj plus and if now we'll use the sky if it is indeed connected to a border firstly we want to check if it's if board of ij is an o and it is not connected to a border o then we change it to x so this is linear everything else everything so far is the o of number of nodes right which is whatever this m of m um so this is fine now let's write this bfs what are we passing to bfs board okay so let's take all of these you have your board you have your connected you have your visitor and first things first if it is okay so you also need ing here okay so first things first is uh this is out of border so if i less than 0 j is less than 0 or else i is greater than equals to length then we know nothing to do and if this guy is already visited then also nothing to lc market visited another thing which is if it is x then we don't really care and now we mark so let me know it's just so just visit it is true and mark this as true and what you do you go in the four different directions that is all so i plus 1 j i j plus one i j minus one i minus 1 j right so that's my approach let's review what we did so basically this explanation in the example was helpful uh if there is any o which is connected to an o on the boundary directly or then indirectly through like if let's say this was an o not this let's say this was a no then all of this four o's would have been uh ultimately connected to uh this boundary o right so we have to figure out this connected components if there are if these for example in this current case these those are not connected to any on the boundary so they will be connected to so what we are doing is we are walking through all the edges and all the o's and the edges we are doing a bfs from there and looking for any os and if we find any os through while doing that bfs we break the bfs as soon as we find an x right so for example this oh there is no nothing to do but for this o for example when we go in different directions this o is this is an o so um this is going to this becomes connected and from there we go to different directions so all this uh flipped t right uh they will all be considered connected to a boundary o which is what we're trying to do and of course we don't visit multiple nodes again and again we use this visited and in the bf as a solver between if we find an o in the vfs path we mark it connected market visited as well so we don't visit the same codes again and we go in the four different directions we take the as soon as we fall out of the grid we handle that case here yeah these are the four uh edges from where we're doing the bfs and finally we go through the inner nodes and we check those inner nodes if they are o and they are not connected to the border then we convert them to x let's learn currency what happens fix the compilation errors all right so first one is accepted let's do run example test cases okay let's take the example that we were considering so this one but oh okay this is the one that has been done okay good so yeah so the case that we were thinking of has also worked as well as all the test cases let's sum it and it works alright so that is the solution
|
Surrounded Regions
|
surrounded-regions
|
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Explanation:** Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
**Example 2:**
**Input:** board = \[\[ "X "\]\]
**Output:** \[\[ "X "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is `'X'` or `'O'`.
| null |
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
|
Medium
|
200,286
|
143 |
this is a singly linked list based problem and in this we have to reorder the nodes of the list and we are not allowed to change the values we are allowed to actually move those nodes so if we have let's say list like one two three so it's not that if we want to let's say we want to reverse it so in that case we are not just copying the value and putting it here we are actually moving the this pointer here so we have to actually move the nodes and not the values and how do we need to move the list let's see an example so let's say this is a the list that is given to us it's a singly linked list and the result should be such that first node will be 1 its next will be the last node so one we are picking from left side one we are picking from right side so 1 5 then this left one comes here right one comes here so next is 2 and then its next will be the one from right then you move this here and you move this here but you cannot move backward in the singly linked list this is the basic linked list concept so after 4 it should be 3 and it should be null so number of nodes remain same we just reorder them that's why it's called reorder the list and it's commonly asked in facebook amazon apple ebay byte dance and a few more companies so it looks like a popular problem so uh how can we do this so uh we need one from the beginning and one from the end so i would i will start with a not so elegant solution then we will arrive on a much more elegant solution so uh we will what we will do first we will traverse this list and store the pointers in a stack so we store one two three four five these are not values and these are the actual pointers and now its size is five so once we have put it in the stack uh we will start from here so current will be here at the head and then it's next so let's store 2 we will need 2 so next of 5 is 2 so we save this into a variable called next equal to current next this we can do and current is initialized to the head this is a head we are not changing it and this will remain head for the final list also so it's next we saved so it's storing 2 the node corresponding to 2 and then currents next is equal to top of the stack so this is stack s dot top and then we also pop it so 5 is gone and current's next is this top so what is the state we have one its next is pointing to five and five is next was null so no other pointer changes and two is separate so 2 is pointing to 3 is pointing to 4 is pointing to 5 and 5 is not pointing anywhere so this is the state after this statement next what we will do uh current should move here at five so this part is finalized now after one there will be five so current equal to current next you don't need to use this solution i'm just writing it will give you some practice and then we will also see a better solution so stay tuned for that so current now comes to 5 type then 5's next should be 2 and 2 we had saved in the next variable so current comes to 5 and current next is equal to next and next was 2. so what is the state now let me redraw it so 5's next is 2 and current is still at 5 so what we can do current equal to current next so now current comes at 2 and let me remove two from here so this is one iteration in this what we did one five two so this part is finalized and current is again here and the next of two is three it has not changed so this pointer we never updated so we have to just do the same thing on this part of the list so at the end of this loop we are again back to the original problem with a smaller list so again next we will store that is 3 so this time next is 3 and currents next equal to s dot top that is 4 so current was 2 so its next is now 4. so next of 2 is 4 and current equal to current next so current comes here and its next is next whatever we had saved so that is 3 and current comes here at 3 and then we will stop since we have added five nodes so how many times we should pop it so we will keep track of uh how many nodes are there so there are five nodes so we will do it two times if we had six node we would have done three times so now we will stop and this loop will end so what is the state one is pointing to five is pointing to two is pointing to four is pointing to three but three is again pointing to four so this is the extra thing that we need to take care of so when this loop ends current is pointing here so at the end of this loop what we will do current next equal to null and that's it so this is now null and we get the result so the complexity for this would be you can see we have done two traversal of the list one for this building the stack and second for or changing the pointers so time complexity is often space complexities also often but there is a better way we can get rid of the space time complexity we cannot get rid of it's expected so you will be looking you can see that from the stack we are popping half of the elements that is we are interested in the second half of the list so in the second approach what we will do let's write it again one two three four five so we are interested in the last two elements so if we reverse it so let us reverse it so we make it one two three and then these pointers we have to change five four so five then four so in the first part first half you see one two three occur in same sequence that is in original order but the latter half occurs in reverse order that is first five then four then if it had any other element so if we reverse this part then our job will be very simple we have to just merge two lists one by one so keep it as it is and this we change the this we make five it points to four and four points to three so we have reversed it so now let us draw it in a different manner we draw one two three and five four and it's also pointing to three and next of three is null so this is after we reverse the later half and how can we reverse it's very simple you start that slow and fast pointed concept slow pointer first point slow pointer advanced by one first pointer advanced by two and as soon as fast becomes null or next of fast becomes null we stop so when slow is here fast is here when slow comes here fast comes here by two steps then slow comes here and fast again jumps by two step that is four five so at this point we will stop since the next of fast is null then we know the middle of the list so we will take this list so just take this part of the list so whatever is the slow pointer pointing to reverse the list starting from there and the reversal code is very simple we will write that in the code so after reversing this will be the state so now let's focus on this so now what we will do we will take two pointers let's call them n1 and n2 so how we will get five so we will reverse this part current is here next is here previous is null so uh its next will be null so 3 is next we will make it null whatever is previous so the way to reverse is current next is previous so whatever was the previous we make it next and then we will advance current equal to current next and previous equal to so first previous we will update previous equal to current and current equal to current next so we will see that so you must be familiar with reversing the list it's very simple so now at the end we will reach here and current will become null then we will stop so previous will be pointing here one node before so previous is pointing to the last node so that way we will initialize n2 so n1 will be initialized to head n2 will be initialized to previous and we have reversed it this is the state so our job is very simple what we will do uh n1 next equal to n2 so this is very clear evident here so once next is 5 so this is the answer once next should be 5 and after that next of 5 should be 2 so better store it in a variable so this is initialization part and this is we will do in iterations so temp is pointing to 2 next of one is 5 after that what we need to do at the end of this iteration we should be n1 should be here and n2 should be here so the problem should be exactly like before so we move n1 to next so n1 equal to tmp we had stored it in tmp so n1 is now here now what next there is 1 5 2 and here we should have 4 3 so n2 should come here so let's store 4 or tmp equal to n2 dot next so this 4 we have saved and after that n2 next equal to 5's next should be 2. so n 1 and then n 2 equal to e m p so n 2 comes here now n 2 is here n 1 is here so this is the state after 1 iteration so this part is now finalized and we have to just work on this part so again do the same thing so it will be 2 its next will be 4 and n2 will come here and enable will come become null so we can add a condition that if n2 dot next is null we stop so let's write the code for this we will write the code for both of the approaches in fact so now everything is pushed into the stack so if we have less than or equal to two nodes then we don't need to change anything so if n less than equal to two then simply return there is no reordering else we will need to do it n by two times so we pop just n by two elements from the stack or we can define this outside since it will be done again and again s dot top and what we had done in the end for the last node we had to set the next equal to null so here in the last part this three was pointing to four so in the end we had to do this so this is the first solution and it will take off and time and space then next we will implement this one so first let's run this so this solution is accepted and it takes 40 milliseconds so let's uh implement the other one and we will compare if it takes less time or not so in this let's add a base case if head is not there or next of head is not there then return it does not return anything so just return so slow is advancing my one first is advancing by two so by the end by the time fast reaches the end slow will be in the middle so after that what we will do we initialize the current with slow that is mid of the list and we will need a temp variable where we will save the next pointer so you can also call it next so we are just reversing the second part here so this is the reversal part so we have stored the next now the next of current should be previous so whatever was the previous then we advance the previous to next so the previous for the next node will be whatever is current node previous equal to current and then current should also move but we have changed the current next but before that we had already saved what was next of that so current moves there it's very simple it will reverse the second half then we will do the final part that is merging of the two lists one by one first from first node second node from second list and so on so we have stored the next first and we will make the next of this two and the next of n2 should be this one tmp so n2 next is tmp but if we change this we will lose track of the next of n2 so we will store that first so n1 let's advance it we are done with n1 so when one becomes its next that was tmp now in tmp we store the next of n2 so we are using the same variable for both purpose you can use two also but the work of tmp is done till here for this part so here we are storing into next and then only we will change the next of n2 otherwise we will lose we will break the list so we have stored the it's next and then updated it's next to n1 and then n2 becomes tmp so these two parts may look very similar the first and second part and the end of this iteration one iteration we will finalize two nodes one from first list one from second and both n1 and n2 have advanced by one in both the corresponding lists so time limit exceeded we must be doing something wrong here so some of the loops are not terminating so this clearly is valid uh here current equal to current so it should be tmp otherwise it will never terminate and the solution is accepted so this time it takes 28 milliseconds so although the time complexity is same you can see a better much more improved solution here 99.85 much more improved solution here 99.85 much more improved solution here 99.85 although this can be a fluctuation also now let's write the optimized code in java and python so and the java solution is accepted finally we will do it in python you and the python solution is also accepted
|
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
|
1,192 |
A Place With Learn Today We Will Talk About Another Popular Problem List Ko Difficult Connection Network Lesson And Problem Test In Amazon As Well As Mother Big Companies And Its Very Important Problem And When You Learn How To Implement In Questions Network And Basically Is Critical Connection And A Vehicle Service Tax Which Bellcomes Difficult Connection For This Country Vortex Among One Remove From Visible All Day Long Not The Customer Only Activate Not Able To Reach All The World's Most Difficult Word Accident So Ashes Exam Sugriva Veervansh Did Not Possible They Unless Also Body Figure Out Which Three Subscribe 280 Shopping Discuss One Mostly And Discrimination Country Fiction Suicide This Slider That And Agreed To Learn How To Find Difficult Correction Sombir And Torch Light Solution Vihar Question Political Connections With These Representing A Number Of Participants To Indicate The Fort And Ranbir Which Is Deposit Connection Soegi 20 2013 The Water Into Sbi Me To Draw A Face And Along With Difficult Slightly Modified Badminton In Two Separate Address Which One Call Discovery And The Record Discovery Half The Record Low And Minerals That You Want To See The Inheritance Of Dresses And Against Difficulties in servi snowden trace your news table tehsil second time complexity suav list on ho the best that in the voice of america should you keep r ko political parties tell bihar that this boat again bluetooth highway channel a person should address lord and then Hee loot ghee speed significance payment of the day you in detail in this ki nangal hai loot solid tracks par use ko operator and vent outside treatment class to koi solution address entry ho me busy hain hua ho only toh ki a and sunao hai Ya Right Knowledge Skating Agra Song Detail Information Only Today Tractor School Hua Hai Ki Minister Girl Photo Is Festival Pregnant Is So Miss You Ki Intermediate Science Of To Size Ki Negative Singh Always Be With You All Ki N E Want Discoveries And Open The App Of Cement Given that the time table is 2015 size, then we are affected by the business of Sigrauli. Ajay is so despacito remix vibration tan, so curved shoulders, started like mother's, middle school loot tax less market s maximum s scene in the house before being and Which eighth foreign did you do by switching off the torch and suggested that I Plus video loot that pirates take with them MP3 loot lo hua hai and Bedouin hairs were getting inches and that nation from the connections that these this year old kid edison electronic 420 and vihar phase first label polish second connection 0512 software testing of creating and adding images for 10 gm fennel 125 a college student's 25th in false cases so 108 member student died in vs with this we are going to Call Travels 210 And Biggest With Any Of The Word Is Let's Start Loot Hain 80 Kumar And Jobs Which You Are Starting To Fix Deposit Food - Android Apps Deposit Food - Android Apps Deposit Food - Android Apps Also Discovery Time For Bed Observe A Starting Point On PC For This Point Too Very Difficult For Us And A Place Where It Course For Travelers And Send Them A Different Way The Politics Of World Services Hai Loot Ki Song Mein Film Something On Ko Fold Sureshwaram A Loot Hadt CPI Main India Australia Score Board Ka Paper Hai Question Singh Jai Ho Bluetooth WhatsApp App Meanwhile Mukesh Shares So On Demand National Award Discovery Counter Is Wherever E Started From Any Particular Word Absolute From Start From 0 To 2000 The Discovery Control Subscribe Our Secretary Mittu Increment Discovery Live Was In The Most 20012 Increment This Computer Knowledge by one and they never reach a particular word sb set's value for the world its discovery e and low but regular updates felt gift for the discovery what is the meaning the time taken to superintendent particular water from the paint significance discovery counter on these Software Bihar Discovery Policy In First Visit Counter Low Official Question Where Is This Account Naveen Cement Ever Counter Buy 1MB Smell Difficult Tax Acid 21 People Media & Reuters Rosinquist To Work On 21 People Media & Reuters Rosinquist To Work On Loot Hello Friends I am Ajay Ko Loot Boat Ignore Actually A That They Blue Bad Track Yudh Connection Question And But You Can Say A Prayer Half Hour Ko To And Subscribe To A Movie Hot Big Boss Basically Just Doing This Is In Any Video Mein How It Is Good To See So Par Were Not Done Anything Ka Durg Anil Pandey Subscribe Businessman 10200 Discovery And Toys For Beginners Pendant And Discovery Counter Switch On To Cigarette Or Face Modified Little But So Ifin Loot A River Takes This Ultimate's Quantity Pinpointed Had Happened Business What Is Means Is Well Wishes In Counter So Let's Wearable Date Of Birth Cases That One Is Be Able To See A Connection Between One Two So It Will Give Me To Value Fighting Value And 2008 Too Three Feet Is Two Wheelers Me To Continue That Bigg Boss Beam Already Come From To Your Dear Parents Be Already Updated Daily Life Discovery And Low For One Fruit Does Us Loud Updates From Here Services Ignore Hours Next Possibilities Pe Encounter What Is That Is Not Visited And Fix Child After Verses 113 Possible Is What Is The Tiger Game And Most 1210 The Best Way To Celebrate Between Sexual Orientation 033 For This Channel Subscribe Button That MP3 Solid Vikram The Self And Difficulties In Per So In Rape Cases Child Born In Affluence Obsessed With Most Difficult To Update Low End Discovery Basically Not Even Discovery Updated With The Proper Time To For Person Subscribe to the Page Subscribe Button This Video Channel Is Not Possible That Daily Been Started 2012 Notification Question And Dear Ones Will Remove That Vivo Not Face Any Difficulty Road This Pain Below What Is Show Which Here Lets Keep In Mind That Wisdom And We Have Se Dahej 20 Comes In Power Up Date Of Birth Bluetooth The Lokpal Bill And Discovery Of Side Is That A Loot Lo Loot What It Means Not Have E Come From 0.2 Means Not Have E Come From 0.2 Means Not Have E Come From 0.2 Dec Tax Lo Time In This Not This 102 Discovery Time Of A Bizarre Basicly Of the world tax co it belongs andar discovery time aur dil valid gunde ka bhi encounter sudesh is vvi update kar lo end airways call difficult children end subscribe shyam sewer tax start end drums dependable passes away counter hai fidjit is vansh get back from three layer gold To Update Lo Next Day Suryadev Singh's Whole Idea Of Soil Into Update Lo And Check Effective Meeting Battery Saving Tubelight 809 Is Updater Amazon Law Of Vehicles Loot Child With One Is My Love You So Loot English S It's Possible Andheron Se Connection Between Schezwan Entry And Will destroy and dental value of three looted by the britain time and discovery of co2 130 kind person high mod with ashok bajaj discover counter birds set a girl school girl discovery time and this claim circulation issues connection the only way setting take discovery on this route Counter Which Is Being Called From Here Now We Daughter Muscle Clear Shot That They In Bihar And Protective Withdrawal To Call Ward-13 Recorded From Fear Listen Volume Text To Dad To Call Ward-13 Recorded From Fear Listen Volume Text To Dad To Call Ward-13 Recorded From Fear Listen Volume Text To Dad Three Verses List The Only I Want A Slight Is President Granddaughter Is Dynasty Which Directly Parents Sotheby's Loot Updated Every Two Years Only Absolute Tube Skill Develop One Is The Child Children Illegal Extortion subscribe Video not Update And Only For Subscribe And Listen Bittu Light Condition To Find The Sting Operation 11 Key Discovery Of The Key All World Yes Bank Looted And A MP3 Photo Cemented News.in Loot Discover With The Discovery Time For Tax By All In This Case One Is Looted And Discover Lo Time Of Birthday 3 Behind Obscene In This Would Not Be Updated Ali Dargah 1431 People Not Be Updated With A Swan Collection But Only Be Updated And Share Subscribe Account Is So Effective Gretel Value For The Child This Entry President Time Period In This Question Is On That Noise Bhari Photo Who Its Users To Understand What Differentiates Quite Very Easy And Gooddo This Problem Without Any Damage Due Them Practices Talk You Should This Basic Education To Find Difficult Collection Is A White Vitamin C Can Fall In Love This B Time Taken To Above That Discovery Time Vitamins Just Simply Relative Time Taken So A Time Taken To Give Voice To Win the time taken for its child lo s always keep in delhi s well tell stories that particular point vs only updated through it is celebrated in the relief from pain to the child you should be asked later for this will be difficult connection quizzes Consider the case of one so let's also side one and five wishes subscribe valid for discovery 0 a grade to the last point connection between 108 updates low value with discovery time of 06 2011 is discovery time of two but low time for one Belcoms na dhan 0 notifications olive notifications ayurveda beech 120 but for this it is not possible because only time will update the discovery of two three and services why women from this is question and not needed to be a great day old result collector pimple t Hain So I Finally Doob Unwanted Can Write But Is Z10 That Thanks Android Pushpa Adi D Android Book V Sulabh's Chinese To Take Medical Connection On Tuesday To Tax Software 183 Law Medical Connection And Edited And Loot Kindly Active In The Reports Person Star 800 Dal United Aur Juliet Is Movie For Domestic Air Suryavanshi Tubelight Thursday Answer 10th To Phir Iss Ki A Hua Tha Loot Scooter Hai Main Video Start Ho Loot Jai Hind Party Run Loota Song On Ki Us Laddu Ram Seervi The Most Indian Hello Starting For Beer in tyson gay hua tha shak tweet soon koi romance hai loot space create band kawat in hua tha ki kisi wedding aur on kar a screen between two walls and stand problem hai selisus hai phone number date isse hotspot off karni 102 hu made tweet kahan Hai ko ek looti na dhoop ki vishnu white 12th loot koi hua a pig politician hai loot lo luta diye for street suite hai the police also very nice status connection sports size hai kisi video dekhna hai loot aur pink sun can see mein robbers ne European Central Office It is Nothing But Justice Modified 2 Years and Years of Maintaining Tourist Dynasty Discovery and Brothers Lok Discovery Sacrifice Time Tax for You Want to Be Taken Off But Lois Physically Giving Us No Alternative for Kids Pet and Be Absorbed Low Every Time They Have Never and displacement child and actively after the time taken for I want to beat so standard time middle class time table for his children child will stand attitude connection white shirt clear and please subscribe like my video and you have any comments please vote and comment diabetes patient Suvidha And If You Have Any Modifications Of Winning In This Attitude Want To Clear Please Utna Comment Thank You Loot
|
Critical Connections in a Network
|
divide-chocolate
|
There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers directly or indirectly through the network.
A _critical connection_ is a connection that, if removed, will make some servers unable to reach some other server.
Return all critical connections in the network in any order.
**Example 1:**
**Input:** n = 4, connections = \[\[0,1\],\[1,2\],\[2,0\],\[1,3\]\]
**Output:** \[\[1,3\]\]
**Explanation:** \[\[3,1\]\] is also accepted.
**Example 2:**
**Input:** n = 2, connections = \[\[0,1\]\]
**Output:** \[\[0,1\]\]
**Constraints:**
* `2 <= n <= 105`
* `n - 1 <= connections.length <= 105`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* There are no repeated connections.
|
After dividing the array into K+1 sub-arrays, you will pick the sub-array with the minimum sum. Divide the sub-array into K+1 sub-arrays such that the minimum sub-array sum is as maximum as possible. Use binary search with greedy check.
|
Array,Binary Search
|
Hard
|
410,1056
|
241 |
Shri Ram Doctor Saheb, it would be very good to ask a question to you, if not, I will whenever you understand how to do this, you should not understand it till the end of AB. Question is a question, my brother, if you understand this then there will be more happiness. New Recommend A Graph Open GPS settings Watched the playlist of questions Question very well How to define a question How to solve Now you will understand Okay How is the probability of India News How is a differential equation Some said roadways Okay Executive officer was like that we will do it today Okay This verse is that now do it well. It is a very good question. At that time I was able to understand the requested question but there is a little problem in the way in which it has been done, so this question is going to be made fine but Mr. Speaker, first of all the question arises that your question. Will it be okay that you are sending capsicum cancer yes that I will do how to do what will happen now that [ __ ] [ __ ] [ __ ] 02888 that right now with the help of this power to some different cancer is coming dust on the basis of pollution off track so I Update You had to shoot, that has been done now Question Muzaffar Jitendra Possible tab Where to do as much as you want This cut is possible That thank you brother These are as different as per different Tell us if something is happening to me This is the question and answer And here is anything from the kidney You can do it, okay, if you search for it, then interest has been added soon, I will keep it in this that there is no relation question in this, you are coming to the topic of finding the top number, this is the best and subscribe 225 about the Sangha, first of all, I thought that if I have any problem, then I should call 200 operators with that operator or keep it in the box that I am on, then let's go through the same process and then I tried but unfortunately without finding it Keep it clear, only the operator is *, so I clear, only the operator is *, so I clear, only the operator is *, so I will do it too, so did he get more points - If you like more points - If you like more points - If you like this point, do n't forget to subscribe to this point, hey, what's this, point is more to-do list than panties, manton. On that side fold 2008 I make this mistake yet subscribe Displacement 282 magh mein ok yes so but this you should try if you see the playlist of vacation usko do hai princess cut kiya hai woh choice and koi naath se hona Want not floral style but ₹ 1 Amazon Want not floral style but ₹ 1 Amazon Want not floral style but ₹ 1 Amazon with which you are fine, the most expensive on Android app, we will think what the admin is saying, will I do Aishwarya packet for the collected from, do it here or do it without, then you have one more important thing, I will open it on the clothes. If you can, then I have passed the interview. If you don't, then God forbid. Then I will have to make two points. If I do, then I can try. Swear on related questions. If you can think the way you want, then everyone can think in this way and gave a superhit. Now it's okay to think. Mukesh can do this typing under your control. You business ward no. 9 was not laying, just that you can think that soon things will come to a standstill and it will stop. Okay, this time it is okay but. No chilli powder PM must have seen developed that the dream tell them to PM is for I colonel and solve a small country and turn the feet west, in the same way how will all the big tests be handed over message vitamin C problem homework We are aware that we are dependent on agriculture only and the current industry will become prince. He said that you spoil it is better, I am very happy, the answer of every house, the answer of the house is the opposition, it has many styles according to it. Even on human health, a human being can go under-16, Even on human health, a human being can go under-16, Even on human health, a human being can go under-16, here he can fold 100 overs on 28th, so this is his right, I think this is not related to the glow of the skin, it is far away from this, the dosa falls in such a situation. To qualify for the World Cup of work and I have no work and if you tell me this Sakoon combination then Multipurpose School Protein Vitamin E stand on 29-7-13, the bus comes on PM, it comes Vitamin E stand on 29-7-13, the bus comes on PM, it comes Vitamin E stand on 29-7-13, the bus comes on PM, it comes soft, then it comes straight line and quarter or so, look, I don't know. How to make it fair, what should I do, now I will remove your patience, that's it, we should do it on ourselves, I just went here in a moment, PM Nov 28, I am suffering from breast cancer, that is the difference in all the Muslim colonies, ABC By the way, if you are a dear reader, then it means this possible university act commission from cash withdrawal, it can be called a comedy, there is a mission, it can be an option in earning, BTPC, you had to do this in between, whoever will give you so much America, the button of your cancer. I can also add flirting on even your cancer possible, just now gather in it, we baked chocolate mixture on it, want something from the scan, whether they, you used it as smooth as I worked - doing Jogiya Answer Attack - doing Jogiya Answer Attack - doing Jogiya Answer Attack Transferring in September This will happen so that Bhavai does not tell him many times, complaint will fall to the department, this is a girl, start it and it was necessary to get approval on the gas, if you have turtles inside you, but you have a reaction while sleeping, then you should think that just this has also worked and It will become the main thing that brother is a good best, this is also the reason for the operator not getting it is in the express, it means its speed with the latest drums, a special we are going to get, meaning on one hand, understand that whoever is interested will make transfer to Mega Mart. This question is necessary along with your house. Comments that indication of Chief Secretary and PM. If you are thinking then it is possible. Subscribe to this channel. Please subscribe to this channel. Subscribe to my channel. Where is the internet or mobile now? Can you see and observe? You will do distraction, my brother is Pintu, till then officer doctor will get down 250 things, I am at that point, yes, now this two have come, now registration will be done in this Yagya only, something will come in this is not the last update, has Pitt ever been an Indian President, this updater is not the one who has money. By selling the inspector's yagya, he made the hotel number 2 bus three times here and there, etc. Decrese the message, if you are an acting operator, then you will accept ₹ 2000. If you accept it, you will do it. There is ₹ 2000. If you accept it, you will do it. There is ₹ 2000. If you accept it, you will do it. There is no incident alum updater on the point. How come BMC is on this point? Shift hold. Call the airport by doing Updater into a Terrific hit the office one came effect Children's Academy Jaipur Edition Fragrant do less than 5 inches into Mere Bhai 3.5 Cup 2010 Career A Akshar 2010 for work 3.5 Cup 2010 Career A Akshar 2010 for work 3.5 Cup 2010 Career A Akshar 2010 for work to remind that host take him out and travel now Have moved ahead * If these two call on famous call on * If these two call on famous call on * If these two call on famous call on call and type for wife in travel side pattern this will stump out the ball that I will give this two cups of sugar will report inches return what will cover please warden's this And that thing, I am self-employed, I heard, my brother, is this from the organization self-employed, I heard, my brother, is this from the organization self-employed, I heard, my brother, is this from the organization or should I continue it now, your Ramesh's saffron, like I took out saffron, I took out all this NDA bed, set tow return came on top of it, what is the reduction from here - return came on top of it, what is the reduction from here - return came on top of it, what is the reduction from here - of 7th - 8th edition. Doing mint will go to commission with my brother of 7th - 8th edition. Doing mint will go to commission with my brother of 7th - 8th edition. Doing mint will go to commission with my brother in 2004, I maintained it successfully and definition of irrigation minister Android, this incident is my work, he moved ahead but compare - again to work, he moved ahead but compare - again to work, he moved ahead but compare - again to develop comfort and what initial point, now tell me, then we will go to this. But others are born who increase the steep waste yagya, then set this vacancy and the enterprises will fight on its shoulder. There are 10 teachers, what do you have to do - teachers, what do you have to do - teachers, what do you have to do - enemy tissue - enemy tissue - enemy tissue - 28th gift collided with Scorpio, against yagnik 10, how will it be then interest? Rate Minus Point Type Characters Interface Log In The City Don't do manner or meat of Yagya Subscribe Like You knew my end here You subscribe Adams will inaugurate this chapter Cancer Now if you match the answer then Mani Shankar Aiyar twice Showed Geeta Manishi Manas Patala tight, when it sticks comfortably, then you can adopt it at work, you have to worry about cancer, click on the clothes updater, it will work on the request, it will give effect, just do the best powder, traction qualification, yes, you need loot, castor, American word, kiss But if you check the explanation of the word, then you will be able to think better. Better trust. It is okay that I was not able to see 98100. I understood that I will cut from here, there is some compulsory military service. If the operator came to some understanding that human is anti-thaman at that point. Question that human is anti-thaman at that point. Question that human is anti-thaman at that point. Question operator has come, subscribe to this, definitely subscribe, if you have not subscribed till then please subscribe, please do that opposition, mother, Amazon, do simple things, after this report, that you understand the meaning, you do not understand the reason, you can subscribe, it has happened.
|
Different Ways to Add Parentheses
|
different-ways-to-add-parentheses
|
Given a string `expression` of numbers and operators, return _all possible results from computing all the different possible ways to group numbers and operators_. You may return the answer in **any order**.
The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed `104`.
**Example 1:**
**Input:** expression = "2-1-1 "
**Output:** \[0,2\]
**Explanation:**
((2-1)-1) = 0
(2-(1-1)) = 2
**Example 2:**
**Input:** expression = "2\*3-4\*5 "
**Output:** \[-34,-14,-10,-10,10\]
**Explanation:**
(2\*(3-(4\*5))) = -34
((2\*3)-(4\*5)) = -14
((2\*(3-4))\*5) = -10
(2\*((3-4)\*5)) = -10
(((2\*3)-4)\*5) = 10
**Constraints:**
* `1 <= expression.length <= 20`
* `expression` consists of digits and the operator `'+'`, `'-'`, and `'*'`.
* All the integer values in the input expression are in the range `[0, 99]`.
| null |
Math,String,Dynamic Programming,Recursion,Memoization
|
Medium
|
95,224,282,2147,2328
|
1,796 |
hello everyone so let's talk about second largest digit in the stream so you are given the alpha numeric string s and return the second largest numerical digits that appears in s or negative one if it doesn't exist so we only want number so uh what you actually need to do is you create a truth set three set and storing the integer and you traverse the string and later on you convert the string the character in the string to the integer then you just return the second largest so let's just start coding and you will see what happened so true set will be stored in the integer and i'm going to put a set and new tree set and that will be it and i'm going to traverse the status to array traverse the string so i'm going to say if c is c sorry this is greater equal put equal to 0 character 0 and c is less than equal to character 9 here and 9 and i'm going to add to the set but before we add we need to convert the uh we need to convert to integer and also when we add into c right since it's the ascii value we need to also subtract by 0 and that will be the solution and later on because presets is through the ascending order uh to those is stable by ascending order so we need to convert to descending order so that will give you the uh the second largest right because the set would will be initially the ascending order then convert to a descending order and then when we do the uh well when we pull the integer out from the set we need to check the size first if the size is less than equal to 1 which means we cannot pull twice we want to return so we need to pull once automatically and later on for the second one we need to just return so that would be the solution on how to solve it but if this if the size is less than equal to one then we just return negative one and that would be the solution and i do think this is tricky because you need to know the descending set and you need to cast the tree set to the stitching instead because the set that descending sale will be navigable set there is not a tree set you need to cast a tree set then you will be allowed to do that and let's talk about time and space for the time and space time you need to traverse every single character in a string so that would be all of n and you need to add every single character if all the characters in a string are integer then it's all of them and you just pull paul is definitely all the fun so that would be the solution and i think that would be the solution and good luck
|
Second Largest Digit in a String
|
correct-a-binary-tree
|
Given an alphanumeric string `s`, return _the **second largest** numerical digit that appears in_ `s`_, or_ `-1` _if it does not exist_.
An **alphanumeric** string is a string consisting of lowercase English letters and digits.
**Example 1:**
**Input:** s = "dfa12321afd "
**Output:** 2
**Explanation:** The digits that appear in s are \[1, 2, 3\]. The second largest digit is 2.
**Example 2:**
**Input:** s = "abc1111 "
**Output:** -1
**Explanation:** The digits that appear in s are \[1\]. There is no second largest digit.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters and/or digits.
|
If you traverse the tree from right to left, the invalid node will point to a node that has already been visited.
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
114,766
|
917 |
hey guys how's it going today I wanted to do another Leko problem I know we haven't done one in a while and I wanted to make sure that doing these legal problems is this kind of like training right as weight lifters they lift like heavy weights it's good for us to dive into these problems whether they be easy medium or hard it's just good to review them every now and then it'll keep you sharp anyways with that without further ado we're going to go and dive into problem called reverse on the letters now this one doesn't require any specific data structures or algorithms but it does kind of it will kind of require to think a little bit on how to do it so let's go ahead and read the problem so give it a string s return the reversed string where all characters that are not a letter stay in the same place and all letters reverse their positions so essentially alphabets lowercase and uppercase need to switch so how would you guys go about this pause the video think about it real quick when I see this problem I immediately think of a few things that I need a way to find if the letter that I'm looking at right now is an alphabet right lowercase or uppercase one of the easiest ways to do this in most programming languages is to use something called radix now regex is stands for regular expressions and it's essentially a pattern matching mechanism and JavaScript has native support for this so the first thing we should do is write kind of a separate utility function let's call it Conn's is valid string for example and I'm just doing an anonymous function here and with let's pass in a string and here we're going to write a simple reg X now reg X is kind of tricky to write if you're not really familiar with it I myself have to look it up quite frequently for complex redick's but generally use there's two ways to do it in JavaScript one you could do the new reg X of which is like us making a class the other shorthand way to do is signalling with these two slashes saying that this is or reg X and then you do a caret to say this is basically you're going to give it a pattern right so in here we're gonna do a through Z and they a through capital Z and basically this is saying this red X needs to start with one of these patterns so the two patterns that we gave it was a through Z all lowercase and a through Z all uppercase and then the next thing we could do is we have to end it with a dollar sign but if we do plus we just say one or more there's I believe star which is there's like exactly you could make it so that it's exact matching or but what we want is this string that we see need to be at least one of character and it shouldn't have anything else so this is the regex and then if the regex has a built-in and then if the regex has a built-in and then if the regex has a built-in function called test and then we just pass it the string and here we could just return it now that's the first part we know that we're gonna need this because we the thought is we're going to traverse essentially traverse this string and every time there is a valid string we're gonna swap it now one thing that you should think about here is how do you keep track of what values to swap right and the best way to do this is by having pointers now oftentimes these programming problems they'll deal with pointers and it's because pollinators can be kind of tricky if you're not careful with it and it's just one of those fundamental things being able to you know manipulate pointers and this problem is one of those problems that we'll use like have the use pointers heavily so what I mean by that is if you think about this problem let's take this input string right here I'll just put it right here I'll just put a comment here if you say hey like let's take like a starting index so let's just say let's start from zero so that would be a and then let's also start from n which would be like the string dot length nicer for example which would be zero right so if you have like a loop that checks one end to the other end and if they are a string in both cases and you swap them in place and then you continue doing that until you meet in the middle then you essentially have traversed through the entire string and looked at all of the strings that needed to be swapped so that's essentially what we're going to be doing here right here the only thing I'm gonna do to make my life a little bit easier is to make this raw string into an array so let's just say let string array equals s dot split and split it's just a utility function and here I'm just going to change the sistar arm I'm gonna do a while loop here and in here all I'm going to do is if start is less than and this has to be - about sorry so and this has to be - about sorry so and this has to be - about sorry so essentially what I'm saying is if the start as long as a start is less than the end then I have not crossed over meaning I'm still in still part of the traversal I'm still looking through all of the characters that I need to swap so that's the first check now in this check there's a few things that I need to do I'll just pseudocode it real quick here the first thing I need to do is if the current start character and its current and character or something like that is valid or valid then I need to essentially um swap and then increment slash decrements start and respectively that's one case the other case is if current start character for example press start character is not a valid string then I just skip over and this would be likewise for current and so essentially the idea is that what I have no way to know that both I basically have to only swap them if they're the same letters they in the current and then the N is both letters but if one of them is like a hyphen or some other character I just skip over it and because and then essentially it will catch up on the next wallet so let's go ahead and code this out let's go ahead and create a few variables here let's call it start letter which would be the CSTR R and then start and then here let's do end letter and then here we'll do n now the next thing we want to do is let's go ahead and evaluate whether the current letter that we're on for both start and end is a valid string so let's just say is start current start valeted it's kind of a long it's current start valid it's kind of a long name but long names are generally okay um let's see and then let's call our utility function is valid string right here and we're going to pass at the star level and we'll do the same for the end letter and then we'll call it his current and valid and letter I'm not really a big fan of these it's curved current start letter let's just say is a valid and then let's just say his be valid this is a little bit as 2's so I'm really not a fan of what I'm naming this let's just be kind of descriptive here as we'll just say start letter a dart letter a start letter ballad and they will say is n letter it's kind of longer but that's fine so the first that took forever to name those two variables but basically what I need to now do is check if both of these letters happen to be valid and letters then I need to swap them in place right so we'll do a simple is start letter valid and is end letter valid then we will go ahead and swap the two letters in place so R and then this would be start equals essentially and we luckily pull them out here so we could you know just do that as well string array and equals start letter so we've essentially swapped them in place now we have done the swap we have to make sure to increment and decrement to start accordingly start this equals one and one great now we have to take care of the cases where essentially they're not valid and we need to increment and decrement properly so if is start letter valid and then we just have to do the knot which is the opposite then we need to make sure to decrement the start and if not is and we need to also make sure decrement the end so that's essentially our loop and this should go through the entire length of the string it'll take half the time of linear time to go through this right because we're going through the length of the string divided by half because we're looking at two string learners at the same time and all I need to do here is assuming that this takes care of all of our little swapping in place we just have to return as TR are a joint so now this is a little bit like turning it this into an array is a little bit you know slower for performance but just doing just working with arrays is a little bit faster when I'm swapping things if not I would have to done like some kind of I would have had to don't like splice or like sub string like that's just like more cumbersome I just did this for simplicity so let's go ahead and run this see if I made any errors and dcba so it looks like it's the same output so let's go ahead and submit it and there you go it's I have successfully submitted it so yeah I hope you guys enjoyed this quick video on legal problems I'm trying to crank out these more and more because I really love doing legal problems it's just one of those things that it challenged me it challenges me to you know when you want to teach these kinds of things you really need to like understand the material that you're teaching and so it's a really good way for me to review some of like especially for medium and above problems it's a good way for me to review these things since I don't get to do like you know simple data structures and our them problems like every single day and I do run into problems here and there that requires me to traverse trees and stuff like that and you know but anyways so I hope you guys enjoyed this video and I'll see you guys on the next
|
Reverse Only Letters
|
boats-to-save-people
|
Given a string `s`, reverse the string according to the following rules:
* All the characters that are not English letters remain in the same position.
* All the English letters (lowercase or uppercase) should be reversed.
Return `s` _after reversing it_.
**Example 1:**
**Input:** s = "ab-cd"
**Output:** "dc-ba"
**Example 2:**
**Input:** s = "a-bC-dEf-ghIj"
**Output:** "j-Ih-gfE-dCba"
**Example 3:**
**Input:** s = "Test1ng-Leet=code-Q!"
**Output:** "Qedo1ct-eeLg=ntse-T!"
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of characters with ASCII values in the range `[33, 122]`.
* `s` does not contain `'\ "'` or `'\\'`.
| null |
Array,Two Pointers,Greedy,Sorting
|
Medium
| null |
1,823 |
all right let's talk about the final winner of the circuitry game so basically this is supposed to be easy so you have friend and then use uh just for a run and then there are fun prime and then you do the clockwise order so you have an integer k so k represent um the number the person you need to remove from the group for each iteration so in this case so this is supposed to be easy so i'm just quickly just uh telling you the sort of solution so you have a queue so i'm gonna add one two three four five into the queue so think about it like if you add uh if you remove the first integer and add the integer back to the beginning this is the circular right like think about it like five the next character is one right so this is pretty much a circular solution and then here's this so i have a length of a k for every single time you need to iterate right so uh i will remove the one and then i will add one back to the q and then at the end when k equal to one i need to remove like two so which one let me change another column so i need to remove it remove the two so uh so the circular is become like three two three four five one right and then i'll do it again uh remove the three add the three back and this is k it's okay i need to remove four and five one three and so on all right this is too much talking so i need a cube and i need to pass the integer q equal to new like this but i equal to one higher let's single the n i plus q dot alpha at i right at every single integral into the q and then i need to say okay well q dot size is actually really why i need i can traverse because i need to return the last person which is q dot p now let's think about this uh for every single time i need to reuse my k so i need to have a temporary variable to store my k and then well remove is actually greater than one i would just have to keep adding and remove at the same time and at the end the last one has to be removed so it's gonna be without remove all right so here's it so i'm gonna just adding and remove at the same time so cue the offer and q dot remove at the same time and then i will just decrement my remove and this is pretty much a solution so all right here we go so let's talk about timing space this is going to be space right so it's going to be all of n every single integer right and this is going to be time of n and this is what all of m times all of k so n times k for the time and the remove over p this is constant right well we are using linked list right we are not actually shift entire array uh right by one or left by one right we actually know there's a pointer point at the next uh variable right and this is a solution and i'll see you next time
|
Find the Winner of the Circular Game
|
determine-if-string-halves-are-alike
|
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise from the `nth` friend brings you to the `1st` friend.
The rules of the game are as follows:
1. **Start** at the `1st` friend.
2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once.
3. The last friend you counted leaves the circle and loses the game.
4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat.
5. Else, the last friend in the circle wins the game.
Given the number of friends, `n`, and an integer `k`, return _the winner of the game_.
**Example 1:**
**Input:** n = 5, k = 2
**Output:** 3
**Explanation:** Here are the steps of the game:
1) Start at friend 1.
2) Count 2 friends clockwise, which are friends 1 and 2.
3) Friend 2 leaves the circle. Next start is friend 3.
4) Count 2 friends clockwise, which are friends 3 and 4.
5) Friend 4 leaves the circle. Next start is friend 5.
6) Count 2 friends clockwise, which are friends 5 and 1.
7) Friend 1 leaves the circle. Next start is friend 3.
8) Count 2 friends clockwise, which are friends 3 and 5.
9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.
**Example 2:**
**Input:** n = 6, k = 5
**Output:** 1
**Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
**Constraints:**
* `1 <= k <= n <= 500`
**Follow up:**
Could you solve this problem in linear time with constant space?
|
Create a function that checks if a character is a vowel, either uppercase or lowercase.
|
String,Counting
|
Easy
| null |
271 |
Hello, my name is Suren and this is a solution with parsing lit-code task number 271 and parsing lit-code task number 271 and parsing lit-code task number 271 and Cold Strings, you may have noticed Cold and Cold Strings, you may have noticed that there is a different task number here, all because I am on the lindcode website and not leadcode because this task is closed on lit-code leadcode because this task is closed on lit-code leadcode because this task is closed on lit-code and Now this task cannot be paid for, so I will use the Chinese site linkout which provides the same task, but for free you can see the essence of this task and here you need to program an algorithm that will allow you to make one line from a list of strings and then from this line back a list of strings for example to you the input was provided by several lines in the list, you turned them into some kind of line, for example this one, and after that you are given the same line as input to another method and you return from here a list the same as the original one from which you made the encoded line. Pay attention to the solution here Solution class in which there are two methods and decout in the first method you need to get a list of strings and return one line to the second method in decout the same line will be passed and it needs to be turned back into a list of strings so that it is the same as the one that was originally submitted in encoat Let's draw and find a solution in this example, a list of four lines is fed to the input, these four lines turn into one line somewhere under the hood. Then the same line is fed to the input to decout and exactly the same list of lines is returned as was originally submitted on encout and here you can see that all the words are separated by a colon with a semicolon, this is a fairly simple solution when you can then divide this entire line using this separator. But in the next example you can see What happens if you enter a colon here, the value that is used as a separator then in this case, it is encoded using another colon, that is, shielding is used here, for example, the input is what is used in your separator And you need to shield This value using this Well, this is a common pattern for escaping This is a good way that allows you to avoid errors However, there is another algorithm that allows you not even to check whether this is the symbol that you use or another that was originally in the word, you can consider an example when you count the number of characters in a word, here there is fu and you can indicate that this is 3 and SP is 4 and then write all these words in one line, that is, there will be three fu and 4 spm and in this case you will have one line in which there is a number that tells you how many more characters you need to take and another number how many more characters you need to take, and so on you can use these numbers to separate words from each other, but what if in some word you have numbers and for example these numbers can be at the beginning? After all, no one guarantees that there are no numbers here, it turns out Here 7 is also a word and if you write it simply 4 and 7 in this line, then here there will be 47 4-7 spam is already leading us astray 4-7 spam is already leading us astray 4-7 spam is already leading us astray because there are not 47 characters here, there are still 4 characters, it turns out you need to somehow tell yourself that 7 refers specifically to the word. Therefore, I suggest using this separator here it can be anything, the same dollar symbol, just a Pipe minus or an underscore or even a space, it doesn’t matter, the underscore or even a space, it doesn’t matter, the underscore or even a space, it doesn’t matter, the main thing is to indicate the same separator after you have indicated How many characters you are encoding, for example for Fu it will be three and a dash and then Fu for spam it will be 5 then a dash and 7 and it turns out that when decoding a string you go from left to right and look at this symbol, it refers to the number of characters in the word that is encoded here further. You come across a separator and once you encounter a separator, then this is how many characters you need to take in the next word you take here Three symbols and everything else relates to the following words, you see here a new number, the same five, and go to the next section, here again you encounter a separator and you understand that this number relates to how many letters you need to take in the next word and here there will be seven - that’s five symbols here there will be seven - that’s five symbols here there will be seven - that’s five symbols that are needed here Take further there are no elements Therefore, decoding is completed if we could store the state, then everything would be much simpler, we could write fu and 7 spm in one line and then simply divide by quantity, that is, write down that we have a list of used 3 and 5 and take here first Three characters then 5 characters but since we must store this without state, that is, all the information must be in the line that you encoded, then this option is completely unsuitable. But what if some word starts with a delimiter For example, if Pipe is selected as a separator, ASP begins with pype or in spam there is a Pipe in the middle, then what to do here is actually nothing bad and this algorithm does not break the presence of a separator in the word itself, why look, there are ugh here there are 3 characters, so there will be three here and then pipe as divided and this word is already encoded we go to the next one in the next word there will be 6 letters and each letter is some kind of symbol But it doesn’t matter at all which one symbol But it doesn’t matter at all which one symbol But it doesn’t matter at all which one because here it will be indicated first 6 then Pipe then there will be a pipe from the word and another Pipe in the word Then when you go to decode it, you will count that 3 and this is the character that is the separator, this is how many further elements you need to take. So you have separated one word and then you count the following characters up to the first separator, not up to some specific one, up to 1, once you have gone through all the characters and reached to the New separator, then here you take everything that you found before this is 6 and take the next six characters one two three 4 5 6 all of you found this word here and it doesn’t 6 all of you found this word here and it doesn’t 6 all of you found this word here and it doesn’t matter that there is a separator inside this word or there may be some numbers you have reached the first separator and this information is enough for you to decode the next word, proceed to writing the code, since there is a restriction on this site that cannot be fulfilled without registering. And registration here is only possible from Chinese numbers. This does not always work, then I will move on to writing the code in jooper laptop, here I will write code and then we will check it First, we need to encode the line, here the input is a list of strings and we need to turn them into one line, make a new line string which will be the result for now this is an empty line, you can immediately return this line by doing Return string Now you need from this lines, make an encoded string based on all the strings that were in Strings, for this you need to go through all the elements and do here for example, Word in Strings and for each word, count the number of elements and also add a separator, you can immediately do string plus equals and here a new string here will be Count then here will be the separator dilemmeter and here will be the word itself that needs to be encoded Word after that make a form to insert here all the necessary values for the number of necessary values for the number of necessary values for the number of elements it will be easy count is equal to ln from this word and then you need to specify the delimit delimmeter is the separator that should be not a number so as not to confuse it with the number of elements, and there can be anything here, for example a pipe or a space or some other value, the same exclamation mark, also this delimiter can be placed in a separate variable just to be addressed through a constant and not through a Literal Specify here for example, the same Pipe and Use this variable de limiter to pass it to the line, the word itself comes last and make simply Word equals Word So you wrote the encout method to check this method. You can execute the code to create a class and make Solution equal to Solution and here we will use the incout method to encode all the words into a line, declare the encoded variable equal to Solution and make a dot encout In order to encode some list, for example Here ugh then you can add Pipe here add sing and another pipe X and here add to for example, a bar and at the end let there be a pipe in order to check what the results will be here, do an encoded print and see what happens here is an encoded line where the number is how many characters are in the word and then a separator and here some separators are stuck together but it’s not scary but it’s not scary but it’s not scary it’s not will interfere with decoding the string, it’s not will interfere with decoding the string, it’s not will interfere with decoding the string, proceed to writing a decoding algorithm, here you will need the same dilemeter, so I will copy this variable in the Code method and you need to declare new variables where you will add the results, that is, you need to turn the string into a list of strings, do result here and it will be simple the list that will need to be returned is done Return result in order to immediately return this result, here you also need to analyze some variable that will count how many characters you have already passed and I will call it Last position That is, this variable will store the position of the last character that we processed and here you will also need to compare the length with the original string, so I will write here string LAN equals LAN from string so that there is a separate variable that stores the length of this string, then you need to use the Wild loop, we don’t know in advance how many Wild loop, we don’t know in advance how many Wild loop, we don’t know in advance how many steps there will be here, but we know for sure that a for loop won’t work here because loop won’t work here because loop won’t work here because we don’t need to just iterate over everything, we don’t need to just iterate over everything, we don’t need to just iterate over everything, we need to iterate through them in steps, so Vile and While our last symbol Last Chartpos is less than the length of this string Land, then we will look for the following values. The first step in decoding is to find the length of this lines, that is, to get to the separator, it turns out that you need to count the number of elements before you met the separator, so make another while loop here and in this while loop you need to look whether the next element is a separator, how to look for the next element, you need to create a new variable here, for example, position then is this will be the position of the number and we will look for Where does the number end here? Well, the position will start from the place where we finished in the previous iteration, that is, at the first iteration it will be 0 because we are starting from the very beginning and then it will be, for example, some kind of then the next position where you need to pull out this number immediately after the previous decoded word. So you set that the current position will be equal to the last position of the word. It turns out in this cycle you need to take the value from string here Specify Well pos and check that it is not equal to the delimmeter, that is, here is the value of the next character is not equal to the separator and do here well pos plus is equal to 1 in order to increase it by one and advance to the next value for example in the case when the length Here is three, the triple three is not equal to the separator will first be read and then will be increased by one and the next character is already equal divide it Therefore, this loop will be completed and from this you can get the length of the word because you know that from 0 to one will be This is the value and from it you need to get a number do here Word LAN That is, this will be the length of the word equal to integer that is, Convert to a number then what will be from 0 to one slices in pything allows you to take from some number to some and from will be inclusive, that is, from 0 will be here string from Last char position will be taken in this line And up to what number will not be inclusive like this as the position of the separator is one, then you will take all the elements up to one It turns out that you will take only three here, do here, well, position and you have pulled out the length of this word, this information is enough to pull out the word and this can be done in one line, but I will write it on several lines Because it will be like this It’s easier to understand, do will be like this It’s easier to understand, do will be like this It’s easier to understand, do here to get the index Where the word wordstart begins and wordstart will not be at num pos at num post is the separator wordstart will be one character further, that is, it’s well pos one character further, that is, it’s well pos one character further, that is, it’s well pos plus 1 and it turns out that the word begins with index 2. It remains to get the index where it ends the word Word and is equal and here there will be wordstart plus Word Land that is, you need to add the length of the word to the beginning of this word to get where the end of this word will be, see here wordstart for example it will be two and wordland is 3 that is, the length of the word will be three and it turns out that the beginning is on two and the end On five if you count the indices here 2 3 4 5 just not inclusive That is, these are the indices that allow you to take a slice and get the desired word pull out This word make Word equal to Strings and do here Word Start colon Word and We all pulled out the word and you need to fill in this result make here the result dot opent add to the Word list and after that you need to indicate from which position to continue. Otherwise, if you do not change this value, then the loop will be endless and the program will fall into the Last charposs value you need to write down the position from which to continue searching here the position is just five, if you look at what’s here at 5, then 5 is the you look at what’s here at 5, then 5 is the you look at what’s here at 5, then 5 is the beginning of the next number. It’s beginning of the next number. It’s beginning of the next number. It’s enough to specify Word and then the Last Chart position will look exactly at the end of this word and the beginning of the next one. The next one starts with 10. It turns out Here in the cycle Will first one unit then another one is added because there are two symbols here and how If you come across a delimiter on the dilemeter then the value here will already be equal to the delimeter then you will exit this loop and there will already be two symbols here, first there will be one then 0 it turns into 10 and you take the next 10 characters after the delimmeter and it will be this word spem and EX with two separators inside, you will go through this cycle until your Last charpose is at the very end, that is, as soon as you reach the end of the last word, then this cycle is already again will be interrupted and you can return the result here, you will return a list of words that you decoded there, execute this block of code again to declare the class again And after that you can re-do the after that you can re-do the after that you can re-do the decout and encout, make the Solution dot decout here and specify encoded here in order to decode back make your line here a decoder equals and add a decoder to the print and execute this code here I got an error because the word string does not exist this variable should be called simply string let’s run the code again and the same string let’s run the code again and the same string let’s run the code again and the same code can be executed again now we managed to decode this line into a reverse list from the same words that were originally Here Fu Here is spam ex with two separators Here is a bar with a separator at the end In fact, the problem is solved, but it’s worth throwing some solved, but it’s worth throwing some solved, but it’s worth throwing some tests here in case I haven’t considered tests here in case I haven’t considered tests here in case I haven’t considered some more cases, for example Here you can use the faker library, this is a third-party library that allows you third-party library that allows you third-party library that allows you to generate various words and here you can also generate random sequences of characters I will use a random library and go in a loop for a certain number of repetitions and will generate a certain number of words from 20 to 50 here I will make lists of these words passing them to the faker wordscount that is, wordscout is fake and there will be some kind of list of words, then I will create a new instance of Solution here to encode this line, I will save the encoded value here And after that I will create a new instance of a new instance I create so that the state is not stored between instances Suddenly, somewhere inside, the position of each element is saved that will then need to be decoded. And after that I decode it back, that is, the decoder here will already be a list of words that should look the same as the original words, you can verify this by specifying here the assert decode equals Words and if they are equal, then everything is fine for here At least you can see something here Print Okay and here it will be okay because all these words were successfully encoded And decoded this part, of course, does not relate to the solution, it’s just checking itself, the whole it’s just checking itself, the whole it’s just checking itself, the whole solution is concluded in this class and in order to see traditional random numbers I will use the brand module and random will generate some random number from 0 to one, multiply by 100 to get percentages and I see some random numbers here I can be glad that I solved this problem correctly I liked it is there an explanation? If yes, write in the comments; if no, write in the comments; if no, write in the comments; if no, write why and like to support me
|
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
|
239 |
hey everyone welcome back to the channel i hope you guys are doing extremely well so today we will be solving the problem sliding window maximum from the sd sheet so what does the problem state the problem basically states you'll be given an integer array okay and you'll be given a size k equal to 3 and you need to figure out what is the maximum in all the sub arrays of size 3 now for an example if i consider the first sub array of size 3 that is this one now in this which is the maximum 3 so you take three if you consider the next sub array that is this over here which is the maximum again three so you take three in the next sub array which is this one which is the maximum definitely five so you take five so what you have to do is in every sub array of size 3 you need to print the maximums in it that is what the problem states now this question comes up in an interview what is the first solution that you are going to give to the interviewer it should be naive solution what we are going to say is since you know first sub-array starts since you know first sub-array starts since you know first sub-array starts from the zeroth index the second sub array starts from the first index the third sub array starts from the second index and so on the last sub-array of size and so on the last sub-array of size and so on the last sub-array of size three i'm talking about size three starts from the fifth index so what if from zero to two i can traverse what if i can traverse from one to three what if i can traverse from two to four what if i can traverse from three to five from four to six five to seven if i can traverse through and all these sub arrays of size three and in every sub array if i can figure out the maximum i think this can be a possible starting solution that you can give to the interviewer so how will the code structure look like now can i say i will easily travels from 0 to 5 indeed and i know the first sub array is from 0 to 2 so i can simply traverse from that i to i plus k minus 1 why because 0 plus k is the size 3 so k minus 1 0 to 2 is the first sub array the next sub array is from 1 to 3 while the next sub array is from 2 to 4 and similarly i can go on so if i write this nested loop i can definitely find out the maximum of every window of size 3 and what will be the complexity i can say this loop is near about n like near about and the inner loop is around k times so it's a nested loop of n into k which is almost an quadratic solution so obviously the interviewer will not be happy with this and he'll ask you to optimize this solution before moving on to the next part of the video let me tell you about coding ninjas now coding ninjas is one of the largest coding education company and they have taught around 50k plus students now they offer you courses in programming in different languages like c plus java python they also have courses for machine learning android development data science and web dev the content quality is exceptional as it is made by experts from iit stanford amazon and facebook they do offer you one is to one doubt resolving support and the average doubt solving time that they take is literally the best in the market now since the courses are really well structured and so many have benefited from it i guess you should give it a try and if you feel so do use the link in the description in order to optimize the brute force that is the big off and into k solution to a much more optimal solution we're going to use the concept that we used in nge that is the next greater element if you remember we use the concept of storing elements in an increasing fashion so over here we are going to store elements in a decreasing fashion and in order to do so we will be requiring something which is known as dq now what is the dq is nothing but a doubly linked list that is being implemented at the back side now what is a doubly linked list does allow you to push at front right it will allow you to push at front it will always allow you to pop front that is you can take out anything from the front also it will allow you to push back also it will allow you to pop back so this is what a dq is it allows use operations on both these sites now in order to solve this problem what you'll do is it'll start iterating okay so you'll start iterating at the zeroth index and what is the value of the zeroth index that's one now does your dq have anything so i see that our dq doesn't have anything so in order to maintain the decreasing order you can simply push back this value zero so i'll just push back this value zero which is the index okay now let's move to the next which is the index one so since you have pushed back the value zero that's nothing but the value one correct that's nothing but the value one now the moment you come to the index one you have a value three logically think if you have an array element which is three right and you're looking for the sub array maximum in a window of size three so if you've got some minus three just realize if you've got someone as three well storing this one matter while storing this one matter definitely not so what you'll do is you'll start checking from the back which is the back element zeroth index that's one so i see that one is lesser than three yes i see that one is lesser than three so i do not require one anymore because i've got three which can be my answer now so what i'll do is i will take this out yes i'll take this out and after this the dq is empty so i'll take this index and i'll plug it to the back of the dq right after that i'll move to the second index perfect so since i've moved to the second index what value do i have a minus one remember your dq has this first index which is nothing but the value three now as of now i have a minus one now this minus one if i plug in into my dq it will maintain a decreasing order and i know if i get a minus 1 it's not the maximum because 3 will be my maximum so no need to remove anything rather push this index to the back of your dq pushed now here comes the main point can i say 2 is the last index of the first sub array of size 3 yes i can so what i'll do is since i'm storing in a decreasing order can i say if i look from the front whatever value is at the front that is the first index the value is three can i say for this particular sub array the maximum i'll easily get at three i'll easily get it as three indeed right after that i'll start moving to the next index so the moment i move to the next index what's the value that's minus 3 correct so will you remove anything from the dq so just imagine if you plug in a minus three will the non d will the decreasing fashion be maintained indeed because three is greater than minus one is greater than minus three so the decreasing is maintained so what you'll do is you'll take this third index and you'll push back to the dq right so since you've pushed it back to the dq now the next step is since you are the third index you know you have one more sub array of size 3 which is ending at the third index so i need a maximum for that since i'm storing in a decreasing order i'll look from the front and i'll see the index one so what is at the index 1 3 so i can say 3 is my maximum for the sub array of size 3 now perfect now i will move to this fourth index this is the point you need to understand something so if you move to this index 4 can i say i'm just concerned about this window of size 3 correct so what is over here that's the index one shall i store that in my dq and the answer to that is no because my boundary is only this much and i'm storing an index which is outside my boundary so if at any moment i store something outside of the boundary i'll check from push of front i'll check from front i will check from front and if i find anything out of boundary i'll simply pop it up so i pop that front right after that since i popped it now i am at an element five i'm at an element five now tell me if you have got five does minus one minus three matter definitely not they don't matter to you anymore so what you will do is at first you remove the smallest so what is third index that's a minus three is that smaller than five yes so you'll remove it so you'll check from the back next smallest is the second index that's minus one is minus one smaller than five indeed so i can also find this smaller so i'll remove it so once you have removed everything that is smaller than five right so once you've removed everything that is smaller than five right just push in this index four so you've pushed in this index four and since you've removed these guys again the new order will start from five now as of now you are currently at this so this is your sub array of size three now right and if you look from the front the index is four and that is corresponding to a value five so this will become your maximum of the new size 3 sliding window perfect that's time to move to the fifth index again what is that the fifth index three so if i talk about the new window can i say this is my new window do you have anything that is out of boundary in your dq no we do not have anything that is out of boundary so what we will do is yes what we will do is we will simply take three and see is there anything lesser than three no there is nothing lesser than three because if you have got three all the lesser elements will no more matter to you but since there are nothing lesser than three i'll just insert it to the dq so i'll insert it to my dq now currently i'm standing at five now i know this is my sub array that i'm concerned about so can i say if i look from the front the index 4 is having a value 5 which will definitely become my maximum of this sub array of size 3 perfect it's time to move to the sky right at the moment i move to this guy this corresponds to this the index 4 to 6 do you have anything in the dq that is out of boundary no we do not have but we have elements that are lesser than six so first element that is lesser than six is three so just take it off so you have taken out of make sure you check from back right because it's a decreasing order next check five so you'll take this off taken off correct by that this is just for representation so you have taken everything that is lesser than six because they won't matter because six is greater that you've got so anything lesser than six will no more matter now so you have removed that now take the index and plug it into your dq correct now it's time to find the maximum of this sub array so if you check out from the front it's the index six itself which is corresponding to a value six so now your dq has the index six which corresponds to a value six perfect it's time to come to the index seven at the moment you come to this index seven you look across this is your boundary correct does your dq have anything which is before the index five no it doesn't have so it's time to remove anything that is lesser than seven so this guy is lesser than seven so i'll remove it correct now once it is removed take this index seven and plug it in so you have done that correct now it's time to check from the front which is the index so you have a seven which corresponds to a value seven so this seven becomes your maximum of this last sub array so once you've done this the iteration will be over and it'll move ahead so once you move ahead can i say all the answers that you got will be the maximum for all the sliding windows of size 3 indeed that will be so let's discuss the intuition behind storing the decreasing order is very simple because at any moment if you reach any index a of i or any element a of i can i say anything lesser than equal to that any element lesser than equal to that appeared before can no more be your maximum because you have got someone which is greater than that which is greater than equal to that so this guy will be my new maximum so anything lesser than that has to be removed and that is why i've stored in a decreasing fashion so that i can remove i can go on removing from the back so that is the entire intuition that i am following so if i ask you what will be the time complexity will be nothing but big o of n plus b go of n which is near about b go of n i'll ask why big o of n plus b often because see you are doing big o of n iterations that is a iterating for every index now tell me when you're removing elements because the moment you reach a of i the first thing that you're removing is all the out of bound index perfect you're always removing all the out of bound basically if your sub array is sum like this you're removing anything that was before this four correct so out of bound you're removing and also you're removing anything that is lesser than equal to a of i because they no more matter now so can you tell me in total when you move from here to here how many elements will you remove in total you'll be like that's n elements because at max throughout the iteration repeat i repeat throughout the iteration you will be removing probably for the first time you remove two elements next time you'll remove one element so in total you end up removing n elements because in an array at max there are n elements so throughout the iteration you'll remove n elements so that's why the complexity is n plus and amortized right and what is the space complexity that you'll be using definitely b go of k if you remember since you are throwing out all the out of bound indexes so at max the dq will only store the size of the sliding window that is key at max it will store k elements so the external space that you're using is b go of k and this is the most optimal solution that you can get for this problem now it's time to discuss the c plus as well as the java solution to this problem so if you check out the c plus solution you're given the nums array correct as well as here given the size k so just quickly you'll declare the dq again you can implement the doubly linked list but yeah you can use the dq stl you can also declare the vector now what we initially did was we i traded through from 0 to nums dot size if you remember we started from zero and we kept on iterating till seven so that is what we have done now the first thing this is nothing but all the out of bound will be removed remember this so you just need to check if your dq is empty correct you have checked if your dq is empty and from this front if you remember your dq or something like this from this front you check the front element is that equivalent to i minus k why so why are you checking just y minus k imagine you're standing at i so this is your sub error right so the length is nothing but k so this guy will be the out of bound guy that will be in dq so i minus k is this element so you just check if this element is i minus k if that is you just say hey can you just go out that is pop front once you have done that what you will check is again you will keep on iterating till the dq is not empty and it'll make sure that whatever is at the back yes whatever is because you're storing in the decreasing fashion so you check the first element then the next element and whatever is smaller again you can just keep it smaller than equal to that is still okay so you have to just remove all these smaller than or smaller than equal to elements both will work so remove all of them so please make sure you remove all of them so this will make sure it removes all elements that are smaller than your a of i or smaller than equal to once you have done that the current index can be taken into your dq and once you have done this again you know that you start taking your sub array maximums in our example we started taking from the second index because this was the first this was the last index of the first sub array so just make sure if k minus 1 because k was 3 so the first index was 2 if you remember for k equal to d the first index where you started taking the maximum was this so if it is greater than k minus 1 you simply take whatever is at the front and you say this is my maximum and you store it in your answer and at the end of the day you can return that answer then the java solution you can see that you're given an array as well as you're given the sliding window size so we compute the length of the array we declare an r which stores all our maximums and you know the number of sub arrays will always be n minus k plus 1 very simple and now what we do is we store a right index basically what we have done is you have created the r array and you kept it ri so that you can easily store answers nothing special right after that you declare a dq once you've done that you remember you iterate it from the index 0 1 till the index 7 and you use the pointer so that is what you have declared i equal to 0 till a dot length now what you are doing is at the first make sure you remove all out of index guys out of bound so if this was your array and you were standing at the index i so you know this is the sub array which you're considering and the length is k so anything beyond this that is i minus k right this will be i minus k so if your peak from the back that is equivalent to i minus k correct if your peak that is the front if that is equivalent to i minus k so it's an out of bound index whichever is at the front so just make sure you remove it right so you have removed it and also make sure you check q is non-empty make sure you check q is non-empty make sure you check q is non-empty because it might happen the q is empty and you're doing a peak so it'll throw a runtime error right after that you have to remove smaller elements so just make sure the queue is non-empty queue is non-empty queue is non-empty and write from the back check if that element is lesser than again lesser than equal to can be used that is okay and you can also remove anything so this removes any element that is lesser than equal to a of i equal to can be removed or you can write it that is your wish so i make sure they move all of them once i've removed all of them i just make sure whatever is at the current index i just take it and push it into the dq once i've done this so if you remember our first maximum that we took was from index 2 because this was the first sub array and k was 3 so the sub arrays that we start as is from two three four so can i say any i that is greater than k minus one k was three and we started taking from two so i whenever greater than k minus one is when we start taking and we have kept an ri initially that's zero so we just do r of r i plus and we take whatever is at the front because that is the maximum element so this is how a big o of n plus n which is near about n solution will look like in java so guys i hope you have understood the entire explanation entire intuition the c plus as well as the java code just in case you did please make sure you like this video and if you're new to our channel do consider subscribing with this let's wrap up this video bye take care whenever your heart is
|
Sliding Window Maximum
|
sliding-window-maximum
|
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.
Return _the max sliding window_.
**Example 1:**
**Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3
**Output:** \[3,3,5,5,6,7\]
**Explanation:**
Window position Max
--------------- -----
\[1 3 -1\] -3 5 3 6 7 **3**
1 \[3 -1 -3\] 5 3 6 7 **3**
1 3 \[-1 -3 5\] 3 6 7 ** 5**
1 3 -1 \[-3 5 3\] 6 7 **5**
1 3 -1 -3 \[5 3 6\] 7 **6**
1 3 -1 -3 5 \[3 6 7\] **7**
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `1 <= k <= nums.length`
|
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
|
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Hard
|
76,155,159,265,1814
|
1,041 |
welcome back guys today we are going to solve it problem 1041 robot bounded in circle so on an infinite plane a robot initially stands at location 0 and faces north the robot can receive one of the three instructions g is go straight one unit l means turn 90 degrees to the left and r means turn 90 degrees to the right the robot performs the instructions given in the order and repeats them forever so which means that it will just loop into the instructions and it will keep performing the instruction instructions again and again so return true if it if and only if there exists a circle in the plane such that the robot never leaves the circle uh what this means is if the robot is standing from zero location then it will perform some the instructions in the set and it again reaches that 0 coordinate right and again it starts performing so basically it's kind of a forming a circle when it is performing those instructions so these are some of the examples that are given to us here so let's just take these examples over here and we will discuss how we can you know solve this problem so uh as the best like easiest way to solve this problem is just kind of simulating that robot is in the plane uh with x and y plane and it is standing at the like a 0 location right so this location is 0 which is the x y plane and what we will be simulating is we will simulate the instructions and we want to check if it is reaching back to the 0 location again after performing those instructions so let's just look at this problem you know like gglg these are the instructions given to us so the robot is facing north right so robot face is on the north side in the beginning this is the north side right so it starts from the zero coordinate and it goes one distance here so it reaches here so after one g right and after second g again it will go here and it reaches here so this is second g right because two distances it will go then after that it will execute ll means it will turn its face to 90 degree left basically so it's from north it will go to west and again l means again l right then it will from west its face will go to south right because now it will again move 90 degrees left so again it will start moving into now the south direction and it will go g and g means two distance so again it starts moving like here and from here again one distance and two distance here right so again it means that a robot is again reaching back to the distance like the coordinate zero where it started so basically as you can see the path is like this right it goes here and again it comes back here so it is kind of a forming circle so that's why we have to return true here right so we will just return true it is forming a circle because it is coming back to where it started and it will just start execute these instructions in cycle so it will again like uh it will like do this kind of thing like it will go here and again come back here right so it's cycle so now uh again another example it's given is a gl so again the robot is standing here and it will zero right we know right this is a zero this is x y location so now it will go 0 so it will go now north side 1 because of this g so now it reached here and it is executing l means it is changing its face from north toward west so now its face is toward west so it will again do gl g right so it will go one distance toward west so this is west so again it will perform gl right because it is in loop so means it will uh reached here and it will again perform l means from west it's facing now south right south so it will again start going south and it will go one distance here now and it will reach here and it will again now from south it will start ll means south l is basically east so it's facing east so it will again go one distance here and as you can see it reached where it started right it again reached the coordinate 0 where it started so basically as you can see this is a kind of a circle right that robot is basically bound with a circle so it is starting and eating coming back to the same point again starting again coming back to the same point as it is performing the dial like this instructions in a loop right so this is the case you know and the other example is when is the example when it will not reach to the when it is not bound to the circle right so let's take one other example so now there is an example where we have just g right g and g basically so g in infinite loop so it will start from here it will go here it will reach here now again it will it's facing north so again after g it will go here so again at this point it is facing north so it will keep going in north direction right like this but it will never be able to come back where it started from so in that case we have to return false so that's what we are exp we will be doing so uh so this is a general approach of you know how the problem we have to solve so now uh how we will be solving this problem in java so we will be using first we have defined a class called as location so location will uh capture the x and y coordinate of the current position of the robot and you know like it has this just one constructor is there and this is our actual method where we have first we have created one location map so location map will be like if you are going uh in the north location and if you are executing g right in the north location then we will be adding like 0 and 1 so we will add 0 to x and 1 to y basically for example this is our plane right so if robot is here and if so now it's facing north right so it's facing north so when g is coming then we from this zero we will on one g right g is the instruction so we will reach here so we what we will do is we will add 0 to the x and 1 to the y right because that's what we want to do so that's what we are doing here we are adding 0 to the x 1 to the y now if we are going south so now let's say we are here we are at 0 1 and we are going south right so south means we will add 0 to x coordinate and we will subtract 1 so that's what we are doing right 0 to x coordinate and we will subtract 1 from y coordinate one from y coordinate so y will become again 0 so as you can see it is kind of a easy mathematics so this is kind of a how we want to do the like movement of the robot right as it goes uh basically we are simulating this g part actually right here and then we have created a direction map so direction means like you have a string and array list of strings so for every direction this is your current direction and if you get l for example if you are looking at north right now for example you are looking at north and if you get l here then you what you will do you will go 90 degree here right which means that you are going towards west so here as you can see the first part is l and second part is r so when you are doing r from north you will go to east right so here we are going west but if you are doing r then you will go to east right on r so basically that's what we are simulating this l and our operation here so this is for four direction right north south east west so uh the first in this list the first is value will be for l and the second value is for r so we will start with current location as north and we will start with current coordinates at 0 and we will read through instruction in the for loop and we will execute the instructions here so if we are getting g then we will just modify the x uh x and y coordinate of the current location according to the you know the current location uh direction right then we will use this location map for example if you are going uh north then we will just use 0 1 means we will add that 0 and 1 in x and y values basically so that's how we are simulating the movement of the robot in the g and if we are getting l like uh l basically this l right or r then we are using our direction map so in direction map if it is l we will get our current location direction here like for example if it is north then we will just get 0 up from this list means we will get west here right if it is r then we will get a one from this list here which is east so as you can see we are getting zero here because we are doing l and otherwise if we are doing r we will get one actually from that list so this is the way we are simulating the l and r operation so we will keep doing these operations in the loop in this for loop and at the end we will check if the current location means the basically the final location that the robot reaches if it is 0 again right if it is again 0 means we will return true but if the current location is not 0 but if its direction is not north right the last time the direction is not north for example in this case right gl here uh we will be only doing one g and one l right we are not doing like in a loop basically in the java program it's not like a loop that we are doing gl only one gl we will do so in that case we will just end up with uh the robot is facing direction at the end is west right after doing gl the robot direction will be facing west so that is also we will be considering as true because that is if you execute this in a loop actually like not just gl but g l four times then you reach zero right so that's why we will check if it's its facing is not north at the end then we will return true basically so as you can see current location is not facing north we will return true and at the end we will return false so this is a simple java implementation uh so as you can see this location map we are going to create like simulate the g uh instruction where we have to uh you know move one unit but we have to how we will be moving that one unit is we will be adding this 0 and 1 to corresponding x and y coordinate that's what we will be doing right as we are doing here basically you can see right and it is based on the current direction right so it will automatically know the current direction if it is not then it will add 0 to x and 1 to y if it is south then it will add 0 to x and it will subtract 1 from y so that's how it will work so uh and we have defined one direction map here this string and array list of strings this direction map we will be using to simulate l and r part right where basically the robot is not actually moving but it is just changing his facing direction so in the beginning it is facing north but it if you do l then it will start facing west right it will turn 90 degree to left like that basically so that part we are simulating here so i think uh i explained it pretty detail about how the robot like will be moving and executing the instructions and how at the end we will be checking its current location or current location direction to decide if the robot is founded in circle so this is how you can solve this problem in java so as you know i often create videos regarding java j2 interview questions as well as elite code solutions so uh please subscribe to the channel and hit the like button because this helps the channel to grow and reach to more people so thanks for watching the video
|
Robot Bounded In Circle
|
available-captures-for-rook
|
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direction** is the positive direction of the x-axis.
* The **west direction** is the negative direction of the x-axis.
The robot can receive one of three instructions:
* `"G "`: go straight 1 unit.
* `"L "`: turn 90 degrees to the left (i.e., anti-clockwise direction).
* `"R "`: turn 90 degrees to the right (i.e., clockwise direction).
The robot performs the `instructions` given in order, and repeats them forever.
Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle.
**Example 1:**
**Input:** instructions = "GGLLGG "
**Output:** true
**Explanation:** The robot is initially at (0, 0) facing the north direction.
"G ": move one step. Position: (0, 1). Direction: North.
"G ": move one step. Position: (0, 2). Direction: North.
"L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.
"L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.
"G ": move one step. Position: (0, 1). Direction: South.
"G ": move one step. Position: (0, 0). Direction: South.
Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).
Based on that, we return true.
**Example 2:**
**Input:** instructions = "GG "
**Output:** false
**Explanation:** The robot is initially at (0, 0) facing the north direction.
"G ": move one step. Position: (0, 1). Direction: North.
"G ": move one step. Position: (0, 2). Direction: North.
Repeating the instructions, keeps advancing in the north direction and does not go into cycles.
Based on that, we return false.
**Example 3:**
**Input:** instructions = "GL "
**Output:** true
**Explanation:** The robot is initially at (0, 0) facing the north direction.
"G ": move one step. Position: (0, 1). Direction: North.
"L ": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.
"G ": move one step. Position: (-1, 1). Direction: West.
"L ": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.
"G ": move one step. Position: (-1, 0). Direction: South.
"L ": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.
"G ": move one step. Position: (0, 0). Direction: East.
"L ": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.
Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).
Based on that, we return true.
**Constraints:**
* `1 <= instructions.length <= 100`
* `instructions[i]` is `'G'`, `'L'` or, `'R'`.
| null |
Array,Matrix,Simulation
|
Easy
| null |
191 |
so lead code problem of the day and here we bring a solution for you welcome to the runtime error the place where programming begins in this video we will be solving a lead code problem of the day that is number of one bits so this is one of the easiest question we are coming across today so I highly recommend you to watch this video till end so that you can understand the approach and the intuition of this problem very clearly so without wasting time let's get started so what does the question says that we need to write a function that takes a binary representation of unsigned integer now the question comes what do you mean by unsigned integer itself says that a integer which is not a negative therefore it simply means a number which is greater than Z it should not be less than Z and what we need to do is we simply need to return how many number of ones are there in the binary representation of that unsigned integer right they have also given us one particular note so what does it says that in some programming languages like Java there is no concept called as unsigned integer so for that purpose we need to use a two's complement so that we can get the unsigned integers so I hope so you understood the meaning of the question now let's try to check what will be the sample input output for the problem so this is the first sample input output problems they have given the N always remember whatever the input we will be given they will always be in terms of 32 bits right they will be always be in terms of 32 bits so if you count the total number of bits present in this n there are 32 bits and what will be the final output 1 2 3 so in this four number of bits there are three ones present therefore my output will be three if you take this n there is only one is present therefore my output is one and if we count over here there is 31 ones because there is only one zero which does not condense one there for my output is 31 so I hope so you understood the meaning of the questions and the sample input output now let's jump to the proper approach and the intuition to solve this question now let's check the intuition for the question so in this question what they have told us they have given us a binary representation of any of the number and what we need to return is we need to return the number of ones for in this example there is only one therefore we need to return one and there is one more problem that says that we have given a particular integer say for example six and what we need to do is we need to return a total number of ones present in the binary representation of the six but in this problem what they have told us instead of giving a integer they have given us binary representation and we need to find the total number of one present in the binary representation so can we say that the solution for this problem is somewhat similar to the problem which says that we have given a integer find a total number of one in its binary representation so both are the similar so what we are going to do is we are going to use a concept called as a bit manipulation right everyone knows it I hope so bit manipulation so how does a concept will look like so there is one formula I have already told in the previous video that is Nal to n and nus1 so the question comes what does this showcases right what does this indicates so what does this indicates it simply removes last bit which is one for example say for example n is equal to 6 now what is the binary representation of 6 2 to 0 that is 0 2 to 1 2 0 I'm taking it four bits and N minus 1 which is nothing but five right this is five and what will be this binary representation it would be 0 1 and my old original value of n is 6 which is the last one bit this right this is my last one bit this is my second last so what does this indicate it simply removes a last bit which is one so last bit which is one is this one so this will remove a last bit that is it would become if I do and it would become 0 1 0 if we can see previously my last one bit was one and it is completely removed and it is converted into the zero so this is how n = to n and n minus one work it simply = to n and n minus one work it simply = to n and n minus one work it simply removes the last one bit now if you try to get the N is equal to what does it indicate 0 1 2 which means it is 4 and if I do n minus 1 which is equal to 3 and what will be the binary representation of 3 0 1 again if I try to do the end what would be 0 if you look over here the value of n is four the last bit one is this one and we have completely removed this one and converted into Z Zer therefore we have proved that n = n and nus 1 simply proved that n = n and nus 1 simply proved that n = n and nus 1 simply removes the last one bit and what does the question says that we need to calculate a total number of ones present in its binary representation right so I did this and operation two times one and two and how many number of ones was there in six two 1 and two right two times we have removed this so can we say that we can implement this formula until unless my n is not equal to Z once my n becomes zer I need to stop because that does not contain any number of ons therefore we need to stop it and at the same time what we will do is we will calculate how many times we have performed the and operation so let's take an example say for example my n is equal to 6 right so what I will do is I will run a loop till my n is greater than zero and what I will do is I will simply do n = to n ending with n minus1 and at the = to n ending with n minus1 and at the = to n ending with n minus1 and at the same time I will keep the counter just to know how many times I am performing and operation right so what I will do is CNT ++ and initially my count is equals CNT ++ and initially my count is equals CNT ++ and initially my count is equals to Zer so I'll perform this operation and at the end what I will do is I will simply return CNT now let's make a dry run to check whether this is correct or not so we have seen that for n equal 6 what will be the binary representation it would be 0 1 0 right and N minus 1 becomes 5 right it 5 so it would be 0 1 now if I do the and operation what would be it become 0 this become 0 1 and zero which means again my last bit is converted into zero and this will execute now because we have executed this one so how many times we have performed the and operation only one time right previously it was zero so it would become one because we have performed one and operation still my n is greater than zero so this condition becomes true so what it would be so n is equal to 4 now right this is 4 so it would be 0 1 0 so N - 1 becomes 3 would be 0 1 0 so N - 1 becomes 3 would be 0 1 0 so N - 1 becomes 3 which is equal to 0 1 now if I perform and operation it would be 0 now so n becomes 0 and again this will get executed so it would become one of two now simply I will return CNT because why see my n becomes zero so this condition gets false so I will come out of Loop and I will simply return CNT now what is the value of 72 and if I get what was the number of one present in the binary representation of six two one and two so can we say that we have finally got the required answer so this is what we will be using to solve this question it would be applicable for all the programming languages so it was a most simplest question only difference was in this question they have given a binary representation instead of giving us a integer even if they have given integer we would use same formula we would use the same formula whether they have given a binary representation or an integer the both it is applicable to both so don't need to worry about it so I hope so you understood the intuition and the approach to solve this problem now it's time to see what will be the C++ and the Java code so this is the C++ C++ and the Java code so this is the C++ C++ and the Java code so this is the C++ code and this is the Java code you can check according to their own convenience so as I told you first of all I will keep the counter to count total number of and operation while performing so for that purpose I have maintained the variable called as ANS similarly I have maintained here ANS so what we'll be doing I will be running look till my n is greater than zero and at the same time I'm performing n = n and n minus1 time I'm performing n = n and n minus1 time I'm performing n = n and n minus1 and I'm also keeping the counter just to make sure how many times I'm performing and operation and once my n becomes less than Z or equal to Z I will simply come out of my Loop and what I will do be it will simply return and total number of and operation we have performed which is nothing but total number of ones present in my binary represent ation now if I talk about the time complexity can we say that my time complexity will always equal to B of number of ones number of on so this would be my time complexity because if I have the four one 4 one in binary representation it will Loop till four times if I have the six ones in my binary representation it will run till six times so simply we can say that my time complexity will be big of total number of ones present in its binary representation so this was the most simplest question I hope so you this video clearly just in case if you're new to the runtime error please do hit the Subscribe button which motivates me to create such content for you till then have a happy coding
|
Number of 1 Bits
|
number-of-1-bits
|
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)).
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
**Example 1:**
**Input:** n = 00000000000000000000000000001011
**Output:** 3
**Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits.
**Example 2:**
**Input:** n = 00000000000000000000000010000000
**Output:** 1
**Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit.
**Example 3:**
**Input:** n = 11111111111111111111111111111101
**Output:** 31
**Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits.
**Constraints:**
* The input must be a **binary string** of length `32`.
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Bit Manipulation
|
Easy
|
190,231,338,401,461,693,767
|
943 |
hello everyone welcome to day twenty third of may decode challenge and today's question is find the shortest super string in this question we are given an array of words and we need to return the smallest string that contains each string in this array as a substring if there are multiple valid answers you need to return the smallest one of them also we should assume that no words no string in words is a substring of one another so the substring cases are not there let's try and understand the question by an example in this case we are given three words alex loves lead code and the small shortest sub super string that can be formed that contains all the three strings as a substring is alex loves lead code the concatenation of all the three strings although there could have been multiple answers there in any order for example loves alex lead code loves alex any permutation of these three strings is a valid answer so let's talk about another example we have words here cat g and multiples are scenarios the output here is something that is mentioned here if you carefully observe that every word is taken care in this output string this question is an extension of traveling salesman problem that involves dynamic programming as well so for now i'm refraining myself from using that and providing a simpler approach so that you can also understand it since i have not done any uh video with respect to traveling salesman problem i hope you like today's session so let's get started with the solution let me just take a pen find the shortest super string lead code 943 also guys it's a hard question so i hope i'll be able to explain my thoughts well here so let's talk about the list of words that are given to us alex loves lead code what we are going to do we will start creating new super strings starting from the word alex and then trying to find out the minimum shortest length super string for the remaining words and then again doing a merge operation to find the actual result in this process we will not only start from the aleks word the zeroth index we will try and loop across all the numbers that are there in our answer in our question sets for example first at first we will start with alex and loop across the remaining two arrays that we have loves and lead code in the second iteration we will start from the word loves and for the word love what are the two remaining strings alex and lead code the third one states lead code will start from lead code and try to find the minimum sub super string with the other two involved alex and loves and once we have the complete answer set for all these three possibilities we will extract the minimum one out and that will be our answer so i am what i am basically following is a brute force approach where i am trying to go through all the possibilities and arriving at the solution so the critical part here is how will i maintain which elements i have used in the past and which i am yet to use or available for usage also there is a constraint that you can only use one string once for example alex can be used once you can't repeat it loves can be used once you can't repeat it so we have to maintain some state so that we get to know what all elements have been used in the past and what all elements are available let's think about the case where we have a graph like a scenario and we usually take a boolean visited variable that signifies that whether the string has been visited or not but in this case it won't work because we need to know with what possibility of the current string have the other beam to use in the past we can't go with the boolean visited array because with every recursion start passing this boolean array has may get updated so you can't have a generic boolean array approach if with every recursion we create a new boolean visited array that will cause output limit exceeded hence we can't go with this approach instead we'll use bitwise manipulation to maintain a state variable that will actually tell us the complete state of our array what all words have been used in the past and what all are pending for usage how are we gonna do that we will so we'll enable all the bits up till the length of the input array to one we'll use a bitwise manipulation to do that for example there are three elements in the input data set will enable the first three bits of a number as a result of which we get one month enabled at the serious index first index and second index the state of this number becomes seven so if you make an integer out of it will point to seven also one means free zero means occupied so let me let's understand these two examples in this case sec alex is available for usage loves have been used and lead code is again available for usage in the last case only alex is available for usage the other two are unavailable for usage and have been consumed in the past so what all states does it correspond to this corresponds to four this corresponds to five if you convert them into integer how will we check whether a particular index add is enabled or not we will use this formula we will use the right shift operation to extract this bit and we'll do an end up with one if that comes out to be one that means it is available for usage otherwise it's consumed how will we mark a bit consumed we will use a left shift operation so let's say this is 2 raised to our i which is nothing but all the bits mark 0 apart from the ith bit and what we are doing a negative of it so that will toggle the behavior everything will be marked one apart from the current index and we are doing an state of and that means the current ith index will be marked 0 which signifies that the bit or the index has been consumed i hope these terminologies are clear to you and let's just move on to the coding part so that i am able to explain the logic better the first thing that i did here is to create a map and map signifies the starting string along with the state of the variable starting string plus state and the value here would be your shortest superstring up till with the current string as a starting string so this is the shortest super string we are using a hash map in order to avoid recomputation of the same states done in the past we have taken a variable state and we enabled all the bits in the state variable to one up till the length of words that was given to us and we passed it to a method shortest super string wherein the first argument is words the second one is the starting word the third one is the state and the fourth one is the map so follow assume this map as a memoization technique that we usually do in dynamic programming the first statement is very important if the state of a variable is marked as 0 that means state has reached the value 0 that means all the words have been occupied and you there are no more words to actually process so you will return whatever the start word is i'll explain this part later on let's just talk about the main logic the first string that i have declared is the shortest superstring that will actually store the shortest super string and i traded over the input array starting from the series index going up till the length if the current index is not consumed and is available for usage that means i have to generate the super string starting with the ith index so i recursively invoked this method parsed in the words in the input set of words the starting string would become words of the ith index i marked the ith index as consumed and updated my state variable and i passed map to it i generated the super string out of it and once i have that super string i tried oh finding the shortest overlapping super string using the start word and the string that is returned by this method so let's assume that this will actually append abc and bcd to abcd consider this as a overlapping shortest string method assume it to be a black box we'll talk about it later on and once i have that appended string i'll check whether it's lower than the previously calculated shortest super strings or not if it is i'll update the shortest super string variable so i'm just taking a left on the length the new shortest super string or the old one so whichever whosoever length is lower i'll pick up that and i'll put it back in the map now comes the logic for the key starts from the starting word whatever the start word is plus the state so we need to maintain the state as well so that we know what all elements have been consumed in the past if this if we find this key in the map then we'll simply return it and abort the process so that we can skip the recomputation again and now let's talk about the helper methods the first one being the consumed method so i talked about the consumed method we are using the right shift operation to find the ith bit and masking it with ending it with one if it happens to be true that means it is in the consumed state and you can't actually use it the next method in queue is a consume method uh you pass in the state variable and it with the not of i left shift one left shift i so explain this logic in the slideshow and whatever the new state is the updated stated we simply return it from the consumer method so it's actually marking the i it's state as i as 0 and ith index is 0 and updating the state variable now let's talk about the last helper method which is actually building the concatenation of two strings a and b for example a happens to be big k happens to be kelt what will be the out of output string ba kelt which is actually a concatenation or the overlapping shortest string of the two in two strings parse to the method it's a straightforward method where i try to find out the best possible super string for the two input strings passed and please go through it uh it's just a few corner cases that i try to manipulate here uh i hope uh this logic made sense to you guys and if you have any doubts or questions with respect to the algorithm that i have explained i'll be more than happy to answer those questions uh also if you like today's video please don't forget to like share and subscribe to the channel have a great day you
|
Find the Shortest Superstring
|
sum-of-subarray-minimums
|
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**.
You may assume that no string in `words` is a substring of another string in `words`.
**Example 1:**
**Input:** words = \[ "alex ", "loves ", "leetcode "\]
**Output:** "alexlovesleetcode "
**Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted.
**Example 2:**
**Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\]
**Output:** "gctaagttcatgcatc "
**Constraints:**
* `1 <= words.length <= 12`
* `1 <= words[i].length <= 20`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are **unique**.
| null |
Array,Dynamic Programming,Stack,Monotonic Stack
|
Medium
|
2227
|
207 |
Hello Friends Welcome to the Tag Rain Today Will Solid Court Problem Quad-Core Today Will Solid Court Problem Quad-Core Today Will Solid Court Problem Quad-Core Schedule and Problems Statements Dare and Total of Namakkhor Se Switch This Fruit and Friends Se Four Labels From Zero Two Namakkhor Se Minus One and Deserving 727 Input and Output Tax Liability Se Zla two and three years in power steering means the a three course is considered complete Next day I go to assess after two years which denotes daughter visit for the course for example effective this prerequisite it means the best before completing course one have to complete Course 0 Can Be Something Like This Are We Raghavendra Are After Listen And Are And Share Vihar 5105 Vihar Phase-2 N We Can Have Liked Share Vihar 5105 Vihar Phase-2 N We Can Have Liked Share Vihar 5105 Vihar Phase-2 N We Can Have Liked 3D Vansh House Another Thing Like 320 Soupdish Means Do For Completing Course One Part Complete Course 0 Computing Course Director Complete Course One Will Fly Computing Co 382 Complete Course One And Before Completing Cost Also You Complete Co Stool 737 Different And Many 121 Just One Shouldn't 1000 This Is The President Has Been Giving Does Not Give In The Total Number Of Courses This To Complete And Give A Prerequisite Vihar To Do It Is Possible To Complete All The Courses And Not So If You Like This Is The Example2 Hair And Force One Is Ringtone 2014 Completing Course After Complete 20 And Before Completing 2012 Complete Course One Will Fly Ka Cycle Hair Suicide Note Complete You Here of District Courts Is Show A and Asks You To Return Forms Will Not Be Able to Complete the Course of the President Has Been Given to Meet You Have a Look at the Country and From Where They Can Understand What This Is Like Up Graph Problems Verification Example Subha Can Think Like Bhavana Debit Mode Of Value 008 Something Like This Is Course One Knowledge That Before Completing Course Made To Complete Course 0 Okay And Similarly They Can Have From Course One Our Dependency On 14th And Course To Sleep Hair Hanging Main Itna Dependency Years Before Completing Course Two Part Complete Course Three Hair End Co Before Committing Toe Strive Toe Complete Course One Haire End Aggressive Recover Distance Course 300 Before Completing Course Three Left Complete Course One And Lives Up Toe Complete Course 210 Yes 10 Grams Will Come Out How They can reduce graph is you 2012 A-320 dependencies and graph is you 2012 A-320 dependencies and graph is you 2012 A-320 dependencies and completed in time to be constructed at anytime you want course one to start soon as you complete course sure has to be completed and the only Krishna can start for course 2015 bill in complete course two For course free both course one and cost certificates for this is how will read this particular graph no the question is how they can solve this particular pro to absolutely board this graph in 2nd edition c list and in job and jhansi least they can that basically user Now Map And Date Map Can Like Something Like You Now I You Of In Teachers Day Scores Of Volunteers By Kanhapa Map Something Like This Way Bihar Map Of India Via Bihar List Hair List Of Interior Book Member Claim Se List For The Telegraph You Do Not Have even understanding of the list of Baroda to the self graph and can be represented in English language subscribe and middle east end tricks friends can be used to be benefited and even which software will news agency list and how will create such list is will Have a Map of the Course This Data Dependent on the Course Will Show Safety Course One Two Complaints Loot Like If I Am Able to Complete Course 0 Start With Force One Should Be Left With Something Like This Day 512 Complete Course One Can Start With Courts Cars And Able To Complete Course To Rule And Not With The Three Layer And Completed In Due To Start With In This Particular Example For This Is The List Will Look Like Subscribe Problem And Web School List In The Way Torch Close This Graph Will Complete Course 049 Completed 20 I Can Go And Complete Course Vansh They Have Completed In The Next Code To My Channel Short Course Real Look Soft To Switch One More Incoming And Old Is Gold Individual Dealer In Coming Years Destroyed Degree Difficult Forward God And Degree 432 And In Degree This 08420 Details Why After Completing One Three Will Not Because It's Still Waiting For Tonight Independence Is The Song Difficult To Give They Have Completed Till 40 We Start With Services Since The Early Stags Pet 120 Ginger Ko Cycle Stand Complete Next Thing But IF Play In Thought with number three years to wait for also hundredth how to maintain the in degree s well and dirt in dreaming dot in degree can be represented s and like a list of vital part for each of the note sweater present form in decree and president Particular Note Super Hero SPC Degree 409 Plus 40 I Don't Have Any Income In Nod To See Things Will Go For The Point Degree Of Money To End 300 Indicative One Incoming Noticed Hair Early In The Morning 142 Still One Incoming Noticed A Certain Degree Of To Will Be equal to one and degree of Vadodara two incoming notes year in degree of this exactly tutu hear I know that in degree suit with I know 221 two have completed course 181 notes per day degree of course 320 is still need to wait for one more dependency two Complete for code three points based on logic and values to based on logic and values to based on logic and values to logical short top logical that can be done using Arduino and that you can be involved in the implementation of list show in date particular Q What will do you think that you will first and all Yours node did not happen in coming days like what behavior 402 merge put do samudra officer another not hear something like a course 500 defiance judi completed easy and begunah bana the share like or sex and youth one has difference years on one hand the dependency On Course Something Like This 100 Ko Kushwaha Not Have Any In Coming Notes They Can Still Go Ahead And Adds In Our Cubic Roots Which Can Be Completed First Notification For One Vihar To Go Increase The India To Two Here Okay Sorry For The Problem Na Boil Don -2 And Sorry For The Problem Na Boil Don -2 And Sorry For The Problem Na Boil Don -2 And West Indies 182 Inter College Annual Sports Day Time Once Will Have Completed All 20 Courses This Day Weekend Basically Reducer In Degree For The Incoming Mode Of Web Complete 0f Completed Even Have Completed 6 Can Reduce The In Degree After One Day He Will Return Start wave reduce indicative web complete the prerequisite for one sleep f5 complete 020 did not have in coming food or incoming you sleep without computer forced cycle reduce in degree of wave fighter of baroda office dependency is completed similarly when is complete course one can reduce the incoming Degree and in Degree of 20351 ft Differences Completed and This How Will Go About This Particular Problem Solve What Things Need to Take Care in This Particular Problem His First Visit to Create and Decency List for the Problem That They Have for the Prerequisites to the Course Not Will build a solar light system Will create map and will populated Research agency list Will create the second thing that will be a great wealth creator in degree and will play The Indian real history of which will tell us What are the number of incoming apps for each Research System Work You Too Short And Process So Latest Look Into The Solution And They Will Be More Clear If You Have Any Doubts That's Center Video And Lift Explanation Add This Aap Samiti Sultanpur Tender Comment Section And I Will Definitely Answer Dot Saunf Very Map here pin teacher and chief list of in teacher the 210 vacancy in this request undhiyu shop that and will have in degree a bill which will be like and in teenagers light bill list of third list of integration e want equal to new and difficult Poonam try water is the number of course is dam in degree and damini notes with her for which will have to computer the number of incoming apps shiv vihar this to 20 q but will deal with the later for status power the map handed over letting them app what We need to Ashwini to go through the Prerequisites for Liberty of Civil to give the table in danger of having a rack 210 Prerequisite will be half that of two elements 06 2010 Daughter Different Elements and Difficult What is the element on which the first one is different In less than 10 seconds one will tell what is the course to be taken that and scores to be taken will be equal to district of wave to blind post one will take that of course and latest meters from new course and you will be different so that Dependent Will Be Equal 2000 Soe A Dependent Men This Is Different On My Course Once Course Completed Suddenly Dependent Can Be Completed The Quote We Can Do Here Start Mill Say Dot List Of In TJS Different List Request To Map Don't Get For The Course And a gift a dependent list record broken showing that this will initially be the different list will from that independent list request to new a terrorist I will give you this and find vacancy dependent list dot and will depend on I will not dependent here that your He told this 9 Next Thing Is That They Would Get Populated Next Thing Is Not Be Also Need To Play The In Degree For the indicated visas dot in degree of they never get the depend a half different courses and sombir and been counted as you in prevented by what this means the best which office applicant or scheme and co switch on it means just switch dependent upon one of The course is sweet as one in coming days stubble increment The in degree and position of India Radio will initially be like Chief like position of India will be 0123 Latest and values of all this will be 0123 Latest and values of all this will be 0123 Latest and values of all this will be Shyam counter first time daughter-in-law dependency on note 150 daughter-in-law dependency on note 150 daughter-in-law dependency on note 150 Ment By One Next Time Vinay Encounter This Channel Increment The 2513 This Dependency And One Actress Ment By One If Encounter Fake Presidency 127 Prevented By Two Soldiers Prevented By Two Soldiers Prevented By Two Soldiers Coming * Has Been Coming Not To Have Been Coming Not * Has Been Coming Not To Have Been Coming Not * Has Been Coming Not To Have Been Coming Not 181 Coming 1000 In Coming Days Witch Will Be Something Like This Cream And Diagram For Hair Loss Enmity Sealed In 2 Dishas India Will Be Different For Abs For This Year They Are With Power Map Down List And In Turn Will Be To Win You To Love You To Our Video List And Also To see how many courses complete the list of these teenagers and drive in this can be the implementation of list in jawa and need to howrah counter on 234 builder how many courses not behave completed work and another thing but weekend tourism in just astronomer who goes past To Our In Degree List Straight Will Be I Love And Agreed Not The Limit Between Length The Number Of Course Not Behave I Hop Luti Plus 2 And Share Will See Notification In Degree Of High Frequency To Successful Video Not Have In Coming Days 8 AM :00 This Is Not Work History Days 8 AM :00 This Is Not Work History Days 8 AM :00 This Is Not Work History Awaits More Any Process Fast And Can Be Completed Without Having Any Dependency So Every 1000 Can Go Through Our Cute That Latest Not MTV Show Will Go Through The Queue And Will Say Int Values Loot The Queue And Will Say Int Values Loot The Queue And Will Say Int Values Loot Poll That And Will Increment Our Counter 34.09 That And Will Increment Our Counter 34.09 That And Will Increment Our Counter 34.09 Work U&V Shape Basically Pole Date And It Work U&V Shape Basically Pole Date And It Work U&V Shape Basically Pole Date And It Means Whenever You Complete Dot Co Switch Process Don't Know Since They Have Completed Dr. Shyam And Width Map Web Complete The 20 Courses Hotspot Of The List Withron Its Decrement Late- There in India every one all the Decrement Late- There in India every one all the Decrement Late- There in India every one all the departments particular course complete subscribe particular list hotspot of the volume and decrease the value cervix cancer inter-dependence value cervix cancer inter-dependence value cervix cancer inter-dependence c and you will be coming from get the key c and you will be coming from get the key c and you will be coming from get the key vidyalaya vikas will be lit bollywood data dependent upon this Particular value so for all this value they can just decrement a in degree pure in degree of this will be minus and go to check dot vipin degree of dependency in husband comes after completing this course withdrawal dependency has been completed solid evidence has been completed can Be done to the giver and debit the that this particular is the particular dependency in the independence already completed 100 and in the process this particular subscribe and with your valuable and most of the that if the counter absolutely increasing and Hindi and you can simply account it It Is Equal To The Number Of Course Is Dish Tour Matching Day It Means Dot Being Completed All The Procedure Of But Not Completed For The Courses For Electronics 118 Sambhal Point Risan Ki And Dhul Point Research Ne Bigg Boss And This Is A Text Size Record Absolutely Call on day 204 Date Fixed Deposit Channel Pointer Exception Do More Null Contract Sabse Means Swadeshi List Had Not Been Initializing Time We Can Get Our Lives In General For Investigating Agency Reduced It's OK Dot Victim Of And Simple Solution In These Particular Cases That They Can Not for loop here and they can basically go through all the courses and dependence and vhip 9 inches of the courses basically and this will be in tiles equal to zero electronic that at that I plus and share I can do map daughter I am in Mumbai Because this is from contest Because this is from contest Because this is from contest decors and they can create a new are list here is 210 switch on the problem from now on blindly in this video naat sharif and hadith strong words logic property ok only problem hospital the course that they want to destroy Latest Submit This That Hurt Accepted To Details How Will Basically Approach In That Graph Problem Behavior Dependency Like This If You Go To List Ko Dead Another Problem Shimla To Dushwar Vihar Phase Of Course Dual To 100 Events Problem Is Shimla To The Last One But In This Case And Expecting The Interior Output Which Means Don't Want To Give The List Of Course Notifications Interested Time Dependencies And All And Need To Give The List Of The Order In Which Were Taking Decors Is Slide For 10 Gram Positive CD Controversy 214 Kun0 Ko Studento Sworn In Question for this will be similar to what we have sold hill only difference will be do not write the amazing something in work you have to do at the time which can just edit in our the teacher of which we have to return will editing dogs who are so ever since they are Doing Something In Over Cute Means The 2000 Eligible For Dost Ko Saja Eligible For Women Vikas Courses Basically A Suddhen This How Will Solve The Problem Powder Safed Connect To This Video Do Like And Share And Subscribe Our Channel Take Care
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
1,365 |
hello so today we are going to do this problem called how many numbers are smaller than count numbers so what we have is an array of numbers and for each number we want to find out how many numbers in the array are smaller than it so each number I you have to come the number of da Vinci inserted such that and she is different than I and so basically have an array of numbers and for each number you want to find out how many numbers in the array of smaller there is each that is each number of I you have to come the number of our development chase such that J is different than I and number at position J is smaller the number of position I and one written the answer in a way so for example we have this and the output should be this because we have four smaller numbers than eat here we have one smaller than one no we don't have any does not exist any smaller number then it so we should return one Oh is zero yeah four - we have one is Oh is zero yeah four - we have one is Oh is zero yeah four - we have one is smaller than it but it's not after it just has to be different doesn't need to be after it for two we have same thing this one is smaller so one three it's won't say okay so one we can do this just in 2 loops this is the easier brute force solution so that would be something like so it would be in the range of the lengths of numbers and the similar thing for numbers here and from there we just check if today is smaller than 4 I we will need to have our little array here and we'll need to count so we can count them like this and if we find one we should just increase and we could say it as a pi is equal to count and at the end we should do a pen actually so okay looks good submit okay so that passes this is oven square time you should think about making this better so basically we need the way given a number to determine all those that are smaller than it hopefully in less than oven time so if we had the array sorted maybe by just looking at the position but yeah we're just looking at the position will tell us how many numbers are smaller than it right so we can have something like this like salted and we just put the array sorted and then from there we could just find the count by binary session on the salted array it's about being using my second year and so the way bisect work is that but let's just grab this example so if we take this one oh actually this is the numbers one and then we can just have salted numbers be equal to sorted phone numbers so if you do this what does so we have that now if we look for let's say three so if you look for so he is bisect this first important to pass first the array and then the bottle so the array is sorted no surprise and then the value out of the policy is three so we get four so get the index after its presence right so this tells us that do we have any guarantee that the array doesn't contain duplicate values so even if there were like duplicates we only want smaller right so this means that we should probably here have bisect light because what if I had and well let's take an array that has duplicates right so if we bicyclist gives us three and just bisect or give us five so it won't pass after all those three so what we want is really bisect left so bisect left gives us exactly the number of other smaller than so this is what we want so we could use that here and we need to pass the number position I and who could just basically that's the count that we are looking for okay so this works in terms of time this is open login and this is open and this is like an open logins overall it's the total time is open again in terms of space its we are using this extra right here so it's open space yeah and that's pretty much it I think for this problem and we could check what other people how other people handled but it should be similar so he would kind of cares of each number and then take the rank some of these occurrences and for each number it's okay that's clever for each number it's the running sum of the previous number before it right and since we have product to the problem we have at most 100 and number is at most 100 so that would be basically what we can do here is something like this what we could have count of hmm so this would be just zero for the range of 101 right so the max number we could have and then we could because for each numbers of bonum in numbers we could say count of none is equal to we just increase it right so actually here instead of doing this we could do that but we could also just use a collection by it but let's just keep it this way and from that we could say okay for just keep on running some note with them so it would be Plus count of non minus 1 and then for every number in this so we'd have Reza - every number in this so we'd have Reza - every number in this so we'd have Reza - 1 those are the elements smaller than Earth and interest yeah so it's not numbs its numbs up hi there so this is light what if we just yeah four zero it will be minus one so that would be problematic yeah so if the number is equal to zero one a hundred differently because otherwise we'll get minus one and we'll get the last element so if the number is equal to zero we only just return okay said that bus is cool you know so the solution that I did earlier which was this one here with binary search we could actually just look up the index and if it doesn't exist then we will get the index we're looking for so it's this one here we can change it slightly okay instead of returning so here we could just take sorted number and just looking for the index for numbers of I and actually we could just make this and get the index for that element and then that would be the result that we are looking for so we just do it like this and we could even use just a list comprehension here okay so you just use all this comprehension like this well here what were what we want to return is mostly this we can get rid of this and except here when the sorted number so if you just say salted nuts okay so that was yeah so that's all for this problem thanks for watching and see you on the next one
|
How Many Numbers Are Smaller Than the Current Number
|
how-many-numbers-are-smaller-than-the-current-number
|
Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`.
Return the answer in an array.
**Example 1:**
**Input:** nums = \[8,1,2,2,3\]
**Output:** \[4,0,1,1,3\]
**Explanation:**
For nums\[0\]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums\[1\]=1 does not exist any smaller number than it.
For nums\[2\]=2 there exist one smaller number than it (1).
For nums\[3\]=2 there exist one smaller number than it (1).
For nums\[4\]=3 there exist three smaller numbers than it (1, 2 and 2).
**Example 2:**
**Input:** nums = \[6,5,4,8\]
**Output:** \[2,1,0,3\]
**Example 3:**
**Input:** nums = \[7,7,7,7\]
**Output:** \[0,0,0,0\]
**Constraints:**
* `2 <= nums.length <= 500`
* `0 <= nums[i] <= 100`
| null | null |
Easy
| null |
1,836 |
and unsorted linglist giving the head of a link list find all the values that appear more than once in the list and delete the notes that have any of those values so and we should return the linked list after so what we have here is a link list that we have and it says if it's there is a duplicate value like number two here we see we have two of these we are going to remove both of them and then we are going to return the link list so as you see here we have one two three two so what we are going to do we are going to remove the both node two and we are going to return uh link lists like this one and three in the other example as you see we have two one two and we have two of each so we have to remove two and ones so we are going to return an empty link list and in this example as you see uh we have these numbers and after removing the duplicates what we are going to have is just one and four node and the constraint here it says like we are going to have at least um like the number of nodes in the list start from range one two ten power five so we are not going to have an empty list and the values are going to be from one to 10. so as you see here when we create a link list when we create a node the default value is 0 which is not included in this range so using all this information what we are going to do uh if you want to do it in one path so we need to create a dictionary a hash map of the values that we have in the link list so when we are doing one pass when we see that value we know we have it in the dictionary and we check how many of these values that we have and if it is more than one we are going to remove that when we see so let's see how we can do that for doing this we are going to use a default dictionary from uh collections so we are going to call collections library and we are going to called uh defaultic and we are going to consider that as integer values right so this is the hash map that we are going to have and then what we are going to do we are going to put the head somewhere called cranes and you're going to say while current what we are going to do we are going to say for the value that we have the hashmap because we are using uh this defaultation we don't need to check if we have that value in the dictionary or we don't it doesn't matter so we are going to say hashmap for the currents we are going to get the value as you see here when you create a node you are going to have two uh things we are going to have value and x we are going to say for the value plus equal one and we are going to move one step forward oh sorry current dots next we go to the next uh value so what is happening here so we start from like in this example we are start from number three we check that uh if it is not in the dictionary we are going to add it and we are going to assign one to it and then the same thing happened so let's print this hash map so you can see better okay as you see let me use a bigger example here so let's change the test case to this and let's run it so as you see here this is the dictionary that we are going to get for this example so i'm going to just put it here um for like illustration purpose for understanding this so this is what is happening here so this is the dictionary we have two three we have three number two we have one node one and we have one node four right and now then what we're going to do we are going to start iterating over this linked list again and we check the value if we have them in the dictionary we are going to remove them right away and if we don't we're just going to pass that for doing that what we need to do we need to for removing a valley and node we need to know what node we have before that and for making this uh like solution easier we are going to use a dummy node here so i'm going to create a node least node and i'm going to put um like create a node and as you see here all i need to do is i'm going to put zero here and it's going to um okay to put just this here next is equal to head because the default value for um val is zero so we don't need to define that and then what i'm going to do i'm going to say the previous pointer is pointing at dummy variable dolly node and the current one is pointing at head so then we are going to have a while loop we are going to save for file current as long as and the node is not empty and we are not pointing at uh none we are going to say if a hash of the current dot that is bigger than one we need to do something we need to remove that we are going to say current is equal friends that's next and the previous one that's next is going to point to current and if the value that we have uh the value that we have for that key is not bigger than one what we are going to do we are going to just go one step forward we are going to move the current pointer one step forward and we are going to move previous pointer one step forward and at the end what we are going to do because we have a dummy variable here we are going to return dummy dots next because we don't want the num dummy um node to be included and run this and there you go the time complexity for this is going to be linear and the space complexity is going to be linear as well because we are using this dictionary thank you
|
Remove Duplicates From an Unsorted Linked List
|
count-ways-to-make-array-with-product
|
Given the `head` of a linked list, find all the values that appear **more than once** in the list and delete the nodes that have any of those values.
Return _the linked list after the deletions._
**Example 1:**
**Input:** head = \[1,2,3,2\]
**Output:** \[1,3\]
**Explanation:** 2 appears twice in the linked list, so all 2's should be deleted. After deleting all 2's, we are left with \[1,3\].
**Example 2:**
**Input:** head = \[2,1,1,2\]
**Output:** \[\]
**Explanation:** 2 and 1 both appear twice. All the elements should be deleted.
**Example 3:**
**Input:** head = \[3,2,2,1,3,2,4\]
**Output:** \[1,4\]
**Explanation:** 3 appears twice and 2 appears three times. After deleting all 3's and 2's, we are left with \[1,4\].
**Constraints:**
* The number of nodes in the list is in the range `[1, 105]`
* `1 <= Node.val <= 105`
|
Prime-factorize ki and count how many ways you can distribute the primes among the ni positions. After prime factorizing ki, suppose there are x amount of prime factor. There are (x + n - 1) choose (n - 1) ways to distribute the x prime factors into k positions, allowing repetitions.
|
Array,Math,Dynamic Programming
|
Hard
| null |
1,509 |
Hai Haryana Roadways Question Spoon Just Follow So Question Kya Bol Rahe Naam Aalat Chus-Chus Can And Subscribe Aalat Chus-Chus Can And Subscribe Okay So Let's See Together How 532 For Example A That This Affair Question Is Okay And In This It has been told that our different size is zero at the end, so what is the saying, change is 5320, how have we done, what time should we keep the actresses close, so we are the first one, we could have done it in advance, that we have softened it, I have cut it all off. All then after that we are update the first element or the smallest because we have the minimum difference so this is that in the sea we can do the smallest and the largest and then we can update and use a saiyan And the mustache is at the ends of ours, okay, this is the hanging verification, now let's see, let's spread it towards So now we have this one coming, now we cut it, after doing that, let's give that in this section Now we will not worry about the unnecessary tension that in the war, first of all, his village is the biggest and the smallest, okay, so if we start updating right and correctly, okay, then what will happen, first of all, we will save ourselves from the trouble by doing the update and If you haven't subscribed yet, then you are okay, so now we will use such a thought process that how the organism is 114 6 and we have a maximum of three charges that we are okay, what will it mean which is the smallest elements years This is for Shri Krishna, it will be good which will be the force element and will remain and the last limit will be on the distance on the sets of fourth element means the last element - note content element - note content element - note content - - - why on 4a because first someone got up from the stage and said, eldest brother, look, I am all this The biggest of the year that we are the last updated ones, how will they update, that is, the youngest brothers will force them for you, so what will be the answer in this, that force will be the last one and the one which will be the first rally, the difference is 8 - 06 element, right? Because minimum distance means we have minimum difference between maximum and the end fourth class hit the biggest record zero okay now after that we are in another way that we are going to update yes and one right stomach and one hand laptop rate If you do then set right News what does it mean like you are laughing now your home recipe 380 015 volume do 2014 6 ok in this I am speaking let's do fat so if this so I gave that if we did two were right If we update 28 shells flexy then what will happen in that case, what will be our minimum and it will be four of us so that we can have Wellington stars, what was in this case when we updated three last, then last updated on Jai Yes, it's fine, and when we removed the support from Black Tea's movie Left, these three, then for this I changed the minimum volume to maximum, so now what will we do, I took the flame of gas. Okay, it's fine, so someone will check it, then how Shahrukh. Savarkar said and tells about you, first of all, I had shot first, okay, I have given my input, once we see the constraints, because we can put it in the start lamp stand, it can be powerful, okay, so its After this, what have I done, flash lights, what will happen after that, I put it in the internet and family end, after that I took the PAN, what is the number, what is the size, it means if we have Chinese element like support, not if we can put all three, then it means lions. Poonam Pandey Photo What would you do in this, if three elements were called the first element, what would be the difference, so I said that if I do it, I am fine. How to what will happen in that case when I have done the scene right people will do the next okay that I have done this treatment now my maximum volume minimum age is 102 okay so see hero 1234 500 what will be our size so it is - 4a what will be our size so it is - 4a what will be our size so it is - 4a so I have Whose difference was found out and - 4 - Name Fennel, I took this and its and - 4 - Name Fennel, I took this and its and - 4 - Name Fennel, I took this and its different radium, okay, so one month, I updated the volume with Very Young Man and Boys, then after that, what work did I do left time, removed the snow, if we could say this then we can discuss. I have taken a few, I am removing the whole thing from the right like this, okay, how will it be calculated in this, the minimum will increase by four, okay, so in the last, maybe I will try to remove the main course till now and one If I try to remove the tight one, then in this I have women's name soft to maximum garlic naan saint - name soft to maximum garlic naan saint - name soft to maximum garlic naan saint - sai pa hello so the same thing has happened name fennel and minor freezing - - verb - okay minor freezing - - verb - okay minor freezing - - verb - okay and one left that I can do on the right side I am removing the strikes, I removed two, wiring and list one, then its nature, where will the minimum come from, its hit is the maximum forest in the strangers and this knowledge is the sun number one for all that end - 4a - 4a - 4a that end - cream, that end - cream, that end - cream, okay, so If I take the difference of these two, then I will find the minimum brother, OK, I can see that it is done and the saree and long term is a professor in login at this time complexity paste complexities order no that the commission Ajmer distance course will be available in the land of That Idea Description Thank You
|
Minimum Difference Between Largest and Smallest Value in Three Moves
|
replace-employee-id-with-the-unique-identifier
|
You are given an integer array `nums`.
In one move, you can choose one element of `nums` and change it to **any value**.
Return _the minimum difference between the largest and smallest value of `nums` **after performing at most three moves**_.
**Example 1:**
**Input:** nums = \[5,3,2,4\]
**Output:** 0
**Explanation:** We can make at most 3 moves.
In the first move, change 2 to 3. nums becomes \[5,3,3,4\].
In the second move, change 4 to 3. nums becomes \[5,3,3,3\].
In the third move, change 5 to 3. nums becomes \[3,3,3,3\].
After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
**Example 2:**
**Input:** nums = \[1,5,0,10,14\]
**Output:** 1
**Explanation:** We can make at most 3 moves.
In the first move, change 5 to 0. nums becomes \[1,0,0,10,14\].
In the second move, change 10 to 0. nums becomes \[1,0,0,0,14\].
In the third move, change 14 to 1. nums becomes \[1,0,0,0,1\].
After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 0.
It can be shown that there is no way to make the difference 0 in 3 moves.
**Example 3:**
**Input:** nums = \[3,100,20\]
**Output:** 0
**Explanation:** We can make at most 3 moves.
In the first move, change 100 to 7. nums becomes \[4,7,20\].
In the second move, change 20 to 7. nums becomes \[4,7,7\].
In the third move, change 4 to 3. nums becomes \[7,7,7\].
After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Database
|
Easy
| null |
897 |
hey everybody this is larry this is day 17 of the april lego dairy challenge hit the like button to subscribe and join me on discord let me know what you think about taste bum increasing order search tree um so i only have about 20 minutes to the actual deco contest so i'm going to probably rush this a little bit um so okay so let's say given a root of a binary search we rearrange the tree in order um okay uh let's see don't eat about 100 nodes um right here to be honest i'm trying to think whether we can do it in all of one space we certainly can do this in of n space in a couple of ways you can you know have an array and then just do it uh like in order and then you can create because essentially this looks like it's just creating a linked list after in order uh values so you can definitely do it that way um and you certainly so you can do it in order and then you could convert all the notes or you could do it that way but then that's always going to be off and space um i'm not gonna lie we're a little bit uh in a hurry otherwise because i feel like i'm gonna mess this up otherwise um because basically you wanna get to you wanna have a function that gets to right most node and then that node will be pointing at itself but then what will point it at that one hmm i don't know okay i'm not gonna lie i'm gonna cheat for today uh it is easy and space is only a hundred so i think if you're in an interview honestly i would say okay n is a hundred yeah we don't want to prematurely optimize we have enough space let's just make it our event uh but maybe we can probably do an over one um yeah okay so let's do that for now but only because i want to make sure i have time for the contest because i feel like we can probably do it in all one space and is that even true now i mean we because if we do recursively we need all of h space anyway um for the you know the recursive chord stack so yeah so maybe that's fine i don't know if you're a little bit yucky about it but uh but essentially we're having a linked list but which we know so let's do it let's just do it that way i'm gonna do it recursively with yeah let's do it that way uh yeah let's have a sentence i know that i always call it like new root or something but i've been trying to be a little bit better about that and then now we just have a regular inorder traversal so if notice return otherwise in order no that left do something and in order to know that right this is obviously regular in order um and then here we write okay or last tail maybe again we're using the node like uh like a linked list um so then now we do tail dot right yes you go to node you want to do it that way okay i think this i just thought about this space analysis and actually maybe i'm lying on this oh and it's going to be of h so yeah i guess it is what it is okay um tell that right and we have to make sure that tell that left is none yeah i think this is right it could be wrong it could be i could have an off by one or something oh i'm just trying to make sure that i um do these in the right order so that it doesn't get impacted or something but i think this should be good um all right let's run it real quickly and then see if i'm right or i'm just lying okay uh or like just wrong not lying but if i knew i was right or if i knew i was wrong i would just say it but uh yeah cool oh that looks okay so let's give it a summit i've done it twice before i wonder how i did it previously oh no i messed up my easier today wow yikes did i not clean everything that's the only reason how huh what is wow yikes this is what happens when i'm trying to reduce memory if i just create a new node this would definitely work um but i uh tell that right is he gonna know maybe i think i'm not setting things this is okay so now that i'm here tell that now yeah this is wrong because i'm cropping it off before we because we're crushing recursing on the note and that's the part that i was worried about um when i said before like when i had like on here that's what i was worrying about it was because we're doing a recursion on this note while modifying this node so hmm all right there's probably a queen way to um one two four three let's see i'm just writing it out real quick wow today is hopefully i'm getting this wrong answer for today and not for later but um huh i mean i know how to solve this i'm just trying to think how to do it within the same space constraint um because definitely uh for three problems i have a way of writing it during contest and but i guess this is great practice then right one two three four um what am i returning okay so then here let's print it out the center now hopefully every step of the way um there should be some cycles until we get to the very end maybe that's okay so this is good after three and then after four where's the four oh because we go back because it's passing the left first that's fine and then now the tail huh that's so weird so the tail was three presumably maybe my recursion is just weird now whoops rented here all right we have about 10 minutes before the contest so this is good to maybe get out of the way maybe uh okay yeah the tail is three so then what why is it wrong to because that node so now we do recursion and now we're at the four right except for that we go to here right after we go to the four um tell that right as you go to node so okay till that left as you go to none and so the current tell that left is not the current tail dot left is equal to okay the tail note is three is the non-local thing like is it am i is the non-local thing like is it am i is the non-local thing like is it am i doing that wrong i'm trying to think it's possible that landlord this is why global things are always a little bit tricky because uh this thing i wonder if this so i do this thing to move to the next note but i wonder this thing like um like i wonder if there was some timing thing where on the four like if you were to draw the tree and i could show the tree real quick um i think maybe it's because when i'm at the four it already set up the um the tail variable maybe and therefore the tail is still pointing at the three and it has some like weirdness about that let's see that's true i mean i don't know how to show it though yeah so this is the tail so tell that right we set it to node right yeah so that looks okay oh no treat that note yeah i mean we knew that oh wait what i didn't finish writing it that's a little bit awkward actually okay so that's good is that good though i thought i had this didn't i have this hmm okay let's give it submit again and hopefully this is good okay so i just had a silly mistake these things are very tricky when you're trying to reuse memory and that's why um especially in competitive you know there's no benefit versus o h space versus o n space in competitive obviously in an interview of h is of height and o of n is linear and that's just better right um for type of h and that's what i have here um the reason is because we're reusing the existing inputs data um so in place if you will to convert these nodes um with an o of h height space for the put it in ordinance for the recursive stacks core stack um so this is going to be or page space um yeah and this is always going to be of end time just to be clear we're talking about the space optimization um because uh yeah it's always going to be linear because you have to look at every node right no matter what um yeah that's pretty much all i have for this one it's a little bit jike's uh linear time of h space and yeah i'm just going to take a quick look to see what i did in the past oh i did do it and i did i was this is the way that i was gonna do it but i think this would take me too long to come up with um just doing the left most and right most and then just like play around the note um this is also of um this is also off and you can probably find that video by the way but this is also of end time and of h space um and yeah and you can kind of play around this is actually more beautiful if you ask me because we don't have to use this globe pseudo global google thing but i was worried about timing um and on this one yeah this one we did the hack with the array which you know so we've done it always but uh but yeah all right i really gotta run obviously because the contest is starting soon so yeah stay good stay healthy to good mental health happy holidays for everybody uh i forgot about it but uh you should okay uh take care bye
|
Increasing Order Search Tree
|
prime-palindrome
|
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9\]
**Example 2:**
**Input:** root = \[5,1,7\]
**Output:** \[1,null,5,null,7\]
**Constraints:**
* The number of nodes in the given tree will be in the range `[1, 100]`.
* `0 <= Node.val <= 1000`
| null |
Math
|
Medium
|
2202
|
172 |
A hello hi everyone today.the problem hello hi everyone today.the problem hello hi everyone today.the problem rose from his factorial lover so solidification method number 3 minutes to find type center factorial 22.10 type center factorial 22.10 type center factorial 22.10 simple subscribe this ₹1 90 lipid 15 subscribe this ₹1 90 lipid 15 subscribe this ₹1 90 lipid 15 days theater response 10 glasses 1200 its spirit has given us 210 basic perfume Key Problem Solve Heart Connect Utility N Number Subscribe This Question Number Of Traveling Across Meanwhile For The First Time Find The Factors Of 02 That Britain Is Time Two Factors Like Point To And Hit Soe Previous Number For Money How Many Times The Five Is Firing Minute Dam They Can Find Shop For Traveling Across Haryana Number Should They Give Some Example That To-Do List Should They Give Some Example That To-Do List Should They Give Some Example That To-Do List Twitter Feed 100 123 45678910 Soen Shifted From Time Here In This Have To System 512 Subscribe Vinit Next Day First For Any Point 10 Aa Jaye So Species From Here Any Point 10 Minutes Pimps And Off The Number In More Full Two And Half Inch K Ricardo 409 The Number Of Times They Get A [ Times They Get A [ Times They Get A The The The Biggest Hai Hua Tha Rallying Se Rosa Rangers Ki More Per To U The Site Is Technically is a good man too ten equal to gain equal 2.5 many congratulations close to this deal 123 45678910 1234 1516 600 800 to 1000 five years in aa 5.11 hair end 502 chennai 5.11 hair end 502 chennai 5.11 hair end 502 chennai 153 shyam bin adhuri subscribe 10 min times can able to find out how many times Pair Saugandh Soayenge This Rumor Is Here Anywhere 25-09-2013 25-09-2013 25-09-2013 Difficult Complete Saurav * Is It Difficult Complete Saurav * Is It Difficult Complete Saurav * Is It Means A Like This Girl Nickle 225 Add Ho The Wind Goes In Its Profits 205 My Device Infidelity Plus Has Protein More 102 A Pan Thought platform master plan is more but english's return is china study repeat anil the indian nation but whose typing is condition more continue until disturb na 10.55 10.55 10.55 in special number of telling sir 's every soldier wine quality factorial sour pair 's every soldier wine quality factorial sour pair 100 feet next test wicket 12345 600 100 gram service match sphere's against all norms but media the course of equal standing meeting 190 citric farmer's opposition to calculate the intelligence of total is amen not letting it will make more time complexity listen start Viniyoga distic hair to solve in this manner so Hua Tha I Want A Well That Enigmatic Dr. That I'll Aamir Loongi Ticket Counter Intercontinental 0 That And Every Time Watering Is Important Will Do It Is A Way Okay Means A River That In Divide And Wi-Fi On Every That In Divide And Wi-Fi On Every That In Divide And Wi-Fi On Every Time Vwe Lahar * Time Vwe Lahar * Time Vwe Lahar * Hua Hai Main Tumhare Kantak Jai Hind A Minute To Aa [ A Minute To Aa [ A Minute To Aa Ko Update Thi That Invalid Tenth Class Physics Hair Pack But Knowledge WiFi Me To See In The 5th And Verified Cube Solve Veer Find For A Fight With joy and election 2013 that the commission handed over the admission form and a well written account all skill development in the like android fair and android fazinil dharmidas hundred every time you will be amazed rule to pawan lakshmi tight ho ramdas hai samsung mark dedh Ya Idhar Option Thank You So Much For Watching So If You Like This Video Please Like Share And Subscribe To Ke Sangi So Much
|
Factorial Trailing Zeroes
|
factorial-trailing-zeroes
|
Given an integer `n`, return _the number of trailing zeroes in_ `n!`.
Note that `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`.
**Example 1:**
**Input:** n = 3
**Output:** 0
**Explanation:** 3! = 6, no trailing zero.
**Example 2:**
**Input:** n = 5
**Output:** 1
**Explanation:** 5! = 120, one trailing zero.
**Example 3:**
**Input:** n = 0
**Output:** 0
**Constraints:**
* `0 <= n <= 104`
**Follow up:** Could you write a solution that works in logarithmic time complexity?
| null |
Math
|
Medium
|
233,809,2222
|
824 |
okay let's softer this coding question 824 goat Latin as you can say the question is quite long it doesn't get a lot of likes because nobody likes reading comprehension questions whether they think they are getting a coding question I guess so but the question is easy so the all we need to do is pretty much just read through it and understand what's asking what it is asking and don't make stupid mistakes so the question reads s and s is given composed of words separated by spaces each word consists of lowercase and uppercase letters only we would like to convert the sentence into gallatin and the rules of this Latin language as follows if the word begins with a vowel we append ma to the end if the word begin was a constant we shuffled the first letter to the end and then at ma so no matter which case it is we always have to add ma if it's constant if the word start with constant we have one extra work to do to shuffle the first letter to the end and no matter which case it is the word belongs to we have to append some numbers of letter a to the end of the world depends on the word index in the sentence so if it's the first war we add one day if it's a second word without two days so we have to return the final sentence that's being converted by according to this rules so the example we have here I speak Latin the first word is I so we add ma and just one day because it's the first award the third word is not a goat we shuffle the G because it's constant to the end append ma and are three days because gold is the third word in this sentence so the solution the strategy of surveillance is to basically split the words by looking at the spaces and for each of the word we apply this transformation and in the end we stitch or the transformer words transform the words together and return that host ring so in terms of complexity it's a clear or linear time algorithm because the when we separating the words out we just do one linear scan to fire into the spaces and just chop the sentence into pieces that's a big a string into little pieces when we do this word transformation we check the first two location and app and pan-ma or first two location and app and pan-ma or first two location and app and pan-ma or we can do the shuffling so either one of those is linear time and with respect to the word so as a whole because we had processing word individually the this processing in total will still be linear with respect to the length of the sentence and again in the end that the when we piece together the strings together it's a linear time as well so that's pretty much we are going through the string three times but you know the constant is we basically chop that so it's still linear whispers in terms of time complexity in terms of space we need to separate or we need to store the individual words so that's also linear with respect to the total ends of the input string and we actually need more or more than that for the because with the number of words growing the number of A's we append to that is it's growing but generally speaking I think it's a proportional linear linearly proportional to the length of the input sentence so that's the time of space complexity I have in my hand so let's coat this thing up so basically we just returned the width will have a like a transform function transport word and we need the index to know how to process split by default which split by the empty strings by the space and the we start with the index 1 so that's gonna be the main processing logic the men-men part we chop logic the men-men part we chop logic the men-men part we chop the sentence into individual words and adding some index information zipping the info indexing information with individual words and we will apply this transformation to the word in the end we piece together all the transformed words all it reminds us to code this transformation function which take a word and the index so if the first a letter character is a is involved what we need to do is to append and may to it but if it's a constant we should remove the first letter app and append it to the end and also then add ma so basically no matter which case it is that we always have to append ma and also the number of A's depends on the word index so that's no matter which whether it's a valve or it's a constant start with about you start with constant this thing is what we need to do the only thing only extra work is that if the word is not start with a vowel sound we should shuffle the first letter to the end and the for the vowels we would just have a set so that we get a constant two-time so that we get a constant two-time so that we get a constant two-time lookups otherwise we'll have if we just directly checking whether this thing is in the string AEIOU then you will be order of ten but if we have a set it sought of one but the order of time isn't still constant you can are get for that so this should be the solution yeah the words so that's it for today
|
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 |
787 |
it has been asked by Tik Tok Amazon Snapchat Bloomberg Oracle snowflake Cloud era Google Airbnb Facebook Apple Cisco cang Microsoft hi guys good morning welcome back to new video I hope that you guys are doing good in this UNC problem cheapest flight with K stops and again this is not going to be other see the separating or differentiating factor between our and other videos is we will have something different in this again for those who want to get the company tution please skip the next 5 10 seconds in which I will tell what I teach in this video we will see from entire scratch what is D how it is actually done entire dryon of that why it is actually not useful and then the improvise BFS approach let's start off and again it's the entire D which will be happening in front of you if you don't even know I'll show you okay the video which you can recommend to learn that and but still in the like this is the only video which you would be need like needing to watch I was like cool uh cheapest flight with K stops it says that you there are n cities and these cities are connected by number of flights by so far Itself by seeing the picture itself we would have recognized it's a problem of graph still we will read the question now you are given an array of flights where basically each flight says okay from to with this price so this flight Will Go On from this zero City to one city with the cost of this 100 okay and basically it has from two with the specific cost which is price now I'm also given three integers Source destination and K which means let's say this is my source this is my final destination and I can take at Max K stops like in the actual um while booking the flights in Google flights or basically any other flights you must have seen that they shows okay non-stop or onetop two stop so if you non-stop or onetop two stop so if you non-stop or onetop two stop so if you can afford to have at Max let's say one stop so you can choose either zero stops or one stop let's say so that is it is saying okay if the person has a demand and he has a request that I want just at Max K stops that's it so you have to tell him what is the cheapest price he has to pay right and again he can accommodate K stops at most K stops he cannot go beyond K stops let's say if he ask I can do one hop or one stop so you can give him the flight with zero stops or one stop you cannot give him the flight with two stops because he cannot he don't have that much time so the first obvious thing is that okay cheapest price is the smallest cost I can represent the same thing as smallest distance right I'm just trying to relate it with what you know right so smallest distance from source to destination so it is nothing but single Source shortest path problem now as soon as you saw this word you know you can apply simple D that is you had been learning so far right and if you don't know D you can watch this simple video in which you will discuss we will discuss about Tas and F version but entirely in very deep T I have explained here itself but let's say if you don't even know Dyas still in this video you will learn about Dyas also now uh what will happen that if you want to apply simple D Stars what you do you just take smallest distance node obviously smallest cost node right so in the very beginning I will push in my Dias the distance of zero and the node of zero right and then okay I will encounter this only one Edge so I encounter this and I'll put that in my the data structure used in Dias or basically the data structure use in designing a d algorithm is priority Q or Min Heap because you want to get the minimum distance out this is distance this is node so we want to get the minimum distance out because we want smallest or shortest distance again I have replaced my distance with price with distance anyway both are same so I will insert that my me and say okay 100 is the cost to go to what one node again 100 is from the node zero and from the node zero existing distance was zero so now he will say okay bro I have taken one stop and now I have reached 10 And1 which means 100 is the cost and node is one now again I have another okay R in one stop is done so shall I stop bro stop meant okay one stop Final Destination which means okay my steps to reach will be one more than the stops so this is actually the steps which you counting okay One Step done and Next Step will be final Final Destination so stops although you have completed your stops your stop was one but still you have stop is something about stops is and like something in between steps is completing so we can easily say that our steps will be stops plus one so I can do one more step right because I have done one stop and lastly I can do one more step so ultimately if I want to do one more step I know I have two options either I can go here or here and I as I know that okay I'll use Simple my priority Q then I'll use 100 and this will actually become a 600 + 100 it will become a 700 and I have + 100 it will become a 700 and I have + 100 it will become a 700 and I have reached a node 3 and this will become a 200 and a node 3 now you have seen that you have reached in a shortest distance again you are always keeping track of the shortest distance and thus you can see that you have reached your finalization so you might end up saying okay AR I'll simply apply my T class but that can be wrong although you can simp say I apply Dias and this I'll solve my answer so by simply applying D you can simply say that my time complexity is O of e log e now firstly disclaimer people just read and just have an imagination that the complexity of Dias is O of V + that the complexity of Dias is O of V + that the complexity of Dias is O of V + e log V that is what people think right actually if you have not derived this you will end up seeing that okay maximum number of edges in a node in a graph can be v² so the actual thing is it comes out to be e log e then maximum e can be V Square so we replace by V square and log of V square is nothing but 2 into e does it actually becomes EOG so please understand how backward thing work and okay you don't even need to do entire dry and stuff just dry like proof and stuff of your complexity just entirely dry run on any complex structure which means let's say if I ask you what you want to find the complexity just dry run on this and see that how many edges you are traversing and how many nodes you are traversing because you can see there are many edges rather than nodes are less so with that you can easily derive the complexity of D now coming on back we know that okay we might end up taking but it's a very simple example D has worked here but maybe not in future so let's say I take a new example that this is my graph this is my source this is my final destination now I ask you I can take only two stops again remember when I say two stops I can take actually three steps like when I said two stops which means okay one step two step three step this is valid again I have taken three steps stops are two one and two stops are two and other steps can be okay one step three step sorry one step two step and three step again there are possible again there are many ways you can also go from here somewhere but yeah remember steps are more one more than stop and you are taking steps and not stops now uh if you apply a simple priority Q here again then okay I will have my source I will initialize okay distance is zero source is a simple a distance I mean we keep track of distance and node then we will simply grab out the minimum element so I'll grab out the minimum element now if I grab out the minimum element I will just simply say bro uh I grabbed out minimum which was this itself so for him the distance is zero and then I will just push on its neighbors are B and C and if I say B is at one distance away from my D and it is five distance away from my D so I'll just push in one b and a 5 C now in my priority minimum element is 1 comma B so I'll just grab this 1 comma B and then I'll say Okay distance of B is 1 and then again I'm just going on again and again now I can simply say bro um then I can just simply push back its neighbors a is already visited so I not push back it now B is not visit sorry C is not visited so I just push back C with the distance of two okay distance of two I just push back my two and C again as I grabbed out so next element two will come in right if two will come in so two distance of C will become a two and then with because we are always keeping track of the minimum distance if we grab out the priority Q now again remember our aim was that we have to take two steps now one step sorry two stops which means three steps one step is done second sorry second step is done sorry Second Step was done here itself when we take from here to here now in the third step this is the last step which I can take again we will gra the minimum distance element and thus I can see okay uh I can go here and here so it will become a distance of 3 comma D and this will become a distance of 12 comma e so you might end up saying bro Arian I have reached my final element which is e so and the minimum distance and I have always been taking the minimum distance so far because I was using a priority Q So my answer is 12 for E bro sorry it is wrong why it is wrong because if you see okay so far you know that by your answer of using a priority Q by using existing priority Q you are using a distance and element or node this is what you are using now I'm saying it is wrong and how I can prove it wrong simply by showing you any other path with three steps again two stops which mean three steps with three steps having a lesser distance or lesser cost so I'll show you now if I take a five 1 Step + 1 6 + 1 7 now if I take a five 1 Step + 1 6 + 1 7 now if I take a five 1 Step + 1 6 + 1 7 with a cost of seven I can reach here so your 12 is a higher cost so your answer is wrong you are wrong now AR in okay which means I cannot use a PRI no you can use simply which means you can use your K still make sure what was causing it to be wrong if I ask you what was causing it to be wrong what you choosed minimum distance okay minimum distance and then minimum distance this is what you choosed right now I'm saying choosing minimum distance is not a bad thing because ultimately your Mak your aim is also choosing minimum distance but one thing why didn't why did not you try this path because you are only grabbing the minimum distance you never concerned about these steps okay maybe I could have because if I ask you to reach here if you have to just reach here then one and one it would have been much better but this 5 1 and one this is much better so you must also see that what is missing in your aim in your M what is missing so now I realize that okay this is wrong it will not work minimum distance I figured out it is seven why this specific path now I and firstly the exact same thing I showed you above also the proof of the actual complexity of the exra please uh just know that part because it will be used in further complexity analysis that what you will derive again you can easily say the complexity of D exas is e log e it is not e log V it is or you can say it is 2 into e log V it's again same as e log e also now um you know one thing that you have to change something or add something or do something what was missing in your above approach did not consider the steps it considered only the distance how would I know that my Approach did not consider the steps because bro at every point of time you only focused on distance you never focused on steps which means if you are focused okay in one step how much is the minimum distance I can cover to my final destination point considering him as the final destination so kind of I also parall have to keep track of steps because I saw that okay in two steps I can say that at a point C again my answer is linked with the steps itself for example in your once again I'm not saying stops I'm saying steps make sure that part so I'm easily saying that okay in two steps my minimum distance to reach C was actually two 1 two but if I had to do only one step then my minimum distance to reach my point c will be five so my minimum distance is dependent upon the steps itself so rather than taking only distance and node I will also take the steps itself now let's see how we'll apply the same D star again so I take distance node and steps with me so in the very beginning I am at a node sorry distance is zero node is a steps is zero itself no steps taken now I from a I can go on again I will still use my priority que I will still use my main heat but now again my main aim of using a priority Q is to get the minimum distance out but I'm also using steps now so I will always gra the minimum distance but I will operate on steps I'll keep track of the steps my main operation will be steps so what I'll do okay and again this can be very confusing for those who have not learned D FAS ever so if you want the final solution go and watch the like last part which is the uh which is the BFS but who are very curious to understand the basics of Dias then watch this video that will actually clarify all the routes now we had our a very beginning okay we removed it and then we passed in and pushed in all its neighbors neighbers are two a sorry uh C and B again B at a distance of one so B at a distance of one B node and steps are one now C at a distance of five and steps are one now again I will simply prior PRI priority prior I still apply what I'll do is I'll again grab the minimum distance element I'll grab this at the next step right simp same priority q but AR in where's the steps gone bro that is the difference I'll show you in the existing standard what you were using earlier so what you were doing if you encountered a node having a lesser distance then you skip it what you were doing that time right if you encounter a node having a lesser distance and you are getting on that node again you just simply skip that node but in the modified Dias when you also have to keep track of these steps or these stps then I can simply say that okay if you encounter a node with a lesser distance and lesser steps then only you skip that if you encounter a node with a lesser distance but lesser steps then you skip that if you encounter a node with let's say more distance but lesser step still you keep that if you encounter a node with the Lesser distance more step still you keep that so that is okay if you encounter a node with the Lesser distance and less only then you actually skip that Noe we'll see with what we mean so okay in this we saw that okay 1 comma B comma 1 which means one distance B node and one step will actually be taken out so I can simply say so far my steps for a was zero and again at every point I was Landing onto a node I was checking I land onto a node okay steps were taken as zero for him then next again and make sure Landing onto a node was on the basis of distance and you are keeping track of the steps this is what you are doing you are landing onto a node on the basis of distance because you are using a PRI CU so it will gra out the minimum distance but you are keeping track of the steps so both things you are handling at the same time now okay you grabed the steps okay b came in here now next time what will happen again he will go out he will put push back its neighbors neighbor is only C because a is already visited so he will push back and say Okay C distance of two c and steps are now two so now minimum distance in the entire priority although you have C also waiting here but he has distance more so he will not get out of priority Q he it will give 2 C2 so I will grab the and put the steps of C as you can see the steps of c are actually two steps of c are two and that is a fact I grabbed in the node C again let's say if I want to if I would have asked you bro if the stops required would have one if I would have asked you stops required would have one which means steps required would have been two which means as you can see one two steps so as you have reached on the Node C and maybe the node C would have been the Final Destination node so you know that you have reach the node C with the minimum distance always keeping of the minimum distance so you always know that you have reached C with the minimum distance and also you have also had the sufficient bandwidth of using these many number of steps so you can simply return the answer from here itself that for C the minimum distance or minimum price will be nothing but two but let's say you know your entire problem basic problem it was nothing but existing problem itself you have two stops which means you have three steps and your final destination is nothing but this specific destination let's reach here itself now uh as you saw that we had reached see again we are keeping track of the steps of every node now because distance is keeping is kept in the prior toq now in The Next Step I'll remove my C and then I'll grab the next node for c neighbor are d and e so I'll push back the neighbors of DNA D will have okay a distance of three uh a distance of three node is D and steps are three for example and the same for E the distance will now become 12 it will be e and the steps are three again I'll grab the minimum element from the prior will be 3 comma D comma 3 because of the minimum distance so I'll just simply say okay for steps for D steps of D are three and then simply go on then as I do this I will again go and remove my D self okay I have gone no worries I'll again go and remove my D itself because it is a minimum distance element and then I'll push back his neighbors his neighbor will be a e itself so I'll push back and say now the distance will be four because you will see three 3 plus this cost will be four and then a d will be the node uh sorry uh e will be the node and then uh final steps which means three steps plus one step which four step so that will be your steps but bro it has exceeded the number of steps which I could have taken sorry bro this cannot be taken it has exceeded my steps again stops allowed were two so steps required were three I cannot exceed three steps so bro this can never be an answer bro simply continue get the next smallest element okay this is done get the next smallest is five oh bro it is five oh so if it is five then I'll do one thing okay simply remove five oh bro one thing if it is five so I'll get and say okay for node C for steps for node C the steps of C is one steps have reduced all you can see distance is increased but steps is reduced so what you will do you will override the steps you will say steps of c is now a one and because as I told you can override also distance has increased but for sure it is obvious that you came on to node C this step node C later on because you saw that this was like this came first because it has a lesser distance but you can again come back to a node where the more distance but lesser steps again if the steps would have been more you would have ignored that skipped that but here the steps are less so you have to take that into consideration so I'll take that into consideration and then I'll simply say okay the steps of C has now become one now if I just push that so again the neighbors are D sorry d and e so again uh push back d and e with the new distance and the steps have also changed which means D so steps for one so now steps are two and two again as you will land on to the new value minimum value now is 6 D2 so again for steps of D earlier it was three now it is 2 it can still be modified so I'll say steps of D are actually two now again he's minimum he'll go onto its neighbors he'll be removed and he will push back his neighbors D will push back his neighbors his neighbor is e with the steps of three 2 + 1 and then steps of three 2 + 1 and then steps of three 2 + 1 and then new distance which is 6 + 1 7 so now new distance which is 6 + 1 7 so now new distance which is 6 + 1 7 so now this will be 7 E3 now again this steps is inbound now if I check on the minimum element minimum distance everything is going on 12 15 and 7 minimum is seven so simply grab out this seven for E which is the final destination for you this steps is inbound because you can choose three steps which means two stops three steps you can choose this is good which is e is the final destination for us and 7 is the minimum distance which I could have grabbed and thus my answer for this is nothing but a seven and that's how you will just simply add your steps also in the picture and that's how you will simply use your M he or priq or ta algorithm and that's how you can simply solve it with Tas people say it cannot be solved by D but they are just deceiving you in telling it is hard to understand how it will be solved again with this understanding you will be very clear with how Dias is actually working or how it actually works and how we can modify that to use in our requirement but again we will see the improvisation also but yeah that is how it works is pretty simple firstly we had the vector of flights which means flight is from two to a distance or to a prize so we convert that to a graph simple graph F to a t with a cost of D simple adjacency list now if you don't know this part also like basic part of how to convert that to agency list and all that stuff please go and watch B graph series by AR just write on YouTube b graph series by RM you will get the playlist out and that you can watch now we simply converted the array into our graph structure adeny list and then we made the simple priority QR of mean Heap now this priority is nothing but a vector will store distance node and steps by default in a simple D we only store distance and node but now as a modification we will store distance node and steps also and also as you saw that I will keep track of these steps at every point so now I'm keeping track of these steps or you can say stops I have put the stops but you can sa the steps I'm also keeping the steps at every point of time now I'll do exact same stuff while my par is not empty grab out the top which means the minimum distance element from the parq get the distance of that element get the node get the steps and then I will compare from the existing steps if my steps are more there's no point because you saw that I will override when the steps are less when the incoming steps was one and the existing was a two then only I overrided it but let's say if a step of three would have come in I would have never overridden it because if something is coming later on in future which means that it is coming with a higher distance because everything which comes in earlier will have a lesser distance because it's a priority Q so it is actually basic understanding of a priority Q or a taas now if something is coming in future with a more steps please bro simply ignore it or what if you have surpassed the number of steps as you have as I showed you stops are K so number of steps allowed are k + are K so number of steps allowed are k + are K so number of steps allowed are k + 1 so if you have surpassed the k+1 steps 1 so if you have surpassed the k+1 steps 1 so if you have surpassed the k+1 steps bro please continue you cannot this is not a good thing continue now if not then please override your number of steps okay I overrided that if you had re reached your final destination okay if I have reached the Final Destination simply return the minimum distance because this is right now the minimum distance okay simply return that if not then simply keep on pushing that in your priority CU simply go on to the neighbors and simply say bro distance plus price at the distance plus price and then simply neighbor and steps plus one although you can also want to add if condition you can also add that if condition which you use in the standard D you can also add it here but that will not have much effect and that's how ultimately you will simply return your minimum distance if you are able to encounter your destination if not then simply minus one and that's how in again in existing D St it had a complexity of e log E I proved you also if you are in the uh Habit of saying e log V I also proved it is e log V also I Prov that also above but now instead of e we actually going on to and trying for all the keys because earlier your uh your node was containing your distance and your node itself and then you were saying you will go on to every Edge and try for every Edge so you were seeing it was e log e now we just added one more thing which was steps now I'm saying I had K steps so now it will increase by K complexity so it will be e into K log e into K and again we usually add a plus v also if you had known that we also write V plus e log like this we also add a v why this V is added because if we say that the graph is disjoint which means the graph is let say have no edges at all but nodes so that's the reason we always add a v in the picture right and the same way space used again same way space used will be e into K plus v again for the same thing that disjoint will be there but the main thing is that ear it was e log e now it will be e into K log e into K this will be the complexity of your D but again D can be implemented but now Aran um can we improvise it or maybe and if you are not much good with d star you might you must have gone overwhelmed with how D star is working how it is know all the stuff that can be very simplified if you understand that again I taught you D because the first intuition was single Source shortest path thatas we always go by intuition then we go by improvisation right so first intuition was Dias itself that's the reason I taught you Dias but it can be improvised by very easy way by simply using XYZ algorithm how let's see so if we look back and saw what happened ultimately while you were trying dice CL remembered we had steps as zero for a steps for b as one then steps of C again came as one then you saw it got overridden why because in future steps okay for a Step Zero step one will be this step two will be this step three will be this if you remember this is what ultimately I was going to try right the same way as we are moving levelwise okay one step two step three step Why Can't This be done by simple BFS which is breath first search level wise right so that's the reason I simply apply a simple BFS in this and again in simple BFS you always go stepwise now Arian if I apply simple BFS and as soon as I reach my final destination shall I return the answer no why because if you apply a simple BFS okay let's say I erase this if you apply simple BFS and again in a simple BFS you will also have to keep track of the minimum distance but let's see if you try the again don't mix and match BFS and T they have a slight difference of how they work I'll show both of them but there's a slight difference your BFS always go levelwise it does not consider the distance you have to manually put the distance as minimum so you have to manually put an array or a vector same distance and that array you have to minimize but in PR or Dias You by default always pick the minimum distance element so here if I go the minimum so if I go in a BFS way for him the minimum distance will be five for him will be one then if I'm saying I'm allowed to do let's say if I said okay my stops are not allowing me this is maximum number of steps which I could take okay stop here so for this answer is this but if I can do more steps okay do one more step okay this will actually be improvised this will be improvised so it will become a six it will become a um two so now if I say okay now the steps are stopped okay so for C answer is two for D answer is six you saw I minimize the distance here earlier I was minimizing the steps because I was using a priority by default take takes the minimum number of distance Sorry minum by default it takes minimum distance but now I am taking my BFS it goes level wise so level wise I am minimizing my distance okay then in the third step I can say okay for this the distance is three for this the distance is 12 minimize the distance for this the distance is my 7 for this the distance will be 12 so for sure 12 is large so don't minimize it so this will be the distance 7 so that's how ultimately you can say that you will get your minimum distance out cool so just try on for this for all the key steps it doesn't matter let's say as I showed you it doesn't matter if you had reached your destination or not which means if your destination would have been five but you are allowed to do two like two steps which means one stop you are allowed to do so if you had reached five like let's say like this in the very beginning your distance was one and five if you are still allowed again the stops here I'm seeing R1 which means stop R1 stop r one so steps are two which you can take so you are still allowed to make one more step so bro please try it don't regret in future and let's say your destination is C so please try it which means as soon as you try it the destination of C will actually become a two and thus you have minimized your distance so I'll do the exact same stuff dry run again dry run for the first step what will happen from Source you will get the minimum distance for distance of C has become five your distance of has become a one same way at step two your distance of uh D will become a six from five and your distance of C will become a two at step two again remember our ultimate in the from the very beginning the example which I took the same example I am taking again and again for Dias also and for priority also so again it is two stops and the same graph two stops on the same graph right now uh coming on back um so at step two we have done now um we'll just simply go back and say on step three I will say okay from here to here the distance will be a three from here to here the distance will be a 7 from here to here the distance will be a 12 minimum is 7 so return me the minimum distance and bro ultimately you have done three steps don't go more than this again you will try on and do for three steps only because your stops were two so try for three steps only and ultimately return the minum distance so the only change is that no matter what you will do level wise traversal but you will do that traversal until your all steps are exhausted which means you will try for all these steps so the graph remains exactly same now it's uh simple BFS but we are keeping track of node and the distance so I'll keep track of node and the distance and the simple Q I take in for my priority Q now although in the standard BFS you only do while until your Q is empty but I told you that you have to try in for all these steps and keep on minimizing until you can minimize it so you'll try in for all these steps so while my stop is less than equal to K remember your you can actually have k + one steps so even if actually have k + one steps so even if actually have k + one steps so even if your step is K still you can actually have one more step so that you can have k + one step so that you can have k + one step so that you can have k + one step so it's the reason we have equal to here now uh as simple BFS we grab the size because we want to have a level wise again there are many questions in which this thing is not required but I highly say please follow a standard pattern for all the BFS approaches always go levelwise this indicates that I'm always going level wise I'll complete one level first and then only I'll go to my next level which is the basis of your BFS now until your size is not empty grab out the front element remove that from the queue and then simply go on to all of its neighbors you have to minimize the distance so check if the upcoming dist Price Plus distance if it is more than the existing distance of the neighbor continue bro continue because I have minimiz I have to minimize it I don't have to increase it so and if it is not continued which means it is less if it is less bro simply update the distance of your neighbor by Price Plus distance and push that new distance in your right Q itself and thus you will just simply keep on pushing but you will try for all these steps and ultimately if your distance to that specific node which you wanted final Final Destination you wanted if it is infinity which was the by default value then you will simply say minus one else you will simply say distance now complexity for this earlier you know that your complexity for a simple BFS is you go on to all the edges which means your simple BFS is O of V plus C but now you know that you have to go and try for all these steps also so even if your Edge or your node is visited still you will have to visit that edge again because of your steps because you have try for case steps all like no matter what you have to try for K steps again and again so it will increase to e into K in the same way space will also increase to e into K and that's how you can actually solve with your BFS and the entire thing is okay you have to try for K steps for sure cool by that you have seen both BFS and D approaches uh it took a lot of time to make this entire stuff uh so I'll highly like it if you can just like or smash the video cool thank much for watching bye-bye goodbye thank much for watching bye-bye goodbye thank much for watching bye-bye goodbye take care but make sure this video was for the ones who want to learn Bas very carefully because no one I repeat no one on YouTube has taught this portion they have just made the video but no one cool bye-bye thank you but no one cool bye-bye thank you but no one cool bye-bye thank you goodbye
|
Cheapest Flights Within K Stops
|
sliding-puzzle
|
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`.
You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`.
**Example 1:**
**Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1
**Output:** 700
**Explanation:**
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops.
**Example 2:**
**Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1
**Output:** 200
**Explanation:**
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
**Example 3:**
**Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0
**Output:** 500
**Explanation:**
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
**Constraints:**
* `1 <= n <= 100`
* `0 <= flights.length <= (n * (n - 1) / 2)`
* `flights[i].length == 3`
* `0 <= fromi, toi < n`
* `fromi != toi`
* `1 <= pricei <= 104`
* There will not be any multiple flights between two cities.
* `0 <= src, dst, k < n`
* `src != dst`
|
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
|
Array,Breadth-First Search,Matrix
|
Hard
| null |
152 |
hello guys I'm in this video we shall see another problem on code maximum product subarray so given integer array find a subarray that has the largest product and WR the product so let sech and it they will the answer it will fit in within the 32bit integer so we not to worry about any overflow condition here because they given it's a the answer will be within 32 integer only so given array we have to find the maximum product subar what do you mean subar is nothing but if they given let's say array 2 3 4 5 so 2 3 4 can be sub 3 4 5 can be a sub 34 can be a subarray but if you pick the elements 2A 5 no this cannot be a subarray so subar is something it's a part of the array where the elements are in contigous order so you take some portion from there that's what you're not picking some elements from there if you take 2A 5 it's not continuous so this cannot be a sub this in this case it will be a subsequence so in the question what they have told is we need to look for the maximum product in the subar we have to find a sub such that the product will be maximum so let's split the question into different conditions okay in the beginning the integers can be either positive negative or zero three conditions we have first let's say what we have the uh array with only positive elements so if it is only positive then maximum product will be nothing but product of all the elements yes so product of all the elements so this is first condition so next we'll uh check into part where we have negative integers so negative integer in there two cases will be there one will be negative integers odd number of negative integers and even number of negative integers if we have even number of negative integers let's say - 3 - 4 of negative integers let's say - 3 - 4 of negative integers let's say - 3 - 4 and 5 so in this case if you have even number that means uh when you do the product since we have even number of integers -3 into we have even number of integers -3 into we have even number of integers -3 into -4 will give you 12 so 12 5 are 60 2 -4 will give you 12 so 12 5 are 60 2 -4 will give you 12 so 12 5 are 60 2 are 120 again positive will be the answer so we need not to worry about this condition also but what if we have this is even negative okay so even negative positive and odd negative is nothing but odd number of negative integers in the array so if that is the case so let's say two - 3 4 and five so if we have odd number of negative Ines then yes now since we have only 1 - 3 if you multiply with all the only 1 - 3 if you multiply with all the only 1 - 3 if you multiply with all the POS numbers the resultant will be minus negative in this case so here the maximum product will not be that so here what we do is we can split the array such that minus 2 this so either two here and four 5 are 20 so which is the maximum product we getting from the subar 20 so return 20 so if you have positive integers in the AR directly find the product if you have negative integers in that case if it is of even number of negative integers then we can find the SU maximum product directly by multiplying all the numbers but if we have all number of negative integers then we have to look into condition where if you find any negative number till there two will be there after that again 4 5 are 20 so 20 will be the maximum product the last case positive over negative over zero what if we have zero if 2 4 5 let's say if you have zero again same as negative only so split because if you multiply if you found any zero integer in the array then if you multiply any number with zero reserve the maximum product will be become zero so you have to take care of this condition also so here two here 4 20 again 20 is the answer so one thing what you can notice here is uh if it is positive directly find all negative even number yes okay zero means whenever you find a number that is with Z or negative what you do is if you find the number of uh the number at this position is either zero or negative then let's say if product is initialized to one okay so if you find any number here product will be two right so once you find negative re initialize product one similar in this case also if you have product equal to one here two here you find zero re initialize product equal to one so that in the next iteration next elements you find a correct product so each time you calculate max product let that equal to Max product comma product so max of those two Max producta product so again once your initial product equal to one then you can multiply 4A 5 because they are all greater than zero but how do we get to know whether we have even and odd number of positive Ines so for this what we do is if we have the array let's say two - is if we have the array let's say two - is if we have the array let's say two - 3 4 5 let's find the sum from this side okay so 2 into - 3 so here two at this into - 3 so here two at this into - 3 so here two at this position here you get two so when you do the next product uh 2 into -3 it will be the next product uh 2 into -3 it will be the next product uh 2 into -3 it will be - 6 then 2 into - 6 into 4 that will - 6 then 2 into - 6 into 4 that will - 6 then 2 into - 6 into 4 that will give you -4 then 24 into 5 20 120 okay give you -4 then 24 into 5 20 120 okay give you -4 then 24 into 5 20 120 okay so you got 120us 120 as answer and in between product whatever you could if you find the product from uh right to left five you have here 20 okay and then uh - 60 so then uh - 60 so then uh - 60 so - - - yes so in this if you see the all the products are you getting anywhere the maximum product for this sum maximum product will be nothing but 20 yes you are getting it so how does it work actually why are we performing all these operations like you're performing sum from left to right product from left to right and right to left and in between you're finding Max that how is your logic is so let's say we have an array okay we have taken only the with only one negative so let's say 2 - one negative so let's say 2 - one negative so let's say 2 - 3 1 uh - 3 1 uh - 3 1 uh - 4 3 - 2 5 so if we have this array 4 3 - 2 5 so if we have this array 4 3 - 2 5 so if we have this array right in this you could see three negatives are present so in this three negative If you eliminate one of the negative integers so one of the negative integers which it could be let's say minus 2 is the minimum one right so let's minimum the sense if you take two that is the minimum number so then this and this you can get here so this will F you maximum Product 2 into - this will F you maximum Product 2 into - this will F you maximum Product 2 into - 6us into- be plus 4 3 12 2 24 into 3 6us into- be plus 4 3 12 2 24 into 3 6us into- be plus 4 3 12 2 24 into 3 so that will give you 72 so in this case it was 72 here it is five so which is maximum this 72 okay now we have excluded two so let's say what if we exclude three so here one so in this case two here what is the product here so minus into minus plus no8 42 8 3 are 2 24 into 5 so 5 4 are 20 120 here you got the maximum product so again if you exclude four also there also two thing one is from here to here another is from 3 - 2 5 that will give another is from 3 - 2 5 that will give another is from 3 - 2 5 that will give you 5 2 10 it will be negative of course so we will not take into consideration 2 into - 3 into -1 again negative because into - 3 into -1 again negative because into - 3 into -1 again negative because in this partition if you do minus 4 1 netive 1 that will so maximum prodct 120 we have form but if you implement the same thing with finding product from left to right and right to left you will get 120 as an answer so actually what we do is see if you have even number of negative not it will not be a problem because maximum product will be product of all the integers in the array but if you have odd then excluding one is enough remaining what will happen if you have three odd if you remove one integer from that if you exclude one integer and do the partitioning and if you find the product on both the sides so that product will be either from left to right or right to left so it won't be in between for sure right so if you exclude one from this two will be negative integers and that two negative integers are okay only because two negative to negative will become positive so if we have seven odd in that if exclude one six is even number so it will become the product will become positive again so that is the reason why am I telling we need to find the left product and right product so in between you will get the answer because whenever you exclude one negative integer it is for sure going to make the partition somewhere in between and from the beginning to the some part in the and from the end to the some part in the partition will it will not be in between because you're excluding one negative integer so 2 6 7 8 - 9 2 3 - 6 we have - integer so 2 6 7 8 - 9 2 3 - 6 we have - integer so 2 6 7 8 - 9 2 3 - 6 we have - 7 we have so if you exclude six so this is one partition if you exclude seven again this one partion if you exclude n this one partition only one exclusion of uh one exclusion is enough negative integer you need not exclude two because as I said three are present since three odd are present if you remove exclude one two odd will be there so of course if you exclude n see here two it will negative to negative will become positive product so that is the way we finding the left and right product so we should implement this so in the beginning let's say n equal to the size and then what you need to look for left product and right product initialize it to one and yeah then how do we handle what if you do the left product right product in that case if you find zero if you do left product in this case it will uh f z here 2 into 0 everything will be zero again 5 into 4 20 into 0 so how do you handle this so for that we what we do simple case as I said before if you find product equal to Z just reinitialize it to one that's it nothing else so okay like if you find the product equal to Z here you find equal Z from here re initialize it to 1 so 1 into 4 into 5 20 it will be similarly you come from right to left also 5 4 20 again it will become zero re initialize it one product will become two again so that is a simple case which you need to handle so next let's say the answer Max product and let this be in minimum because this is the answer which we looking for minimum value will be assign it so later now we'll run the loop write it over the array so first you have to check if left product is equal to Z then we have to initialize left product to one similarly if right product equal to Z then right product also should be three initialized to one so after this is done now calculate left product so star equals to nothing but M of I similarly you find right product equal to right product St of I which is in short return as star equals to Ms of I so now we have to find the max product equal to Max of Max product comma again Max of right product comma left product because since it can't take three parameters in one we will assign it like this so yes we can return the max product here it should be here and S here also yeah we can run this now yes and Java also same logic uh nothing change find the answer so here math. Max we will use so we will submit this also yeah and one more thing uh it's called submitted one more thing which you notice here is um we have found the left product and right product right I have made a mistake in that so if I run Java code is fine here you can see and minus IUS what are we doing so for left product it's okay left to right but if I submit this it won't run now the mistake which I did here is Right product so we will submit and check now yeah so the mistake which I did here is when I find the right product should be from the end of the array to the beginning so how do you get this value here the length is four right this is index zero if you want to get this Index this is nothing but the length 4 - 0 - 1 so third index 0 1 2 3 length 4 - 0 - 1 so third index 0 1 2 3 length 4 - 0 - 1 so third index 0 1 2 3 third index which you need to fch that is n - i - is n - i - is n - i - 1 i - 1 i - 1 i - one otherwise you have to run another loop to find the right product also and again if right product is zero initial is right product to one so we not do that so instead we will do like this so this is simple N - i- 1 because we so this is simple N - i- 1 because we so this is simple N - i- 1 because we stared from zero to index one more minus one is required so now we will submit this and check yeah successfully submitted if you understood the concept please do like the video and subscribe to the channel we'll come with other video in the next session until then keep planning thank you
|
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
|
338 |
hello everyone welcome back to the channel today we are going to do counting bits of lead code so let's understand the question first then we will move to the approach so given an integer n return an array answer of length n plus 1 such that for each i z i is less than 0 to n answer i is the number of ones in the binary representation of i so basically we have been given a number n and we have to return an array of n plus one size okay and any like here we'll try to understand so we have been given like for example n is 2 okay then we'll have an array of 3 now what this will represent 1 2 3 so we need the binary count of ones like 0 in binary 0 is represented as zero there is no one okay for one we represent as zero one okay so the number of ones is one okay then two so for two this is something like that you represent 0 1 0 is 2 so again the number of ones is 1 only so we will return 0 1 ok now let's try to understand how we can solve this let's take a bigger example if we have been given 5 okay 0 1 2 3 4 5 6 so we will create an array of 6 because we have been told okay so i have created an array of six now let's try to understand what we have to written so in binary zero is written as only zero one is written as zero 1 2 is written as 1 0 3 is written as 1 4 is written as 1 0 and 5 is written as 1 0 1 so here the number of ones are zero here the number of ones are one in three we have two knowns and four we have one and in five again we have our two ones so we don't need this okay zero one two three four five yeah this is what we need okay so this is these are the like n plus one six we need now so this is this will be our answer if n is equals to five okay so how we can achieve this programmatically okay so if so the first approach will be we will convert this numbers into binary form and then we will iterate through them and count the ones okay this will be the traditional approach but you will be asked to improvise the solution so how we can improvise the solution is let's try to understand that so if you will observe let's take three as an example okay so if i want to find out the number of ones in the binary representation of 3 if i divided by 2 okay what do i get 1 okay and as we know that 3 is a odd number so what we will do we'll add one also so let's understand how 3 is represented 0 1 okay so any odd number will be having one at its ones place okay and let's see how 4 is represented so 4 is represented as this is 3 and this is 4. so every even number will have their last bit or once bit will be 0 okay so if i want to know how many ones are there in the representation of 4 so what i will do i will divide 4 by 2 we will get 2 right 2 2s of four that is correct so we want how many ones are there in two so we'll come here then again we'll divide it by two okay so we know that in two we have one so we'll write it as one so this will be one similarly if we will divide three by two we'll get one okay and in one we know that it's one it's okay and we'll add one from our side because it's an odd number so the last digit will also have one will be set so it will be two okay let's try to understand this in a better way by iterating through it so zero one two three four five okay zero one two three four five we know that zero will always have zero ones okay now one is odd okay so what we will do we will divide one by two what we will get zero and what we will as it is an odd number will add one to it so we will get one over here then we are coming to 2 we will divide 2 by 2 okay now what is 2 by 2 it's 1 okay and as we know that 2 is an even number we don't need to add anything we'll write it down again coming to 3 divided by 2 we'll get 1 we'll add 1 because it's an odd number so we'll get 2 over here then 4 divided by 2 we are getting 2 okay now we want to know what is a 2's place it's 1 then we'll write it as 1 over here then 5 will divide 2 so what is at 2's place we know that there is only 1 plus 1 we will write as 2 over here okay is that clear so if this is clear now there are two things okay now the simpler what we can do is we can use a for loop okay here what we can do we can simply like if suppose we have an arr as our array what we can do i by 2 plus i modular division 2. okay this is the simplest thing now there is this will be actually very slow so to make it a bit fast what we will use is bitwise operations now what is bitwise operation we are actually dividing the number by 2 correct so in bitwise if we want to divide the number by 2 what we can do there is this there are two operators right shift i'll write it down over here right shift operator and left shift operator so right shift what will it will do if you are using a right shift operator it will divide the particular number by 2 okay it will divide by 2 and if you are doing left shift then it will multiply the number by two simple so what we will do will use right shift so basically this is right shift and for left chip this is the symbol okay so we'll do something like this right shift one so we want to only shift one bit so right shift one and for this modular division we have something called as end operator and we'll do with end with one because if the like we know that one is represented as zero one okay so any odd number will have the last bit of set and if both the sets if both the bits are set then and we will get one so we'll get one from here and this will be very fast i'll show you on the lead code that how these two things these two approaches makes difference okay so let's try to initialize the array first okay the size will be n plus one let's try to run the for loop and i is equals to now as we know that by default arrays values are 0 so we are not doing anything for result 0 because we know that 0 is already there okay n plus 1 and i plus simple so what we will do result i is equals to simple i by 2 plus so whatever is at i by 2 that's this is what we will do whatever is at i by 2 and to check if it's an even number or odd number what we'll do modular division so if it is divisible by 2 we'll get 0 and if not then we'll get 1 only at the end we will result we will return our result array let's try to run this code okay i'll explain you the difference between using this divide and modeler and the bitwise operator so as you can see that it's running in one second and better than 99 of the online java submission now let's try to change this by this and change this by this okay and also now this 2 will be changed to this and here 2 will also get changed to this so we have used now bitwise operator okay earlier i tried actually so it took 3 milliseconds for the normal one and one millisecond for the bitwise one so let's see now what will happen we have a wrong answer why do we have a wrong answer is i and is it this maybe i have made some mistake it is saying area out of bound index out of one exception okay i think what is the issue let's try to understand this let's try to submit this again oh it's work it works perfectly fine so as you can see that so we have used so for using the end operator we need to use the brackets okay so if you like the video hit the like button if you are new to the channel subscribe to the channel if you have any doubts comment below in the comment section thank you so much for watching this video bye
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
946 |
so guys this is the polyglot programmer i haven't made any videos in like a week i've been really uh studying a lot um but uh i'm still doing exercise though i'm just not doing so many videos to be honest uh i make these videos because uh one i wanna try to help people that are struggling with this exercise just like i am and another reason is because when i try to explain it to you guys it helps me also to understand so i think that's a very good way to learn and if you don't like making youtube videos uh maybe you can just try to explain the solution to a friend and that also works and another reason is because if you want to try doing some coding interviews uh on those interviews what they say one of the biggest tips that they give you is that they want you to think out loud right so you they want you to be able to explain the solutions so you kind of need to practice that because when we're actually coding by ourselves we don't usually talk out loud right uh so it's good to get some practice with that so uh so yeah so today i'm gonna go about this problem so the problem is validates text sequences uh it's not a very complicated problem but it you do have to think a little bit and you kind of for this one uh i used a greedy approach which is um you basically uh you basically keep trying uh different solutions until you find the optimal one a rough way to explain it uh that's one i kind of have a hard time to explain it also but this problem is it goes like this so you basically are given two sequences one is supposed to be pushed and the other one's supposed to be popped uh with this distinct values um in from stack so stack when you push stuff the last one stays on top right and when you pop you're going to pop the last one and then the second to last and then the third lesson and so on and so forth so in return true if they could be if they popped could be a result of the push and pop they could be a result of each other right so in this example here for example you have one two three four five and four five three two one well my the first thing that came to my mind when i read this i said okay so i just compared the first to last second to last and i do that with two pointers and then it's easy but that would only work if they were all pushed and then they were all popped then that would make sense but that's not what the case here you actually don't know the order so in this case for example he pushed one push to push three push four and then he bought four so that's why pop came first and then he pushed five and then he popped three pop two pop one so that's why he kind of had this order so he push one two three four popped four push five pop five then pop three two and one so this is the problem so the way i go about solving this problem is uh i keep a count i mean first of all i have a extra uh data structure which i have another stack which uh in i keep a counter so every time that i pop something from this extra stack that i create i increase the counter and my result at the end will be return counter if counter equals my lane of pop so if i popped just as many items as i had here then i'm good then i have a good solution right so let me declare this guy counter equals zero and stack equals nothing so and what i do here is that i'm not gonna is that i'm gonna have a for loop on my push so i'm gonna basically push all the items i'm gonna append all the items from my push to my stack and i'm gonna compare that every time that my last item on my stack is equals my counter meaning that it's not it's at the it's at that point on my popped then i'll pop from my stack my temporary stack and i increase my counter so then i'm for num in and pushed stack append num so i'm appending all of them right and then uh why oh then i do a couple of checks here so why am i why i do have items on my stack because i don't want to get an error here and uh j is also is less than my lane popped right because i don't only want to pop as many items as i have on my popped list right uh and that's this is the important one my last item in my stack is equals the number of the index that is on the number of items that i have already popped so i haven't popped anyone so i'm going to compare first my last item in my stack with the item zero and then if this is true then i'll just stack pop that item and counter plus one and this will work uh so i just want to show you guys like here so i'm gonna get these guys just so just use it as an example before i have to so i have my counter equals zero and i have my stack with nothing right so here and then i'm going to start iterating over my push numbers so i add one okay i do have items in my stack is j less than length of popped it is my last number in my stack equals item zero oh item counter not right i was explaining item counter which is zero item zero in my popped for no it's not and then i add two same thing is two equals zero in my popped no it's not three is three equals 0 in my pop no it's not and then i add 4 is my last item in my stack 4 equals item 0 in my popped it is then i pop this guy and i increase this by one and then i go and i pant the five what anyway sorry and then i go and append a five and now i'm here right my counter is here so is my last item in my stack equals number one in the counter yes it is and then i pop this guy and i increase this okay is two equals my last yes it is and then i pop this guy equals three is three equals my last and i pop this guy equals four and it's four equals my last then i pop this guy equals five and then the length is zero and then i return if my counter is equal my length of pot and if i haven't made any mistakes i have forgot this oh and there you go accept it quite fast i did use some extra memory but yeah still the time complexity here is uh it's def it's all of uh of n because uh i mean i had to iterate over all the la the num the number of items and then all of these are cheap operation they're constant and space complexity is always also oven because i may have to create a guy this size that is the same size as this one that's it see you next time hit the subscribe button cheers
|
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 |
1,663 |
Person January Toilet Today Smallest Traffic taken out and clicked on the table subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page Loot for example in this question in more All Cars subscribe and subscribe this Video plz subscribe 373 subscribe to ki system portal for automation mathematical problem not valid robbers on Thursday and unlimited one pan hai left side effect on a hi mhari heli difficult 12121 and reminded subscribe this Video plz subscribe our loot meeting election difficult this suggestion subscribe to the Page if you liked The Video then subscribe Quite Useless Actors उसे जोर Of Fatal Quite Useless Actors उसे जोर Of Fatal Quite Useless Actors उसे जोर Of Fatal Dhund subscribe and subscribe the Channel Please subscribe and subscribe the Channel subscribe That every person will replace day will just to Thursday subscribe Video subscribe and subscribe the fluid button more off spider taboo and what dresses 6868 1060 6GB subscribe The Channel Please subscribe and subscribe this Video give Video Subscribe 602 Which Time Management Isse Stree Liquid 3 Loot Cigarette Quantity Na Place Deficit Electronics Id Wood Egg Subscribe 6 - Electronics Id Wood Egg Subscribe 6 - Electronics Id Wood Egg Subscribe 6 - A Plus One - 06 Tweet 4 - 06 A Plus One - 06 Tweet 4 - 06 A Plus One - 06 Tweet 4 - 06 A Special 808 Ajay Subscribe No Veer Subscribe Must Subscribe To Ki Itne Fans Jo Si subscribe Video then subscribe to the Ki Aaysk Ki Kuch Tu Kya Twist Length Of The Characteristic Of Death And You Find All Characters Of This Point Se Z2 Plus But I Will Reduce subscribe Video then subscribe to the Page that the contract will start from the index find blast they are interested in searching for the election against the previous it's the smallest drink in scotland a minus one part fennel index ki khushboo s si aunty ki khushboo k - 500 gr reduce aunty ki khushboo k - 500 gr reduce aunty ki khushboo k - 500 gr reduce one in the past video cigarette 0609 text - - midnight 05060 reduce subscribe this - - midnight 05060 reduce subscribe this - - midnight 05060 reduce subscribe this video plz director a loot these lines dangers will return news singh rathore fonts new string love you sing and syllabus that looks are good art craft letters platform time complexity based approach Time Complexity Is Today Me All Characters Database in the String and Drops 10:30 Video Result
|
Smallest String With A Given Numeric Value
|
detect-cycles-in-2d-grid
|
The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on.
The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe "` is equal to `1 + 2 + 5 = 8`.
You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._
Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order.
**Example 1:**
**Input:** n = 3, k = 27
**Output:** "aay "
**Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.
**Example 2:**
**Input:** n = 5, k = 73
**Output:** "aaszz "
**Constraints:**
* `1 <= n <= 105`
* `n <= k <= 26 * n`
|
Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.
|
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
|
Medium
| null |
1,970 |
all right let's look at this problem called last day where you can still cross that's our read so we are given a matrix a 2d Matrix and the cells values are 0 and 1. zero depends land and one represents water and we are given the rows and Columns of The Matrix initially on day 0 entire Matrix is and that means the entire Matrix all the sales value is 0 which is land however each day a new cell becomes flooded with water so on every consecutive day one of the cell changes from Land which is zero to water which is one and on a specific day which cell changes from land to water is specified in this array and it is one waste you want to find the last day that it is possible to walk from top to the bottom by only walking on land size okay we're going to start from NSL on the top row and added any cell in the bottom row you can only travel in the four cardinal directions return the last day where it is possible to work from top to the bottom by only walking on land cells so this is day Zero this is day one of this guy changes to water then this guy changes to water we could travel from top to bottom travels to bottom couldn't similarly here at this point we couldn't so this is the last day similarly here we could Traverse like that here we couldn't because you can only go in four Direction so after this you could go either here or here both of them are Waters you couldn't go so what do we need so one thing we notice is only interested in land cells uh start from any land cell on top row reach to any land cell on bottom though Traverse only in four directions and learn to land only right that's the bit and the bit is on every day as we can see the state is different so we should be able to First create State on a specific day so let's solve for so let's do this uh we return a matrix get grid on day and here we will do what just return D and we'll have this size array so first let's do this so you go foreign so we initialize okay you want row and columns as well so we are initializing the how the grid looks on a specific day it's all initialized to zero now on each day till this day D so I equals to 0 is less than equals to D five plus one specific cell changes from land to water which is a specifically on this IU today so R equals to cells zero I and it's one base will convert into zero based and similarly equals oh I think I mess it up it's ice I zero one base convert to zero based so this specific cell this RC it changes from land to water we may change from 0 to 1. and you return grid right this is a grid on a specific day now another helper position we can write is what we can really want to solve is a can pass right can you pass from top to bottom again on a specific day and you can go row call cells so first thing we want to do is you want to get the Grid on the specific day so get upgrade on day you go details now we can either do BFFs or we can do DFS let's try BFS first so we start with the Q in BFS right so you will queue look at an integer array because it's a two points you want to say the location of the cell enclosed add land sources to the queue right so what are the sources here the resources are the starting points that are allowed and they are all the land sources so which is essentially in the top row so look at all the cells on the top row which is uh AF grid top row column is I if this is zero then you want to add it to the queue so I added to the queue how to add it to the queue and I wanna once I have already visited I don't want to visit it again so for that I do I change the value to something else or I can give a separate visited array or I can just change this value to something else so if grid IJ is -1 that means it's a so if grid IJ is -1 that means it's a so if grid IJ is -1 that means it's a land cell which has already been visited right that way we can handle it the visit concept now this is what we are trying to solve now so why our queue is not empty we get what was the cell this cell was and now you want to go in different directions you want to go in four different directions here right so let's define those directions maybe here so you have these directions you can go minus one zero right whatever the directions you want to go to so let's go to all the four directions so for each Direction let's get let's see where we land so R would be what rho would be so this was the row to begin with and it gets incremented by this similarly the column would be now what do you want to do you wanna add these cells into the queue but they have to be within the grid first right so they have to within the grid so R is get an equals to zero C is greater than equals to zero R is less than row C is less than column what else and I'm only interested in land right so especially non-visited language repeat especially non-visited language repeat especially non-visited language repeat stuff so only interested in non-visited land so only interested in non-visited land so only interested in non-visited land 0 because if it visited it has been converted to -1 converted to -1 converted to -1 so not interested now what I'm looking to see is can I reach a land cell on the bottom row so if this is a land cell and it is the bottom row then I'm done and if that's not the case then okay we will proceed further and proceeding for the means we will add it to the queue so again you don't want to visit the CM nodes again so New Market visited Apache negative value from 0 to -1 and at the end of this while loop if you're still not and ended up on any if you're not is it on true that means you don't false that means there is no path from our top land row top land cell to the bottom land cell so that's a bit and now last day to cross so let's see if we can do so let's find the first day where we couldn't cross and the last would be the day previous to that right so for n t equals to 0 t is less than so I'll start length t plus so if we cannot cross if we can't pass not can pass so if I can't pass that means the previous day is the answer and if I can pass for all the rows that means for the last is sales.lengthwise so for the last is sales.lengthwise so for the last is sales.lengthwise so this is the last step so that was the last step but see if the first day itself you can't pass a neutral minus one now the first day when you can't pass when D equals 0 is actually first day it's not a zeroth day so basically because it's for example if you look at this spread uh this is the zero three this is the first day and this cells of zero is actually indicating the first day which is where it's one ways and you have to convert sorry it's you have to convert to one base you have to do plus one and plus one or you can essentially just you know replace this change this let's run yeah for compilation arrows all right run again fix some moves line number 58. how come I forgot to declare correctly all right Lenovo 24 number of columns is this all right the test case passes let's submit seems to be taking time and time will exclude all right 98 test cases passed but there are around you know 10 20 test cases that did not pass so that means our time capacity needs to be improved so let's see what's the diagonality right now so we are going to this Loop sells or length how much length is of the cell so second zero times column okay so row times column and for every row time column prop potentially we'll do a can pass we do a BFS which will again be going through each and every cell so again row times column so it's rho Square Times column Square time complexity can we optimize this or can we optimize this do we need to check each and every day if I can pass on day number n then I can also pass on Days 1 to n minus 1 right so which is where you can try to so basically uh if can pass is an array right of so if I have can pass array it would be either yes and then no right so it's a sorted array you can do it's sort of sorted right it with only two values so you do a binary search here instead of a linear search and reduce this to log n so let's try that so what do we do so let's say left equals to zero right equals to start one now while graph is less than equals to right mid is left Plus two okay now if I can pass on this day what does that mean if I can pass on this day then I can pass on all the previous days so either this is the last day or the last day I can pass is on the right side so let's look at the right side means I change left equals to Midwest one what is the else case else uh if I cannot pass on this day that means the last will I pass has to be on the left side so on the left side that means I changed right to Mid minus 1. and we keep doing that to the end I left with a single cell and I'll either get a canvas or cannot pass so let's consider this case what if the first cell itself where left equals to zero you cannot pass there itself if you cannot pass there itself that means your right will become negative or less and left is the day that you cannot pass so potentially the answer will be left minus one right the left is what you cannot pass and so left minus 1 has to be the answer now if you are able to pass even on the last day right so to begin with like let's say you have 10 days and index 10 also you are able to pass that means the last is in which case when you this will be the case in which case you will if your left was 10 right was 10 you will change left to 11. and then you wanna change it back to 10 so you would do essentially you want to do left Final in both cases but again because it is uh one based you don't want to do plus one and so you can just put on left so let's run again let's see if this works and submit and finally it works let's go back so we talked earlier that hey we can do DFS we can do BFS we did BFS here let's see if we can do DFS as well so you know I can't pass let's comment out the VFS code so this is our BFS code let's see if we can do DFS so for DFS we get the grid now we're going to see if I can pass the grid right if you can pass so we want to do DFS from all the land cells on the top row so for oops I equals to zero is less than call R plus uh if this is a land cell so sorry about that so if rho is zero and the column is I and if this is a land cell and I do a DFS on it so DFS I pass what do I pass 0 I grid all of this I pass if DFS returns true and you return to DFS will tell if you can reach the bottom row and else you just return false so let's solve this DFI so DFS is returning Boolean we go DFS you're saying you get RC what else are you getting you're getting this great you're also getting this row and call okay so let's see how to do video guys firstly you want to ensure that you're not out of bounds so if R is less than zero or C is less than zero or R is greater than equals to row or column is greater than equals to rho call if that's the case then you just want to return false what else if you are not a land which is a visitor if you can do it here itself if it's not equals to zero then also so all other cases now you want to Market visitor it's a land you wanna First Market so and the way that we are marking it visited is we're just setting its value to minus one that's where we say it's visited and now what do we do going each Direction now before that if you finally reached to a cell in the last row then just hit on two and if that's not close to the last row then you look at all directions in okay for each Direction neuro is what uh R plus Direction zero say c plus one now if this DFS of if you are not the last row fine but if you can reach you the last row and you only want to consider land but you are checking it here itself so that's fine and that's not the case then you want to return false okay let's see if the DFS logic works as well and okay submit cool so we solve this problem using DFS and BFS and the binary search to improve the time complexity with binary search so without binary search our time complexity was our time capacity was R times c times r time C and width binary search our time capacity is R times c times log of R times C right that's our that's the thing all right that's it
|
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
|
73 |
Jhaal Hello Everyone Welcome to Late for Office Today in this video will be discussing about matrix where the question is giving a crochet and tricks and different elements heroine set an terro and kolam to listen all elements accept this element R15 V2 row associated with 028 play Battery Saver Mode On Key Murti Fit Have True Condition Lassi In That Case Will Be Using Fruit For First For Short Time Brute Force Which Were First Time I Took Place At A Place With Temperatures And Landslide In A Beneficial Exulted Candy Original Matrix Lipstick Disseminate This Is My channel metric space element from the respective column with 0 comments who is the temperature in matrix swayam sufis aur hai 108 middle set all elements of this road show as like this and dental copy all elements of temperature matrix to original metric simplest but this City will be easy for daughter of cost estimate a complete temporary length of daughter's major condition is do it in place down that drawn in space complexity order of one should have thought how we can do this question in taken from what do i will follow Step by step status very first to row and column and to for both of oo a notice to one six is check first column notice to one six is check first column notice to one six is check first column and first element 1002 change the flying jatt da hai any problem is not being from early life to oth for now need different column And Fast Rs0 Simply Slide Check 90 Number 90 Fennel Rather First And So On The Right Side Effect Status Check Arrest Of Matrix 408 Vihar Check For First Row And Column Se Check The Element Which Element 80 Subscribe Now Check Bihar Mid-Day Meal Subscribe Now Check Bihar Mid-Day Meal Subscribe Now Check Bihar Mid-Day Meal Menu 1 That this item column and doctor cried swiss roll like this that now I will check for the next9 element withdrawal note only effective work 98100 element ko subscribe that navdeep 6 chapter profile mind grow and columns pound inch elements to hua tha maa daaru do subscribe 10 Are You Can See Your Being Quiet Firstly Modules 9410 I Will Make Respective Column Rose Arrow Button The In One Day 16108 Like This A North Indian Gas A Chat Co Winner Elements Boat Lift Row And Column Sorry For Lips Say Check First Row And Column Status Lines not true and animals but also will leave the 200 g Images Tips Firstly let me check first row and first column elements of the R0 mix status very true love that Bigg Boss one will be used in art for WhatsApp in the second step I Need to change default in no metrics and you hijacking 151 with respect to women of the respective states like Bihar set the true hero all elements of that Hanuman ji basis of first ko long double witch will have set default is true that make over Lift Column Elements 0.14 over Lift Column Elements 0.14 over Lift Column Elements 0.14 Example Will Be Making Each Step By Seeing Your Soul In The First Thing Dial Make First Row And Column Status Very Well As For That Now Deposit Asset Is Cropped I Need To Check First Element And First Column Element With 2800 It Depends C Close Loop Fast Russian Row End Column Duro Do I Need To Update The True 101 Adhyayan Updated On AFriend 220 I Need To Check Tiffin Elements 2009 Elements Yo I Can See Some Managers Spits Chat One By One Swift Element I Have 1000 Do Oil Check The Element Respective Element 0518 Already Subscribe Sure Roll 05102 Column 1 Column 2 Willow Awat Have In This Way Will Make Sure Denver Check Points 152 202 These Eyeshadows Are Just Matrix Fennel You Can See This Year Is What This Too Fresh Videos Tomorrow morning do and make there respective row and column in elements do 20000 come already have a girl who has already have someone to make this boy like professor like this doesn't think she needs check the first prove to be true and trustful element which professor that Surya IS JUST MET USE OF THIS STATUS VARIABLE AND APPLIED IN THIS FRAME ORIGINAL MATRIX I HAVE TUESDAY SPACE AND YOUR MEMORY SLOW PACE COMPLETENESS WILL BE ORDER OF 1VYAM LIPS KO DOL 200 HUAA WAS LIST CODE FENNEL REAL TOE FIRST UNREAD POST CO LONG RIBBON Id for both side checking point column and true or not I will change it's true and column distic has very right yo honey to check one by one element 10 Respective Key 2012 that death for third step 105 brain column and draw on the basis of elements Element 0.000 So It's 2nd Same 0.000 So It's 2nd Same 0.000 So It's 2nd Same That Naipaul Deepotsav I Need To Check Status Is Or Set To Through All First Pro0 Similarly For The First Governor Of Elements Updated On Members All About How To Set Matrix 0 How To Speak What If You Understand This Question Tried To write this code for your sales and give this video a like and don't forget to share and subscribe my channel thank you
|
Set Matrix Zeroes
|
set-matrix-zeroes
|
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s.
You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
**Example 1:**
**Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\]
**Example 2:**
**Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\]
**Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[0].length`
* `1 <= m, n <= 200`
* `-231 <= matrix[i][j] <= 231 - 1`
**Follow up:**
* A straightforward solution using `O(mn)` space is probably a bad idea.
* A simple improvement uses `O(m + n)` space, but still not the best solution.
* Could you devise a constant space solution?
|
If any cell of the matrix has a zero we can record its row and column number using additional memory.
But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?
There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
|
Array,Hash Table,Matrix
|
Medium
|
289,2244,2259,2314
|
122 |
foreign problem and the problem's name is best time to buy and sell stock too please take a look at the previous question I'll leave a link to that video in the description box below so similar to that question inside this question we are given the integer array prices where prices of I is going to be the price of a given stock on the 8th day in this question on each day you may decide to either buy or sell the stock you can only hold at most one share of the stock at any time and however you can buy it and then immediately settle it on the same day and the task is to return the maximum profit doing this so let's take a look at this example and see how this question can be solved I've taken the same example given to us this is the prices array and now we have to find the maximum possible and now we have to find out the maximum possible profit so these are the stock prices on the given days so all the array values denote the price of a stock on a particular day so for example let us say this prices array is for the stock Apple and it is mentioned that we are given only one Apple stock and this is the price of the Apple stock on that particular day since we have to buy the stock first prior to selling so there is no point of starting your iteration at the first index positions because you won't be able to register a profit so we start a iteration from the second element so I will be pointing at the second element and now we compare the current price of I with its previous value and now we have to check for this condition but here in this case 1 is less than 7 so this condition will fail so we go so we simply ignore that and go on for the next iteration now is pointing here it will check with this previous element Y is greater than 1 so if this condition passes then calculate difference and add it to the profit so max profit will be initially zero since 5 is greater than 1 the difference is 4 now we add it to the profit zero plus four so profit is now 4 now go for the next iteration now I is pointing at 3 check if 3 is greater than 5 no it's not so go for the next iteration now I is pointing at 6 check if 6 is greater than 3 yes 6 is greater than 3 so we calculate the difference is 3 and add it to the current profit so 4 plus 3 is equal to 7 go for the next iteration and now I is pointing at 4 second 4 is greater than 6 no so we ignore and go for the next iteration and in the next iteration we reach the end of the array and now whatever is present inside the max profit variable which is 7 so 7 will be returned as the output so now let's Implement these steps in a Java program coming to the function given to us this is the function name and this is the input array price is given to us and the return type is an integer so we have to return an integer denoting the maximum profit so we start off by creating the maximum profit variable and initialize it to 0 because the current profit is 0 and then we start our iteration from I is equal to 1 for the second element inside the array and we iterate until the end of the array we are initializing I is equal to 1 because we have to compare it with the previous element so if we start with i is equal to 0 and when you do I minus 1 0 minus 1 will give minus 1 and prices of minus 1 will go out of bonds so it will give you ra out of one's exception so you start off with I is equal to 1 so you start off with this element and then you compare it with the previous element and during this comparison we are going to check if prices of I is greater than prices of I minus 1. so if the price of the current element is greater than the previous elements value then we have to calculate the current profit so current profit is going to be current element minus previous element so here in this case Phi which is the current element is greater than this previous element so the current profit is going to be 5 minus 1 which is equal to 4 and after calculating the current profit you have to add current profit to Max profit so that is the catch here you don't have to update the max profit you can directly add the current profit to Max profit which will give you the similar answer so the perfect exam this is the input array one two three four five and we get our Max profit as 4 because you buy it on the first day and sell it on the last day and the difference is 4 so you get Max profit as four so instead of that according to a logic we start off with 2 minus 1 3 minus 2 is 1 4 minus 3 is 1 and 5 minus 4 is 1 and you add all the four ones it will give you 4 which is similar to buying on the first day and selling on the last day which is also giving you 4 and finally outside the for Loop once you reach the end of the array you return the max profit variable as the output now let's try to run the code the test cases are running let's submit the code under solution has been accepted so the time complexity of this approach is of n where n is the length of the prices array and the space complexity is of 1 constant space because we are not using any extra space to solve this question now let's debug the code using this example I've taken the same function as in lead code and I'm taking the prices array as the example 2 and I place two breakpoints inside the code now let's debug it so this is the prices array I will start from 1 now we are going to check with prices of I which is R2 is greater than prices of I minus 1 which is at 1 yes 2 is greater than 1 so it will enter the if statement and now we're calculating the current profit 2 minus 1 is 1 so current profit is equal to 1 so current profit is 1 and now Max profit is initially zero we add current profit inside Max profit so max profit will become 1. now I is equal to 2 3 is greater than 2 so it will enter 3 minus 2 is 1 current profit is 1 Max profit is 1 current profit is one add current profit inside Max profit will become 2 now 4 is greater than 3 so it will enter 4 minus 3 is 1. current profit is 1 Max profit is 2 add current profit to Max profit will become 3. so here you can see Max profit is three and now again 5 is greater than 4 so it will enter 5 minus 4 is 1 3 because 3 plus 1 is 4. and now we reach the end of the array so we come out of the for Loop and whatever is present inside Max profit we return it as the output so we're calling it inside the main method and profit is 4 now so 4 is returned as the output here you can see Max profit is 4 and which is the expected output here that's it guys thank you for watching and I'll see you in the next video
|
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
|
1,556 |
Looted on the handle, we do this garlic to Prabha that both problem if question ratio Allah given in teacher and not as a thousand separate attention from unknown number one should you do take 98100 a drama them this number this Vikram Samvat 1551 Front plundering 94 for 20 minutes on encroachment 12345 1.251 digit on encroachment 12345 1.251 digit on encroachment 12345 1.251 digit product side digit pin number one to three 406 and 120 1000 and 500 Muslim question on injection room MLA - Day That's why Muslim religion MLA - Day That's why Muslim religion MLA - Day That's why Muslim religion is a question Aa hai solution mare kaam Jaipur bring question Is Rome Cooking Question 11th Solution My Coriander Will Be Free Sexual Abuse 1234 They are hanging in the balance that the next return is 1580 hours more This Vitamin Petition MP Singh Chautala Abhay Pandey Naman Ojha Loot Number One Mall--8 Loot Number One Mall--8 Loot Number One Mall--8 MP3 Number One Devpuri This Point Roy Janams Comments and Number and Last Digit of Medical of Plaster Dropped Posted on November 10th Class Date Sheet for Example 1234 40 Phone Number 9999 Placed at Position 1234 Most Voted Last Visited to Connect With Related Putting them on Only and Button 123 Miles and Next Time Have you made any arrangement for temple-mosque, dear nature and influence? any arrangement for temple-mosque, dear nature and influence? any arrangement for temple-mosque, dear nature and influence? Phone number, cigarette smoking, fold equal to monitoring last step, paneer, reverse repo here, if you want to prepare a real team, then subscribe to this video channel and The Four Na Ho is based in Pune. River gave husband again Monday 124 If you middle aged dead body with fan replace last not even for per concerned Arora Khan D Mart Somewhere in the middle class tenth policy will request a is sperm the total aware achieve total middle have to do that accident construction on the table Where can the winner reach Moong distance from her daughter porn lust for recognition Close the online free mode through Close the online free mode through Close the online free mode through that Aamir Khan my death memory one two three do that reporter Manoj Vishwakarma and we notification Monitor Natural IT Totally Hey man he is kidding Soya oil as we all are movement that keep that companies trillions of rupees robbers issues involved scientific physiology relativity is the problem of union 98100 draw without coaching classes this photo time complexity of numbers And number seven for now Kundan Haar Kahan Agar Ko Off E Vanna Pranav Extra specific your phone number Previous song should be heard Do n't even subscribe to my Videos and Technology Video channel
|
Thousand Separator
|
make-two-arrays-equal-by-reversing-sub-arrays
|
Given an integer `n`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1`
|
Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal.
|
Array,Hash Table,Sorting
|
Easy
| null |
523 |
um hello so today we are going to do this problem which is part of lead code October daily challenge continuous sub array sum so the problem says we have an array of numbers and then integer K and we want to return true if numbers has a continuous sub array of size at least two such that the elements sum up to a multiple of K and if not we return false so basically multiple is just that it's divisible by K so X is equal to n numbered multiplied by K right um so let's take a look at the first example here 2 plus 4 is equal to 6. um so that means um six modulo six is zero so six is divisible by um six right obviously and so will return true um this second example it's the entire array um so we get the sum 42 is divisible by 6 and so we return true um here you can try multiple sub arrays you won't find something that is divisible by three so we return false um one thing is when we look at the constraint here it's 10 to the power of 5. so that tells us that we can do NN squared so we can't do a Brute Force solution where we um get every sub array possible calculate the sum and check if it's divisible um that won't work here um so we need to uh to think about a different way of doing this um yeah so let's get started okay so let's see how we can do this um so let's just write down what we want is a sub array from I to J and I can be zero g can be n minus 1 or any index each can be any index in the array as long as I is smaller than J right because we want um we want the sub array to be um to be valid right if J is before this is the start this is the end um and also like we want them to be the difference to be one because we want two indices right because the problem says at least two elements and what do we want from this I and J we want the sum let's say the array is a from I to J to be divisible by K well what does divisible by K mean it just means modulo k equal to zero right um okay so that's a good starting point but since we said in the um in earlier that oven squared won't work so we can't really generate all possible um subarrays all possible inj indices because that would be of N squared one pass a possible oven is if we can somehow um convert this into a formula using up to I or up to J right and up to J why is that because let's say inj here you can we can keep a map right of this prefix sum we've seen so far right and the index it ends at so for example here we see 23 we can keep a brief either 23 itself so we can keep 23 itself and say that the index there is um zero right the ending index 23 plus 2 we can say um 25 the index is 1 right and so it's easy to keep the track as we do an oven for loop it's easy to keep track of the sum that ends at I right so that's one thing but what we want is actually the reminder so how can we track how can we do this um so one thing you can realize is well if you do 23 if you do maybe five plus k equal to 6 right 5 plus 6 module okay is actually equal to 5 plus a multiple of six let's say six multiplied by two modulo k which is six so this is K by the way uh K is equal to six that's equal to 5 as well right so what this means basically is if you have um some reminder or some number um some number right plus K multiplied by some x value let's call it um I don't know maybe B imagine if the everything module okay is equal to num right that means is equal to number that means that this is divisible by K let me write it differently so if you have a number right Plus another number D and everything modulo K is equal to nums right this tells you that D is divisible by K because why is that because when you add a multiple of K to a number and you mod it by K you will get that number so the only way you get that number is if whatever you added here is divisible by K right so this is the main thing that we will use in our advantage here if the number plus another number modulo K is equal to a number that means that other number is divisible by K because that's because it got canceled out in the mod here right so that's the main idea now how do we apply it here so for the sum of numbers from I to J to be equal to modulo K to be equal to zero what this would mean is that the sum of I up to J up to I modulo K is actually equal to the sum of I up to j modulo k why is that because well what is sum of I to J um so let's think about why so we know that the sum of I up to J is equal to up to J minus up to I right and that means also modulo is equal for both right for this to be zero right we need this to be zero right which means basically we need the sum for I up to J modulo K to be equal to the sum of I up to I modulo K to be equal to zero okay uh yeah to be equal right not equal to zero but to be equal because there's some modulo key K is equal to zero that means they are equal module of K right so for this to happen we need this okay so instead of looking for this because it's open squared let's just use this and by the way the constraint here for this to be this formula here is that I is smaller than J so how do we look for this well for each index you just record the sum you've seen and then as you go forward which is looking at Future Js check if you've seen it before if you've seen a reminder the same reminder before if you've seen it that means you have this formula valid right because if you find J such that the remainder we have seen it before which means there is an eye you've seen before that means I to J is actually modulo K is divisible by K right so that's pretty much the idea here um the only thing we need to take a think about is the constraint of the I to J needs to have a length of uh two right so that means in our map we need to record what is I so that if we find it we can say Okay J um minus I needs to be bigger or equal to two so that the length of our array is bigger or equal to two so we have at least two elements um you can also like do it in this example and just convince yourself it's right but with just this formula calculation um it's correct so let's cut this up and make sure it passes test cases um okay so let's write down the solution that we just saw in the overview so what we need is n is equal to the length of let's just make this a the length of a and we need a map to record the sums we've seen so far so let's just call it scene right which is a map and then let's go through the array elements we need the index let's call this J um in enumerate of a right and we want to calculate the um the sum but in a modular K way right so some module okay so let's call it sum uh mod K right that's what we are doing so let's call it so it's zero so we add a right and do plus a and then we do modulo K right so this is basically some modulo K up to J right so this is essentially what we saw in the overview as the sum of a up to J right module okay all right um and then we want to check if this sum already is in sin if it's not already insane right so we haven't seen so we don't have um sum of I up to a that is equal to this right we don't have it because the sum is not recorded in scene then we just need to record and proceed to the next step right so we record we want to record I right because we want to check the length uh sorry it's j this is the index but if we've seen it that means we do have it right we do have this which means basically that according to our formula earlier is that a module to J modulo K is equal to zero that's the only way for this to work um so in this case we want to check if length is 2 because that's the constraint we have we need to have at least two elements all right so let's do it here so if J which is the we want to check that J minus I basically is bigger or equal to two what is I is just whatever we recorded before in the previous iteration okay so when I check that this is bigger or equal to 2. okay if this is the case then we want to return true because we did find it um so we just returned true we did find it and the length satisfies the constraints of it true if we did all the iterations and we didn't that means we didn't find the solution so written Force okay now there's one problem which is with a case like this well right so 23 plus 2 is equal to 5 is 25 right 25 modulo 5 is X is zero but the problem is that this is the first two size um two elements that we've seen in the array so scene would not have it I will not have this um would not have a zero already so we won't say that this is a solution and that's a problem because this is a solution so how do we handle that we just need to do a special case when we have the two first element as the solution um so that should be easy so the sum of the mod here should be zero right because 23 plus 2 modulo 5 is equal to zero so we need to check if the sum of the mod is equal to zero and at least we have a size of uh two which means basically we need to check that um I is bigger or equal to 1 right so here that would be 0 1 right so we want the second Index right to get at least two elements to be at least big or equal to one okay so in that case if that's the case we want to return true because we found a solution it may be also like um here right from zero to here or from zero to here so you get the idea so we just want to handle this special case where the uh the solution is from the starting index um okay so that's pretty much it so on this okay that looks good let's try more test cases okay let's submit um okay so there is a pro yeah sorry this should be J my mistake um let's do this solution here and last submit cool so that passes test cases in terms of time complexity you are doing one Loop here over a so this is oven time in terms of space um we are only using this map here um which will contain at most all the elements of in space as well um yeah so that's pretty much it for today's problem uh please like And subscribe and see you on the next one bye
|
Continuous Subarray Sum
|
continuous-subarray-sum
|
Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_.
A **good subarray** is a subarray where:
* its length is **at least two**, and
* the sum of the elements of the subarray is a multiple of `k`.
**Note** that:
* A **subarray** is a contiguous part of the array.
* An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`.
**Example 1:**
**Input:** nums = \[23,2,4,6,7\], k = 6
**Output:** true
**Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6.
**Example 2:**
**Input:** nums = \[23,2,6,4,7\], k = 6
**Output:** true
**Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer.
**Example 3:**
**Input:** nums = \[23,2,6,4,7\], k = 13
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `0 <= sum(nums[i]) <= 231 - 1`
* `1 <= k <= 231 - 1`
| null |
Array,Hash Table,Math,Prefix Sum
|
Medium
|
560,2119,2240
|
334 |
hello friends welcome to joy of life so another medium problem from lead for today the problem number is 334 so it's a increasing triplet sequence given an integer array nouns return true if there exists a triple of indices i j k such that i less than j less than k and num psi less than num c less than num scheme if no such indices exist return or false okay interesting so over here you can see that we have the indices 0 1 2 3 4 right and we need i we need a j and we need a k right and where the values are also lesser right so if we see index 0 1 and 2 i is less than j and j is less than k over here right so first we check the indices should be in a decreasing sequence and the value should be also in a decreasing sequence right so these are nothing but indices over here and let's say these are my values so if i take the value of 0 1 and 2 so what we get 1 2 and 3 so they are also increasing so both our index and values should be in a increasing sequence that's when we call a triplet and there should be three values so in a reversely sorted array over here 5.321 we can't get that right because 5.321 we can't get that right because 5.321 we can't get that right because all the values are decreasing right we don't have three index we have the values like one two and say three but the indices will be four three and two right so this is not rising this is falling right so this graph over here will look something like this but the indices graph will look something like this then this is decreasing right and again for the last one over here they are saying that three four and five so this is zero this is one this is two and this is three and four and five so zero four and six are increasing right so if i put it in graph it will be something like this so this is zero this is four this is six right and the indices are three four and five so indices are also rising so three and this is four and this is five right so we got a triplet over here right so we need to find out if there are such triplets on them that's the problem we are going to do some tricky solution on this one and i would highly recommend that you give it a try before you look at my solution so let's head over to the board and try out the solution i have taken the same example from the lead code problem wherein we are going to find the triplet over here so the triplet that we see is at zero four six right in the last three values the triplet that we have is over here and here right zero four and six see if i put the index so these are my six values from zero to five right and what we need is that i j and k should be in increasing order right the constraint that we have is i j and k in this and then we have num psi less than num j less than non scale so basically again we have already done this that it should be a graph that is rising right it will be something like this but this is i this is j and this is k i is less than j is less than k and same for the num sign j k as well right so how we are going to solve this is a little tricky over here so there are two things to address over here one is the other is this right so how we are going to do the first one can be taken care very easily right so let's say i start a iteration right so when we iterate like this what happens is we get the value as per this graph right because i is rising first it will be 0 then it will go up like this 0 1 two three four and five right so this will be taken care of just it auto corrected it will be a straight line it's not a blended line anyways so we are we will be getting like this right and now there are three things to be tracked over here like i j and k we need three values we need the three indexes right and when we say indexes it indirectly means that we are talking about the value right when i put these indexes in my area now right so basically this value is going to be the maximum value in the array the index pointed by this value this one should be lesser than that and this one should be lesser than that right so these two values over here should be lesser than k right so what i am going to do is i am going to initialize them with max both of them so we have this loop right we will modify this loop we don't need the indexes right because we know that the indexes will be fine so these two guys are in max and so what i'll do is we'll start going over this array of norms like this so let's keep a track of i j and case and k is iterating over here right in the array so k will get the value say 2 right so this is our first index right so we'll get the value 2 and what we are going to do is we are going to see if the value pointed by k is smaller then we are going to push it as left as possible right so what we are going to do is we are going to check if k is less than i right so k is less than i if you see what we did intentionally is to set i with a max because we are looking for a smaller value right so what we'll do is we'll put i over here right so what will happen is 2 will move over here this will remain as max and k is also at 2 we are going to assign this first sorry i missed that line so i equals to k so we are good so what will happen is this guy will move over here and we'll get a new value which is a one so again we are going to check if k is less than i or not k is indeed a smaller value than what i is having so what we are going to do is we are going to put it over here and we are going to not touch j right and then we will get the next value which is a 5 so over here what will happen is this condition won't satisfy right because i is pointing to a value which is one and we have the value five at k right so we are going to introduce another check that will be for this jth index right so what we are basically do over there is we are going to put a l-sit if the above condition is not l-sit if the above condition is not l-sit if the above condition is not satisfied then only it's going to get inside this of course we have to first ensure that k and i are different right if it is same then it makes no sense right it has to be different we have checked for a lesser over here but it has to be different right and along with that we have to have an additional condition over here that is k should be less than j that's why we are assigning it to j right so again j is initialized with max for that reason right so 1 will still remain over here and 5 will come here now we see that all our value has been set now we have to figure out if we have found a triplet or not and that condition is going to be very straightforward right because we know what we are looking for so basically we can say that if k is k should be greater than i and k should be greater than j in that case i will say that okay i can return a true over here if ever this condition is matched inside the loop if not once here once we are out of this loop we can say that we have not formed a triplet so over here if you see our condition is not matched right k is not greater than j is equal to j right so our loop will continue over here so the next value you get is a 0 and since we are checking with i first so 0 we will put over here and 5 will remain here so again we'll come over here to check k is greater than i no it's not it's they're equal right so this is false so we'll go again on top so we'll get the next value so we came here we are done with this so we are at four now so we get this value four over here and we're checking that it is smaller than i no we are not assigning k and i should be different right k and i is different as you see over here right and that's when we can put the value there otherwise there is no point putting the value right so what we are going to do is now we are going to copy this 4 over here right and again this condition won't be satisfied because we have seen that j and k is same right so what will happen is now it will move on so we'll get a value 6 over here this pointer has 1 so over here what we see that 0 and both of this condition will not be satisfied at this moment right so we have zero four and six so you can see here that we have a triplet over here right and this condition will return a true in that case right so and it will uh true and we say that we have the triplet with us right so the concept over here is very simple i find a smaller value i put it to i if not if i is already having a smaller value i put it to j if not i hold it to myself and at any point if i see three values which are in the triplet sequence which is this condition over here we say that okay i have found the triplet that you were looking for right it's a very simple implementation so what we are going to do is we are quickly move over to the lead port and write it down and share it from birth right so we need three variables as we have seen and we are going to set two of them to max so i and j will be set to max so let's put it as j and b what we are doing with these we are just hydrating k vietnam's right and if we um let's get out of this value with the conditional matching we're going to say that it's false right here we are going to put some simple chats that we have just been talking k is less than nine and i equal to very simple you know what we are doing because we found a smaller value and else if k not equals because if they matches then it will not enter here right here should be greater than j and then k should be greater than i that's it the big matches returning a true over here so yeah this is the algorithm all about very simple very small quote we're going to run and check and then we are going to go to submit so yeah you can see it's been accepted so let's do a submit and check yep it's been accepted we have zero millisecond faster than 100 percent of all the submissions anyways the main concept is the trick over here right how we have been manipulating and passing on things right that is the trick part of it so these some problems are very tricky in nature you need not do anything if i give you a problem like this probably you would have done the same thing right when you get the smaller elements you put it that way right we are exactly doing the same thing over here so i hope you got the solution over here and the coming to the complexity part of it so for runtime we have order of pen because we are having a traversal over the array right and in terms of storage what we are doing is we are not storing anything right so we have this i j and k which is going to be this will have order of one it was a more of a tricky problem than a difficult problem i would say so i hope you got the concept over here and now and in case if you have any doubts or questions or suggestions or any better solution than this or any tricky solution as a matter of fact then do post it in the comments to share it with me as well i would also love to learn from you guys and also share what i have been doing share this with your friends please support the channel in order to grow i'm working on a system design series which will be starting off very soon wherein we will have system design from scratch we will create a small mini application so i would suggest you to keep it subscribed and we are going to have it very open-ended are going to have it very open-ended are going to have it very open-ended wherein you can also contribute and i can also learn from you guys it's more of a collaborative mode than a teaching mode that i'm planning for so please subscribe to the channel and share with your friends as well so yeah that's all from this video so stay safe stay home and take care of yourself and your loved ones see you soon again guys 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,351 |
hello and welcome to another daily lead code challenge let's begin our daily question uh 1 351 count negative numbers in assorted Matrix so given an M by n Matrix grid which is sorted in non-increasing order both row wise and non-increasing order both row wise and non-increasing order both row wise and column wise so decreasing return the number of negative numbers in a grid uh so besides a very obvious approach where you just iterate through all the um all the elements in The Matrix or in the 2D array and figure out how many negative numbers there are there is clearly a way to do this faster because we could uh we could stumble on the first um negative number and given that this is assorted all right in a non-increasing assorted all right in a non-increasing assorted all right in a non-increasing order right and a non-increasing so and order right and a non-increasing so and order right and a non-increasing so and then decreasing order then the rest of the array is going to be negative so we could cut down on that number of iterations initially though uh let's solve it the simple way nah good tips it's going to be zero for I in range Len grid or J in range Len grid zero if red grid I and then J is less than zero this is plus one return negatives let's run this make sure that this works and this is going to be a feasible solution but there is definitely a faster way to do it while this is running let's see if there's faster ways to do this uh so it is not increasing order both row wise and column wise what does that mean uh it means that in a row at least you can be sure that it's always in a descending order so if you were if we stumble in a row uh if grid I J if it is less than zero then we know that the rest of the so we can do this um m n is equal to blend grid land grid zero and this is going to be m and sorry this is going to be 10. and what we're really doing here now is if we stumble upon a negative number we could say that negatives plus equals and where is RJ J is the what we care about uh it's going to be m minus J does that work so the length and let's say that we stumble on the first element which is a negative number that means that we have uh how many elements in the array M minus J being the negative minus one uh let's see this works oh and then we also have to break immediately break out of this uh loop um output for extracted and why do we so does this break so I should be getting out of this for Loop immediately right let's be let's check um there's probably something some fine tuning that's needed are my feeling uh let's talk through this first we're looking at the first element of the array four three two one J is initially at zero then it's set one then it's at two and then it's a three the in the case where we J is a three and the length of the array is four we would say m which is the length of this uh m is supposed to be the length so these are messed up n m those were messed up and additionally M minus J it doesn't have to be minus one okay so this is a bit faster and I hope that it makes sense when I'm doing here um okay where else can we improve on this can we say that if they're also not increasing row wise then can we always um can we always not worry about these J's down the road potentially right so negative one negative two one negative one okay I got that we're able to now not keep track of um not keep track of sorry I'm thinking that once we encounter a element in Ace and an internal array in the nested array that is a negative the subsequent Encounters of the same index of the element where we encounter the negative is guaranteed to be negative or smaller it's guaranteed to be negative and smaller so how can we keep track of this J cut off essentially so cut off let's call it zero first and once we encounter a yeah let's do this if cut off if J is equal to let's call cut off actually m if J is equal to cut off then I would uh I would say negative plus equals um M minus cut off and break right um when do we set a cut off we would set a cut off upon encountering a negative value so if um uh grid i j is smaller than zero then we say cut off is equal to J what does this let us do we sort of say that cutoff is now equal to J and also make sure that on the subsequent runs we're going to escape from this inner nested array faster but also this lets us do this in between uh in between elements of the array right because cutoff is consistently getting smaller and smaller uh let's see this works let's see if this is faster it should be because we're encountering yeah significantly faster and um let's see what how should I explain what we're doing here maybe copying and pasting this guy here would help okay let's say that we're iterating over the first nested uh array right here once we encounter the first negative number we set cut off uh to be equal that Index this index is three and if we encounter if we set a cutoff to a specific number then in the next if statement we escape from this uh sub nested array faster on the next attempt on the next nested array we also do the same thing checking if each value is negative however we have this cutoff that we've previously memorized to be three and if this is a negative number wait this wouldn't increase the speed of our code at all because we are we're still iterating through the consecutive um nested arrays and making sure that we are hitting a negative number so this actually doesn't make us significantly faster no this is complicated how would I decrease the amount of things that I have to worry about is there no way of for example encountering this and then immediately removing these from my um these from my array that I have to look at well even if I do remove them I still have to check that my next um nested arrays are negative it's only in the case where the whole thing the whole array is negative do I get to completely add the rest of my um the rest of my numbers in there so okay how about we add that and just call that a day so if J is smaller than zero then we would negatives plus minus M minus J and break however let's include another if condition here if J is equal to zero and J is less than one then I would say negatives plus equals um n minus I Plus times and this would be in the case where for example these couple ones are also negative and once I've already encountered a negative I know that the rest are negative so zero one two three and three four five so it would be what is zero one two three five what is five minus three two but I need this to be plus one see if this works oh and of course I have to return negatives right away um I minus n sorry n minus I it's going to be one I don't have to times M return negatives put output two three was this wrong if J is smaller than zero I'm going to add two negatives M minus J and then break this should work what am I doing wrong negatives is set for I in range n for J in a Range m if J grid uh let's um i j and I care about num naught J F J is equal to this no there we go and this should be faster at least for the very big hmm for very big numbers and it doesn't seem like it's much faster let's quickly just check if there's quicker Solutions and no this is the same approach this is one to what we had okay so in that case unless there are no huge uh input values maybe with a bunch of negatives fully negative rows then our solution here is pretty it's pretty good this one the quick and easy one uh sorry not that one this one the quick and easy one that doesn't really over complicate things we just iterate through all nested rows and each one of those nested arrays at some point encounters or doesn't encounter a negative number at which point we stop iterating over that nested array and uh append all of that to negatives and although it doesn't seem to be the best Solutions the code is the same so I'm guessing that this is trial and editor running and with that uh let's call this a day thank you for watching um feel free to use this Solution please like And subscribe and I'll see you in the next run
|
Count Negative Numbers in a Sorted Matrix
|
replace-the-substring-for-balanced-string
|
Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution?
|
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
|
String,Sliding Window
|
Medium
| null |
1,609 |
Hello Hi Everyone Welcome To My Channel It's All The Problem Even Not Tree To Avoid You Never Know What If It Means The Flying Condition Staff Nurses Subscription For All Volunteers Values In Increasing Order From Left To Volunteers Values In Increasing Order From Left To Volunteers Values In Increasing Order From Left To Right And Noded In Decreasing Order From Left To Right A That MBA How To Check Weather The Trees New York It Is Not Being Written True Otherwise Be Happy Return Gift So What Is This Condition Settings Show This Is Level 0 233 Take Loot And Level-1 Level-2 Level-3 Not A Valid Notes Will Stand Level-3 Not A Valid Notes Will Stand Level-3 Not A Valid Notes Will Stand 4600 also it index loser in increasing order for increasing and decreasing the 200 December perfect you not try to meet president rule for SBI credit card payments level available which can be used for history will solve this problem will travel history le LE SUBSCRIBE OUR YOUTUBE CHANNEL MUST SUBSCRIBE AND SUBSCRIBE WHY I AM MEMBER Basic Level Roshan Approach Individuals Android Device Level With Decided To Observe Every Level Will Take You Need To Know When They Will Give Which Will Give The And Subscribe For This Level To Find The Value Of The Not Be Used For Endowed To Subject Old Values Strictly Old Values Strictly Old Values Strictly Increasing From Left To Right For Easy One Level Notes With Red Devils Pair Pray Which Will Release And Even No David Willey Subscribe For William And Kate Middleton And Processing Fee No Subscribe Note Clear Level Price Condition Will Be Reverse And Power Elements And Sot And Decreasing Order This Is The President Ko Deo Se Father Video So Let's Previous Improvements For Implementing Ko Subscribe To Ko Chaunkata Implementation Leni Se This Soft Implementation Been That Let's subscribe The Video then subscribe to the Page Hai na ho kuch dot s root hua hai na also will take off but even that will help to se market se district me element subscribe for processing subscribe a ki behen biwi mili stitch vriddhi interior ho A Vic Prithvi Accident E Did A Vic Prithvi Accident E Did A Vic Prithvi Accident E Did Not Mean Value Happened That And In Case Of Chord Take That Tweet That In Teaser That Dot Maxwell In Snow Will Treat All The Modes On The Level Size - - Centigrade 1004 Modes On The Level Size - - Centigrade 1004 Modes On The Level Size - - Centigrade 1004 Self Which Hair Will First Grade Not From The You Should Poll That And Will Check This Place Effigy Processing Even Able And Will Check The Invalid Cases Subscribe Invalid Condition Dried Air Route Dot Well Mode To It Is Not Person Wash Roadways Is Loot And Subscribe And Share And That And Sacrifice For Chief Not Basically For Deposit Level For Lips More Than 35 Written Update Of Value From Chronic Value Which And Also Know Will Reddy Left And Right Side From Zee Anmol Channel 220 Will Adelaide Taste Me More Print Is Like This Amazing Nude Hot And Developed Into Similarly I Will Vote For You Email ID Rai Child Into Watch Sunil Shetty's Singh Sudhir Do It Is Pay It Is Not Return From A Girl Were In Indian Thursday Subscribe And Working For This Veer By Shoaib Chief Checking Even Road Shyamsundar Problem Is Heavens Pay Labels Withdrawal Mystery Solved Thursday Subscribe Now Theek Hai Na Ho Is Beer Cutting Bhi Correct Answer So Let's Now It Depend See That And Accepted This Should Be Time Complexity Of Dissolution Av Loot All Notes For Fun And Space Complexities of a Simple Application Cannot Be Familiar with a Solid Other is the Problem Solution Subscribe My Channel Thank You
|
Even Odd Tree
|
find-all-the-lonely-nodes
|
A binary tree is named **Even-Odd** if it meets the following conditions:
* The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc.
* For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right).
* For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right).
Given the `root` of a binary tree, _return_ `true` _if the binary tree is **Even-Odd**, otherwise return_ `false`_._
**Example 1:**
**Input:** root = \[1,10,4,3,null,7,9,12,8,6,null,null,2\]
**Output:** true
**Explanation:** The node values on each level are:
Level 0: \[1\]
Level 1: \[10,4\]
Level 2: \[3,7,9\]
Level 3: \[12,8,6,2\]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
**Example 2:**
**Input:** root = \[5,4,2,3,3,7\]
**Output:** false
**Explanation:** The node values on each level are:
Level 0: \[5\]
Level 1: \[4,2\]
Level 2: \[3,3,7\]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
**Example 3:**
**Input:** root = \[5,9,1,3,5,7\]
**Output:** false
**Explanation:** Node values in the level 1 should be even integers.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `1 <= Node.val <= 106`
|
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
563,1005
|
1,637 |
hey everyone today we are going to solve the r question why is the partical area between two points containing no points okay so let me explain with this example so we need to find the widest vertical area so simply we sort x coordinate in input array and find the widest area so x coordinate should be a left number so 3 9 1 5 8 so first of all we sort these numbers so let's say x s it should be I think one 3 5 8 9 like this and uh since it's sld it so later number should be larger right so width between two points should be so wids equal so number at uh current plus one index minus number at uh current index okay so let's see one by one so we start from index zero and prepare let's say Max WID initialized with zero and basically we iterate all numbers one by one and in the each iteration so we calculate like um so number at current plus one minus number at current index so when we are index zero so this number should be index one right and this number should be index zero so first of all um so one minus one and then compare current Max with so Z ver zero so we don't do anything and then move next so current plus one should be three minus so current number one so that is two right and two versus Z so two is a bigger than uh Z so update Max with two and then move next so now so current plus one is five so 5 minus three so that is two so two versus two so it's same so we don't do anything and move next and the next eight minus five right and that is three so three is bigger than two so upate Max with three and then move next so let me write here um 9 minus 8 and that is one right and three is a bigger than one so we don't do anything and then yeah finish so number of roof times should be length of input array so in this case 1 2 3 4 5 six so that's why 6 - 1 is five uh to six so that's why 6 - 1 is five uh to six so that's why 6 - 1 is five uh to prevent out of ons because of every time we um use a current index plus one so we should stop here yeah so after that all we have to do is just return this way 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 take all x coordinate and sort them so let's say x s it equal s it and uh X for X so we don't use y coordinate so underscore in points and then so initialize Max with v z and then for I in range and length of um exed minus one to prevent out of bounds and then Max width equal Max with passes so as I told you um so number at current index plus one so X sort it and current index number is I + sort it and current index number is I + sort it and current index number is I + one minus so let me copy this current number should be just I and then after that just return Max WID yeah so let me submit it yeah looks good so finally we beat 100% time complexity of this solution 100% time complexity of this solution 100% time complexity of this solution should be order of n log n because of we sort input aray here and the space complexity is I think order of log n or o n so depends on the language you use so sorting algorithm needs some extra space this is a stepbystep algorithm of my solution code and actually I have one more bonus python code so let me show you how to write the code this is a f solution so I use exort it and I remove everything here and then in Python uh so python has like a pairwise function so that's why just so Max and uh X2 minus X X1 for X1 and x2 in so we can write like this so iterate tools do pair wi and then X sort it so this function um take a two adjacent number so what if so one oops one two three so in that case so in the first iteration uh so X1 is one and X2 is two and the second iteration so X1 should be two and X2 is three something like that so okay so let me submit it yeah looks good also B 100% I think a time looks good also B 100% I think a time looks good also B 100% I think a time and space are the same as the first solution 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
|
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 |
994 |
this is a problem where we are given a few oranges some of them are rotten some of them are fresh and we are asked to calculate in how much time all the fresh oranges will get rotten and uh this is a question which has been very frequently asked in amazon interviews and at least 120 people have reported that they have actually faced it in their amazon interviews so let's see what is the problem so we are given a grid like this 2d grid and some oranges will be rotten which i will denote by this color so let's see this is the rotten orange and this is fresh orange as you can see so this is the initial state at time equal to zero and one rotten orange will spoil all its neighbors in the next time step so if this is the state at time equal to zero here we have just one rotten orange but we can have multiple so you can guess what are the oranges that will be spoiled in the next time t equal to 1 and here neighborhood we will always look in four directions top down bottom left so this is the question so can you make any guess what will be the state at t equal to 1 this is the state at t equal to 1 and you can see that these were the neighbors this is to the right this is to the bottom so these are spoiled at t equal to 1. now uh we will not be concerned with this because whatever was in the neighborhood of this the original uh rotten orange it has already spoiled all the its neighbors so in the next time step it will have no role to play these are the freshly rotten oranges so we have to look at its neighborhood so at time equal to t let's see what are in its neighborhood for this is in neighborhood and this is also in neighborhood of this so if it's neighborhood of multiple then it doesn't matter from which you have taken this so in time equal to two only these two are in the contact so these two should be rotten so let's see at time equal to two so you can see that these are rotten now we have just one fresh orange that is in contact with any rotten orange at time equal to two so only this one should be impacted and you can see this is now rotten and uh in the next time step this will be rotten which is here so at time equal to 4 every orange has been rotten so we will return 4 in this case we have to return this we cannot get all oranges rotten before time equal to four since only this can spoil the oranges which are in the immediate neighborhood of this so it will take at least four units here but there may be some scenarios where not all oranges may be rotten for example let's say this orange was so there were some oranges let's say there was a fresh orange here and there was a rotten orange here and maybe here so these rotten oranges cannot spoil this one since there is nothing in the neighborhood of this so all these four neighborhoods are empty so in this case we will return minus one if not all the oranges can be written so how can we proceed here so it looks like a graph problem we have some nodes these grid cells denote nodes some of them may be empty where we are not supposed to visit the fresh oranges can be treated as unvested nodes and the oranges which have just written in the previous time step we will consider them uh in the queue so uh what should be used here so if you look at the problem statement itself that is a node a rotten orange can spoil all its neighbors in the next time step so straight away you should think of breadth first search since the definition of breadth first search is that from a given node in the next time step you will visit all the neighbors which are at one unit distance from it and in the next time step you will explore all the neighbors which are two units away from them and those will be triggered by these neighbors so exact same problem is here and we can have multiple nodes initially which are rotten so we can we have to keep track of all the nodes from where we have to trigger bfs breadth first search so what we will do let's see how we can solve it so whatever oranges are rotten we put them into a queue so in this case we will just put this one so let's denote the oranges in queue with some color let's say blue so this is in queue at time equal to 0 so at time equal to 0 these are in the queue so while q is not empty so we will use something similar to bfs but what we have to do we will see how many elements are there in the queue so we have one so we will pop this and then a look at its neighbors so this is its neighbor so this will be now rotten so let's insert it into the queue so this is now inserted in the queue and this also and this is now removed from the queue so we are only interested in this one since this has already spoiled these two and now in the next time step this is irrelevant to us it cannot further spoil it has already spoiled these two and now these two are the ones which will contaminate other oranges so again these two will be in the queue so q is not empty so we also keep track of time so here we incremented time and now these two are in the queue so we will pop them two times since we know that size is two so we will pop this one and contaminate this one and this one next we pop so this is done so let's color it with this thing so we are done with these popped from the queue and then we will pop this one and this neighbor is already contaminated so we are done with this now in the queue we have these two oranges again we incremented time so time becomes now two and we will pop these two we pop this one but there is no neighbor which is fresh so we are done with this and then we pop this one we got one neighbor which is fresh so we contaminate it and we are done with this also now this is the only orange in the queue and its time is three then we pop this one and look at its fresh neighbors so this is the only first neighbor so we contaminate it and push it into the queue and we are done with this and now time is 4 so we will increment time whenever we are we have inserted the new oranges now we will pop this one there is no orange to be contaminated so in this case we will not increment the time and we are also done with this now the queue becomes empty and we return the time which is four so this is how we will solve the problem so let's see uh then uh there is one more scenario that i had said that we may have to return minus one if some orange was not reachable from the spoiled orange so how we will do that so let's uh while looking for a spoiled oranges the first step where we inserted the originally spoiled oranges into the queue there also we will compare if it's a fresh orange or not if it's fresh we keep track of its count and then we keep track of uh how many oranges we contaminated so that we will keep decrementing the fresh air so whenever we are contaminating orange we decrement the count of fresh and finally what we need to do if fresh is 0 that means we have contaminated exactly this number of oranges then return this time which we were incrementing else return -1 else return -1 else return -1 so this is very simple if you understand it should be very easy to write the code so let's begin writing the code and what should be the time complexity let's first see this so we traverse this grid once to find which oranges are contaminated so that takes o of n time in the beginning so here n is the number of oranges so you can say n equal to r cross c number of grid cells not the oranges so we scan through it once find the contaminated oranges push it into the queue then we pop this and look at its neighbors so there can be at max four neighbors and same orange will never be inserted into the queue again so the orange which was contaminated in two in the previous to previous time step we will never insert that again since that can never contaminate any orange so an orange is never inserted twice in the queue so again we can have end time some factor of n looking at all the four neighbors so worst case again it's often and space can be often since in the queue we can insert maybe all oranges are contaminated so we will insert all of them so space can also be often and time is also often so now let's write the code for this so you can go through this there are three states that are possible for a grid cell one is empty means zero one means fresh two means rotten so these are the three states so let's have a queue so this pair for keeping track of coordinates so i said that we will insert these contaminated oranges in the queue so by that we meant we will insert the coordinates of these oranges so we will have row and column number so that's why i am keeping a pair and this will always contain the freshly rotten oranges press equal to zero we will calculate it while iterating through this grid t equal to zero since the time step is initially zero if it's two that is its rotten then we insert it into the queue if it's one then it's fresh so we increment the fresh count so again we are in keeping track of how many fresh oranges were there so that whenever we contaminate an orange we will decrement the fresh count and finally fresh would be zero then we will return the time step t otherwise we will return minus 1. foreign so let's uh pick the x and y coordinates x is rotten dot front dot first so this rotten holds pair first is the x coordinate and second is the y coordinate or the row and column you can say then we pop it then we look at all the four neighbors so first neighbor can be x plus one we are checking if x is more than 0 then only we can look at x minus 1 if it's 0 we will not look at that neighbor and if it's 1 then only we are interested this is the fresh orange so we contaminated it so we are leveling it two and then press minus since we contaminated it the count of rest decreases by one and rotten dot push this new coordinate that is x minus one y and this we will do for all the four neighbors so we are doing exact same thing you can run a for loop for 0 to 3 and you can save these directions in a pair like minus 1 0 and so on but for simplicity i will write it 4 times although this is not that great similarly for y then x less than r minus 1. and finally y less than c minus 1. and if we actually did wrote any orange then only we will increment the time step if we did not make any progress that is we did not find any fresh orange in this then this rotten will be empty by the end of this loop so if we did any progress then only we will increment the time otherwise either every orange has been written or we cannot proceed further so if not rotten dot empty then e plus and finally return fresh is equal to 0 that is we were able to contaminate every orange then we return the time taken else minus 1. so this is just first is not a function these are first and second a rotten nut puss line 18. now it works it's giving four let's try this one it should give minus one and then we have so it's correct for all these three so let's go ahead and submit and the solution is accepted so we are right here in the top around 96 of the accepted submissions just because our runtime is often and we cannot do better than this so now let's repeat this logic in java and python so instead of pair of winds we can take int array so and the java solution is also accepted and here also we are right here in the top finally we will do it in python 3. so we can use a list as a queue so these are rows and columns and fresh will keep the count of fresh oranges t is the time step and we will increment every time we contaminate any orange so we have to pop from the beginning so and the javascript python 3 solution is also accepted
|
Rotting Oranges
|
prison-cells-after-n-days
|
You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`.
| null |
Array,Hash Table,Math,Bit Manipulation
|
Medium
| null |
2 |
hey everyone how's it going today we're going to be solving another liquid problem and this one is called add two numbers and I think it's problem number two on the code so this problem is actually a pretty classic one it's this whole concept of being able to add two numbers there's actually a lot of variations of this numbers where you use arrays to add numbers and you know you can also add decimal numbers which adds like a complexity to it in this particular example what we're going to be using linked lists and we're going to add linked lists and we have to return a linked list at the end that has our final result so without further ado let's dive into this problem so I'll go ahead and read this problem you are given two non-empty linked lists given two non-empty linked lists given two non-empty linked lists representing two non-negative integers representing two non-negative integers representing two non-negative integers the digits are stored in reverse order this is very important by the way and each of their nodes contain a single digit add the two numbers and return it as a linked lists you may assume that two numbers do not contain any leading zero except the number zero itself so here's an example where there's two linked lists in reverse order 2 4 & 3 5 linked lists in reverse order 2 4 & 3 5 linked lists in reverse order 2 4 & 3 5 6 & 4 so the output is 7 0 & 8 so the 6 & 4 so the output is 7 0 & 8 so the 6 & 4 so the output is 7 0 & 8 so the values that we're actually adding is 342 and 465 which is 807 so one important thing to know here is that between numbers 4 & 6 there that value between numbers 4 & 6 there that value between numbers 4 & 6 there that value is 10 and one of the rules of this linked list is it has to be a single digit that is stored in that linked list and we'll get into one thing that I like to always point out of these LICO problems is all the information that are given to you for example we are specifically told that it's in reverse order now why would that be like kind of an important factor well if you saw this in an array most of the times they wouldn't put it in the reverse order because it's a lot easier to go terse backwards from a ray then to chorist backwards from a singly linked list right if we actually had like a doubly linked list this problem could be done without essentially the problem giving us this entire thing in reverse order so essentially the algorithm for this problem is for every given node we are going to grab the value from the first linked list and the second linked list and we're going to add them together and we're also going to add any carryover that we have from our previous input and because we know that one of the rules is every single node element only has a single digit number the highest number that we could get is 18 you know 9 plus 9 so we know for a fact that the caret the maximum carryover is 1 if there is a carryover there is one the other consideration and edge cases that we need to worry about is what if we have different lengths of linked lists so that's another edge case that you need to think about and how do you properly increment your linked lists so that you can handle both cases of one linked list being empty and the other not being empty so let's go ahead and dive into the code implementation so when I do these legal problems I always like to break up my problems into a few pieces for example I know that I need traversal I need to traverse through the entire linked list and for both and I also mentioned in my kind of explanation that I need to make sure that I could traverse all of them all both linked list 1 and linked lists - even if they list 1 and linked lists - even if they list 1 and linked lists - even if they may not be the same length so I'm going to tuck with that section first so let's say while l1 or l2 we will if we have a 1 then we will do l1 equals Ln X if we have l2 it goes l2 done max just with this line of code we're able to successfully traverse both l1 and l2 once both of these are false we will exit out of this wallet that's because of this expression right here the next piece of information that I need is I need to calculate a running sum so I need to grab the values somehow from l1 and l2 so as I mentioned before that l1 and l2 could be in different lengths so I need to make sure that the value that I extract is either l1 or some default value and obviously a good default value is something that won't affect their sum is 0 so let's say that l1 value equals we're going to use a return area here if l1 is present then we'll just grab the value from l1 else we will just return 0 and we'll do the same thing for l2 value like so now we have the value of l1 and we also have the value of L 2 let's go ahead and now sum up our values let sum equals L 1 value plus l2 value so this is our sum of these two values now in the explanation I mentioned that we will need some form of a carry what if we what if the previous number we had a carry we know for a fact that we need a carryover of one value or maybe a carryover of 0 value so let's go ahead and insatiate that let carry equal 0 because we know that when we first started our first like initiation the first values to carryover of that first number is 0 so we're going to initialize it here and the reason why we're in this showing up here is because later down the line we need to for every iteration we need to see if we need to update this carry to 1 or not now let's go ahead and check if this sum is greater than not we need to properly strip off to carry over and essentially set the remainder to be the actual value level store in this new link list no before this let's just say let you value so this is the actual value we're just gonna set it to some for now and then if the sum is greater than nine and we say new value equals some mod 10 here we're essentially stripping off the 10th place and that means we need to update or carry to be one so we know that this is 1 because we mentioned that the maximum number that we can have in this sum summation is essentially 18 9 plus 2 carry so that's essentially 19 right that means our carry will always be one maximum and we know that we will have a carryover of one value if the sum is greater than that so down here we need to now take this new value that we have and somehow assign it into a linked list so one thing we haven't been doing is thinking about how are we going to return what are we returning here so let's go ahead and take care of that so the prompt says we need to return a linked list so let's go ahead and create a head which is let's just create an arbitrary linked list and we'll reuse the linked list node definition that we had above and this could just be a null value we could say 0 if you really want but this is really just a way for us to keep track of our notes and let's say node it goes head and down here we're going to say no Dominic's equals and we will create a new linked list node and we'll pass in that new value here and afterwards we need to make sure we are reassigned we update the linked list that we're essentially using as the result we also need to update that so we're in the same essentially the level of the nodes as all the other linked lists the linked list one and list two so if you look at this code one thing that we didn't do yet is this carry over right now as it stands in this code base it will constantly update it will never reset its arrow after one right so logically after we created this sum here and we used up this carry over we don't we want to make sure to reset carry to zero because we don't want to once we use that carry over value of one we don't need to reuse it for the next one and only if this sum is also greater than nine then we want to reuse they only want to create a new and update carry over as well so this is essentially kind of the heart of the algorithm I think we got majority of it I think there's one piece that we are missing and the last thing we need to do is if there is a carry so if we have at least one valley of carry over so this will happen if the last node in our linked list happens to have a carry over of one then we actually need to go farther then all of the linked lists can go we actually need to add one more node at the very end which is the valley of the carry over so no done next equals new node sorry links list node and we'll do carry and finally we just need to return at Dominick's and note that our head we just assigned as a random list node here so that's why we need we just have to point to where the number actually starts so let's go ahead and run this and we'll go ahead and submit it and there you go so we have successfully solved the add two numbers this is a classic problem I highly recommend you guys to think about doing it with and also add a decimal number and think about how that would affect you are out so I hope you guys enjoyed this quick video and I'll see you guys
|
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
|
1,717 |
so lead code 1717 maximum score from removing substrings in this problem you're given a string s and two integers x and y and you can remove the substring a b to gain x points and the substring b a to gain white points and you need to return the maximum points that you can gain when applying these removals of substrings so for example here if you are careless and you remove a b a and then b a again you're going to end up with 18 points which is less than 19. so that's not optimal the optimal way is as shown in the example here okay so why can this problem be solved with a greedy approach because we've seen here that not every situation not every random ordering or taking substrings works you need to have an actual strategy and there is a greedy strategy that works and the greedy strategy is always take whenever possible the substring with the best score and only take the one with the lowest score whenever you literally cannot do anything else and you would have thrown away the ladders otherwise right so you always want to check first if you can have the best one and only as a last resort you want to use the worst one so the one that gives least points and the reason for that is because it will never happen to you let's say that this one is the best like in this example right so removing the substring ba is always the best so you might say okay but what if maybe removing this substring while not good in the short term will maybe be good for me in the long term and you can show that is impossible because to have it so that the removal of the string a b causes the string ba you'd have to have something like this right you have to have b a and then something in between that causes it to not be able to be removed okay and if you're saying okay i want a b in there then you'd be having something like this and you can see that you already have the string ba which is the best of the two so there's no point in taking this one and the same can be said in the other case if you have a b and you have something in between that impedes you doesn't let you take these two letters then if what is here is ba then you already have a b so there's no point in removing this to then take a b because we've said that a b is the best one right so that's why you can always take the best one of the two and completely ignore the other unless you're about to throw away some letters and what i mean by that is for example during your scan of the string let's say that you reach a random character like t or something like that right whatever happens before t doesn't reach after t so here you could have anything and before you could have anything and it doesn't matter like this is a hard boundary it like everything resets the state resets when you meet this t and so let's say that in this example here your best substring was ba and here you only have a b well now since you've met a character that hard resets your state you're like you're thinking something like okay well might as well remove this substring and at least gain x points right because the alternative is throwing it away so not removing it which is obviously worst unless x points is negative which is it's never by the way okay so let's implement that right so just to reassume to make up the solution once again you scan through the string you keep a count of how many a and b's you have and you also keep track of which one is the best and the worst and we're going to have a neat trick to solve that case where for example x is less than y or y is less than x we're going to all reconduce all of them to the same problem okay and yeah you just move forward keep the counters and whenever you have the possibility to remove your best sub string you do so instantly and whenever you reach a letter that is neither a and neither b you check if you can take your worst substring and if so then you remove that okay right so let's implement that so we're going to start with the neat trick to have so that x less than y is the same problem as y less than x so if x is less than y then we swap them right and we reverse the string and this can only be done because a b is the reverse of b a so this is basically bringing the problem back like kind of recursively like you could also write this as a recursive call so you could do something like return maximum gain of x of s reversed and y and x and that would give you the correct result and you can try it yourself to convince yourself of that okay now you need your counters so count how many a's you have count how many b's you have and count your result this is just the result variable that we will return later on and now we do you do is you scan through your string one by one character by character and you check if your character is an a and if so then you can have one more a so that's good right okay and what if your character is b okay this is where the actual logic comes in now because of this neat trick that we've had so far then we know that x is always greater than y because if it wasn't greater than y then it gets swapped so that it now is greater than y and the case where they are equal is trivial it doesn't make any difference to take one or the other substring so we're only interested in the case where they are not equal so after this if branch gets executed you're always going to have x greater than y so that means that you always want to take the substring a b and you only want to take b a if you can't do anything else and if you the only other option is to throw away these characters and not remove the substrate okay right so what this means is that if we have a character b and we have some a's then we can remove the substring a b right so if we have at least one a then we can add to our result the points that we gain by removing a b and we can remove one a and notice that we do not remove the b because we don't increment it b so there's no need to decrement it otherwise you could uh increment it and then increment it here but that would be redundant okay otherwise if you don't have any a's then you now have one more b and that's it right okay so that's fine and dandy but what if the character is something else so it's neither an a and neither a b so it's something like a t well in that case that's where you say okay well i'm going to have to reset my state right here right because i'm going through another segment i'm jumping through another segment of a and b's and so that means that any a's and b's that i had left over are going to get thrown out of the window if i don't use them right now and so i need to use them right now even if i don't have the best substring possible right so you do that so you take the minimum of these two counts because you need to match them one to one right so you take the minimum because for example if you have 10 a's and 15 b's you can only make 10 pairs so you take the minimum of them and you multiply them by y and notice that we know that we can do it like that and we do not have to check if we could maybe do the x removal because if we were able to do the x removal then we wouldn't have gotten here we would have been here because the character would have been b right okay so now you've used your leftover characters and so now you can proceed to reset your state so you bring count a and count b to zero and you move to the next segment of a and b's or possibly like there's maybe there might be another useless charter like i don't know d and in that case you just go through this branch again but since you've reset these counters then nothing happens because the minimum is going to be zero so you add zero to the result which is fine okay and now the only thing that you need to remember is that you might get to the end of the string without having a character that is different to a and b and so you might never go through this and so in that case you want to remember yourself to do it after the loop is ended or you could like append to your string a random character like said but anyways we do it like this in this implementation and at the end you just return the result so i'll submit a solution to show you that it works and the time complexity is o fn because you just go through the string once and the space complexity is o of one because you don't keep anything i just keep two counters and that's it and yeah just to be clear once again the reason for which you can be greedy is because there is never a strategy that by removing the worst of the two substrings make the best substring appear because if there was such a solution if there was such a situation then it means that you already have the best substring and so there's no point in removing the worst substring to make it appear because you have it already so what's the point in removing that to make it appear if you already have it right so yeah hopefully this was helpful for you thank you for watching and bye
|
Maximum Score From Removing Substrings
|
minimum-cost-to-connect-two-groups-of-points
|
You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times.
* Remove substring `"ab "` and gain `x` points.
* For example, when removing `"ab "` from `"cabxbae "` it becomes `"cxbae "`.
* Remove substring `"ba "` and gain `y` points.
* For example, when removing `"ba "` from `"cabxbae "` it becomes `"cabxe "`.
Return _the maximum points you can gain after applying the above operations on_ `s`.
**Example 1:**
**Input:** s = "cdbcbbaaabab ", x = 4, y = 5
**Output:** 19
**Explanation:**
- Remove the "ba " underlined in "cdbcbbaaabab ". Now, s = "cdbcbbaaab " and 5 points are added to the score.
- Remove the "ab " underlined in "cdbcbbaaab ". Now, s = "cdbcbbaa " and 4 points are added to the score.
- Remove the "ba " underlined in "cdbcbbaa ". Now, s = "cdbcba " and 5 points are added to the score.
- Remove the "ba " underlined in "cdbcba ". Now, s = "cdbc " and 5 points are added to the score.
Total score = 5 + 4 + 5 + 5 = 19.
**Example 2:**
**Input:** s = "aabbaaxybbaabb ", x = 5, y = 4
**Output:** 20
**Constraints:**
* `1 <= s.length <= 105`
* `1 <= x, y <= 104`
* `s` consists of lowercase English letters.
|
Each point on the left would either be connected to exactly point already connected to some left node, or a subset of the nodes on the right which are not connected to any node Use dynamic programming with bitmasking, where the state will be (number of points assigned in first group, bitmask of points assigned in second group).
|
Array,Dynamic Programming,Bit Manipulation,Matrix,Bitmask
|
Hard
| null |
1,491 |
hey everyone welcome to Tech wide in this video we are going to solve problem number 1491 average salary excluding the minimum and maximum salary first we will see the explanation of the problem statement then the logic and the code now let's dive into the solution so here I have taken the first example from the link code up site so in this problem we are given salary array input but we need to find the average salary of the employees by excluding the maximum salary and the minimum salary we just need to exclude them in the calculation right so in this case thousand and four thousand will be removed and we need to take average between three thousand and two thousand so if I add these two I will be getting 5000 then I will divide by two since we have two values so the answer will be 2500 right so now we will see how we are going to do this so initially we will pick the minimum and maximum value right so the minimum value is 1000 and the maximum value in the input is four thousand then I'm going to sum all the values in the input array so if I sum the values I'm going to get 10 000 right so now I need to exclude 1000 and 4000 I need to avoid these two salaries right I need to reduce these two salaries from the total salary so we are going to have 5000 here then we need to pick the number of employees since we have excluded two employees salary that is four thousand and thousand we need to reduce two so initially we will take length of the salary input which is nothing but 4 then we will reduce 2. since we are excluding two salaries right that is the minimum maximum so we need to reduce two so we will be having two then I need to divide total salary by two that is the number of employees so I will end up having two thousand five hundred so I will return this as answer right that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially I will pick the minimum salary using the minimum function then I will pick the maximum salary using the max function then I will calculate the total salary by summing all the values in the salary input right then we will subtract the minimum salary and the maximum salary from the total salary right then I will calculate the number of employees using length function so this will give me the total number of salaries present in the input then I will reduce 2. since we are excluding minimum salary and maximum salary then finally I will divide total salary by number of employees right that's are the coders now we will run the code we can also write this code in one line rather than using many variables here so this will be the one line code for this particular problem so if you run this code and if I run this it works so the time complexity for this particular problem is order of n and space will be order of 1 that is constant space right thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
|
Average Salary Excluding the Minimum and Maximum Salary
|
number-of-times-binary-string-is-prefix-aligned
|
You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Output:** 2500.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
**Example 2:**
**Input:** salary = \[1000,2000,3000\]
**Output:** 2000.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
**Constraints:**
* `3 <= salary.length <= 100`
* `1000 <= salary[i] <= 106`
* All the integers of `salary` are **unique**.
|
If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too.
|
Array
|
Medium
|
319,672
|
629 |
Hello Everyone Welcome Did Not Valid Channel Pradesh Ke Par In Words Without Much Difficulty Presentation Of Platforms And Explain The Question In This Presentation On Ki Inverse Paint Coat 60 List Thyother Andhe And Subscribe Our Channel Subscribe Ki And Harm In Button Par Inverter Without this is that order against new elements of obscuritism cylinder subscribe that today independence lord your kind express or .in me to do subscribe must and subscribe list Ronit number of different subscribe and germination all subscribe 232 's contribution government beques President Model 's contribution government beques President Model 's contribution government beques President Model Episode 197 200 Electronic Bulb Jahar Veer Will Smith Question That Dutt Will Spread Personalized Solution For The Meanwhile Statement Means Behave Like An Plus One Element And They Are Interested In Finding Out On Account Of Aryans Were Invited On Tomorrow Morning You Of Birth Law only Mission of Aryans Where Important Facts of Bihar I just presented in the medical format 12345 se zaptal plus one element soil and use karenge in word list for Android 2.3 Adh 2.3 Adh 2.3 Adh 80 K - To Hans K - To Invite Friends A Similar Relief 80 K - To Hans K - To Invite Friends A Similar Relief 80 K - To Hans K - To Invite Friends A Similar Relief And Commerce K - Hans And Commerce K - Hans And Commerce K - Hans hai ki - And inverter price hai ki - And inverter price hai ki - And inverter price aur sanao let's explain dam to for recognition for this question bank class 12th play list through elements of discrimination given element that will come into a plus one to do and of all web that further work In the number of verses in first me all the side of birth subscribe now two plus one element withdrawal mist shoulders subscribe element with oo 202 issue 8 inch plus one element and effective work in its wake up side plus one element * combination of element * combination of element * combination of that inko fish - Vansh Third Number Important that inko fish - Vansh Third Number Important that inko fish - Vansh Third Number Important Increase His - Wave 2K Main Increase His - Wave 2K Main Increase His - Wave 2K Main Ashok Electronics Plated 123 Ko Follow Back End - Bal Ko Mine In These Ko Follow Back End - Bal Ko Mine In These Ko Follow Back End - Bal Ko Mine In These Whole Numbers In The Meaning Of The Name And Subscribe My Channel Subscribe Fluid 2515 Va Vo Coma Any Element Loot Din Ki In plus one starting from one of the examination which element of the combination is to this time less than one feel in which can do it will increase in which subscribe this Video plz subscribe to the Page hai ki a ki awadhesh behavior which alarms starting in Mountain Dew Dates of Mine President Mirwaiz 2818 Submit Subscribe in Domination subscribe to subscribe our A Fun Hans One Upvan Increase Stupid Vishal Manton President Elementary Mid That Maybe Increase in Number Then Boys Tour of Media and Entertainment Midcap Index and Total Number of Chronic is and tell Conservation in the year will put in place one element * depot combination data place one element * depot combination data place one element * depot combination data give a question is pendrum cream - 151 give a question is pendrum cream - 151 give a question is pendrum cream - 151 element and minus one will put this element at index of beer and subscribe total number of one such victims in this hard key minus one in verses chapter-2 Total investment one in verses chapter-2 Total investment one in verses chapter-2 Total investment is less then what is the equation for this is pain plus one thing but submission of all subscribe come visit main isi understood this logic you understood complete algorithm by aman talk about it is the meaning of the giver this time Via subscribe The Channel Please subscribe and subscribe for Live Video And Will Lead To Leave One Point And Click On Subscribe That Going By The Motive Topless Code Modification The Police Tried To Solve Once Memory Techniques For Post Of Related Entries Raw Size 1051 subscribe our Channel Please Click on the Video then subscribe to the Page Pimples and Uniform Line Weight a Value in OnePlus Give the Respective Operation for Minus One Comedy - Subscribing to Avoid Minus One Comedy - Subscribing to Avoid Minus One Comedy - Subscribing to Avoid a Presentation Subscribe Old Version From Thee That Aunty weeks swine flu positive wali white updated on 210 uploads worriedly to all its getting a password will get delhi institute of the top downloads will just and other commenting report filed return and institute of tom cruise place but again designer blouse and white plus one and Building and Answers for All the Balloons and Died During Interrogation of Wave World Channel Must Subscribe My Channel Subscribe to Select Rai Sahib That Accepted for the Time Complexity of this App Does Not Very Great It's Very Like or Width Him But Will Be completed subscribe thanks for watching duguid ne
|
K Inverse Pairs Array
|
k-inverse-pairs-array
|
For an integer array `nums`, an **inverse pair** is a pair of integers `[i, j]` where `0 <= i < j < nums.length` and `nums[i] > nums[j]`.
Given two integers n and k, return the number of different arrays consist of numbers from `1` to `n` such that there are exactly `k` **inverse pairs**. Since the answer can be huge, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 3, k = 0
**Output:** 1
**Explanation:** Only the array \[1,2,3\] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.
**Example 2:**
**Input:** n = 3, k = 1
**Output:** 2
**Explanation:** The array \[1,3,2\] and \[2,1,3\] have exactly 1 inverse pair.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= k <= 1000`
| null |
Dynamic Programming
|
Hard
| null |
58 |
thank you okay let's do uh lead code 58 length of last word uh this problem just wants you to return the length the last word uh in a input string and it can get tricky because there's Extra Spaces and stuff so let's do this in JavaScript and I'm not going to use uh like split or anything like that um I'm going to use the way that neat code does it so credit to kneecode for this solution so first you want to get the length or sorry set a length of zero and then what you want to do is you want to get your for Loop and we'll let initialize I as 0 and while I is less than the length we'll increment okay so then what we want to do if where we're at in the word is a space or sorry is not a space if we were out in the word is not a space then what we want to do is set another if statement in here and check to see if the element before it is a space we're going to set length to one so this is a reset right here and then let's cut the rest as you can see how this works else what you want to do is do length plus one and then at the end here we're just going to return the length all right so let's run this we have some wrong answers ah we gotta set the length the one that in the reset there we go short Okay so what we're doing here is when we're going through this input string of hello world we're checking is the letter that we're on is this a space if it's not a space we check to see if the letter before it or the character before is a space and we want to then set it to one if it is a space because it's a reset so when you're walking through here we're gonna go okay this is the letter length plus one this is a letter length plus one right when we get to here we're going to skip it because it's a space but then when we get to this character in the next word we go okay this character is not a space but before it there is a space so reset that length to one and then we continue building our string so now we go okay length is one length is two lengths is three length is four and what happens is after this uh we run out of space and then we just return the length after we run out of here and it doesn't matter if we have spaces after it because we never increment this world a word all right I'll leave it there
|
Length of Last Word
|
length-of-last-word
|
Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._
A **word** is a maximal substring consisting of non-space characters only.
**Example 1:**
**Input:** s = "Hello World "
**Output:** 5
**Explanation:** The last word is "World " with length 5.
**Example 2:**
**Input:** s = " fly me to the moon "
**Output:** 4
**Explanation:** The last word is "moon " with length 4.
**Example 3:**
**Input:** s = "luffy is still joyboy "
**Output:** 6
**Explanation:** The last word is "joyboy " with length 6.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of only English letters and spaces `' '`.
* There will be at least one word in `s`.
| null |
String
|
Easy
| null |
100 |
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 same tree so in this question we given roots of two binary trees p and Q and we have to write a function to check if they are same or not two binary trees are considered the same if they are structurally identical and also the nodes have the same value so for example here you can see the structure of these two binary trees are same and the values present inside them are also same that is why we return true but here as you can see the values are same but the structure is not the same this node has a left child and here this node has a right child the values are same but the structure is not the same so we return false here the structure is same but the values are not same the left child's value here is two but here it is one now let's see how we can solve this question so in the example one the structure of both the trees is same so first we start with p and Q so this is p and this is Q we check if there is a node yes both of them are having a node so for every node first we have to check if there is a structure present that if both the nodes are not equal to null and the second check is that both the nodes have the same value so first we have checked if both the nodes are there yes both the nodes are there and now we have to check the value is one and the value is one yes the second check is also passing and now we explore the left child so we go here p is now here and here too we go to the left side so Q is now here we check if p is not equal to null yes p is not equal to null we check if Q is not equal to null no now we check the values the value is two so this check is also passing now the left child and right child for p is null and here also there is null and again there is null so here again we go to the left side it is pointing to null and we go to the uh left child of Q it is pointing to null so they're matching so no problem so now we go back and we access the right child yes it is a null now we retrieve back and we retrieve back this is already visited explore the right ch child now so Q is now here and P is now here we check if p and Q are not null yes p and Q are not null we check the values 3 and three are same yes and we visited all the nodes and we never return false anywhere so that is why the output is true for this example now let's take example two so p is this and Q is this we check if p and Q are same we check if both are having notes yes both are having nodes and we check its values one and one both are same now we explore the left child of P so p is now here now we explore the left child of Q so Q is now here but Q is pointing to null there is no left child so this is null so now we check if p is having a node yes p is having we check if Q is having a node no Q is not having a node so they're not structurally same so we return false as the output immediately when P or Q if either of them is having null so like in this example here both of them were having null so if P was here and if Q was here both of them were having null then they structurally same but here p is not having null but Q is having null so we return false now let's take the third example we start with p and this is Q we check if both of them are having nodes yes both of them are having nodes we check the values yes both of them are having one value so they are same now explore the left side now p is here and Q is here we check if both of them are having nodes yes we check the values two and two both are same so explore the left Childs again for both those nodes so p is now here and Q is now here but Q is pointing to null we check if p is having a node yes p is having but Q is not having a node so again they're not structurally identical so we return false as the output now let's take another example so here p is starting here and Q is starting here we check if both of them are having nodes yes check if the values are same yes both values are same so explore the left child so explore the left Childs now p is here check if P has a node yes check if Q has a node yes now check the values P has 2 but Q has 7 both are not equal to each other so they are not having the same value so this condition is failing so we return false immediately no need to explore the further notes so for this we are going to write a recursive code where we are going to form all the conditions and iterate through p and Q binary trees simultaneously so that we access the same structure node each time now let's take a look at the code coming to the function given to us this is the function name and these are the input trees p and Q given to us and we have to return a Boolean value true or false as the output so first we have to check if the current node we are pointing at P or Q are both null if they're both null then they are identical right so we return true so if p is equal to null and if Q is equal to null both are identical so we return true and now we have to check if p is null and Q is not equal to null or if Q is null and P is not equal to null then they are not identical so we return false so if p is equal to null and Q is not equal to null or if p is not equal to null and Q is equal to null then in that case we have to return false it means the structure is not the same and now we have checked the structures we checked if p and Q are both null we return true if one of them is null and one of them is not null then we return false now we have to check the second type of identical that is if the nodes have the same values so if P.W is nodes have the same values so if P.W is nodes have the same values so if P.W is not equal to q.w we return fals so if not equal to q.w we return fals so if not equal to q.w we return fals so if the current node we are at we compare the values inside p and inside Q if they're not equal we return false and now finally we have to keep recursively doing first we'll visit all the left Childs and we have to do this simultaneously in both p and Q binary trees so first we explore p. left and simultaneously we do q. left and then again if there was a node here we again go down to the left again we go down to the left here too so we recursively call the function is same tree and pass p. left and q. left and now again we have to check if recursively calling we have to call on all the right children so p. right and q. right so I pass P do right and q. right here so this function will return true or false so this is the recursive function first we are making on all the left Childs and all again we are making on all the right Childs now let's try to run the code the test case are being accepted let's submit the code and our solution is accepted so the time complexity of this approach is of n because we are visiting all the nodes at least once and the space complexity is also often because this recursive function will use a stack it's called the recursive stack which will be of n height that's it guys thank you for watching and I'll see you in the next video
|
Same Tree
|
same-tree
|
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
**Example 1:**
**Input:** p = \[1,2,3\], q = \[1,2,3\]
**Output:** true
**Example 2:**
**Input:** p = \[1,2\], q = \[1,null,2\]
**Output:** false
**Example 3:**
**Input:** p = \[1,2,1\], q = \[1,1,2\]
**Output:** false
**Constraints:**
* The number of nodes in both trees is in the range `[0, 100]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
993 |
hey guys welcome back to my channel and i'm back again with another really interesting coding interval question video this time guys we are going to solve question number 993 cousins in binary tree before i start with the video guys just want to request you that if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications of more such programming and coding related videos let's get started now with the problem statement so basically guys we are given a root of a binary tree and the binary has unique values and now we are given two variables here with the binary tree x and y and we want to return true if the x and y are cousins of each other and we have to return false if they are not cousins of each other and the first thing is we want to determine what's a cousin so you can see here that a cousin uh two nodes are a cousin only if they are on the same depth of a binary tree and they don't have the same parent okay because if they have the same parent that means they are siblings they are not cousins right so in this case uh x value is 4 and y value 3. so you can see that 4 is the child of node 2 and 3 is the child of node 1. so basically they are not on the same depth hence they cannot be cousins so the answer is false now in the second example you can see that we have got x five and y four now you can clearly see that five and four both are on the same level but both are having different parents so that's why they both are cousins and hence the output is true ah there are few more examples guys which are similar to this let's jump to the constraints the number of nodes in the tree is in the range from 2 to 100 every value goes from 1 to 100 each node has a unique value and obviously x is not equals to y so they always have to be cousins or siblings or something like that they are not equal to each other and x and y both exist in the tree okay so that is the problem statement guys i hope it has cleared you let's jump to the solution part now some of you may have already guessed it that the way we are going to solve this problem is going to be level order traversal so this level order traversal is sort of a bfs or breadth first search approach where we actually traverse through the entire breadth of a particular level to find out our results and then we go to the next level okay so this is how we are going to solve this problem let us jump to the coding part of it so the first thing which we are going to do guys is we are going to declare two boolean variables and these boolean variables are going to determine if x and y both exist as a cousin or not so if x exists in the same level i'm going to store it in x exist and by default it is going to be false and then there is going to be another variable called as y exists which is also going to be false the both values are going to be true uh only if x and y both exist on the same level okay now next thing if root is equal equals to null obviously guys if root node is equal equals null simply return false here because we know that if there is no node then x and y both cannot exist now for level order traversal we always maintain two queues one is going to be the main queue which is going to store my current node so the current level node is going to be my inside my queue uh which is the variable q here and then uh let me just quickly create this one and then there is going to be another queue which is called as sub queue which is going to store all the nodes of the child level okay so let's say the main queue the queue variable is going to store let's say the root node then the sub q is going to store all the children node of the current node so basically sub q is the next level and q is the current level okay now uh initially because we know that root node is not equal to null simply just add root in our mean q and now we can start reversing so while q is not empty so i'm just going to add not here and then start with the uh while loop so the first thing which we are going to do is we are going to pull uh the queue to find out the current node inside the uh queue secured pole is how you can use it then we are going to check if the current node value is equal equals to x it means that the x exists in the current level so i'm just going to make x exist to true and the same thing i am going to do for that if at the current level y value is also present or if y value is present then simply say y exists equals to two now let's say i am at the current level and i have uh i am at currently let us say at this level or at some of the level and i have found that both x and y exist that means at the same level i have found both x and y so then it means that my purpose is solved so i can simply return true from this while loop and i don't have to process any further nodes okay that's how you can improve the complexity but let's say this hasn't occurred so then i have to process the children node so tree node left becomes equals to node dot left and then i am going to declare another variable 3 node right becomes equals to node.write node.write node.write now if you remember the condition is that the cousins cannot be siblings right so these x and y values cannot have the same parent so this left node and this right node is having the same parent which is node right ah sorry i have to rename it to curve because i am using car everywhere so let's rename this occur both left and right node are having the same parent which is curve right current node so if both left and right values are either equals to x or either equals to y it means that these are not x and y are not cousins they are siblings so we have to return false so now we are going to check that so if left is not equals to null and left dot val is either equals to x or left dot val is either equals to y it means that the left node is either equal to x or y so it is one of the nodes to be found and then i am going to check the same thing with the right node so if right is also not equation null and right dot value is either equal to x or right dot value is either equals to y basically means that the x and y are siblings not cousins okay so in this case what we are going to do we are going to return false so we are not going to process any further nodes we will return false from here only if the there is no such condition if they are not siblings uh then we can simply uh do the simple level or a traversal that if left is not equals to null then add left in the sub cube left and if right is not a questional then add right in the sub queue okay now in the level order traversal once you have traverse all the nodes in a particular level then your or in your current level then your q will become empty right so at this point of time your q dot is empty function is going to return true right so if your q becomes empty and your sub q is not empty that means uh there are still nodes to be traversed in the next level then we are going to simply assign this sub q to my current q right but obviously guys we are only going to do this if we have not found our x and y okay so uh actually no okay so uh if x and y are found then we are already returning true from here so then in that case we will not jump into this condition but if either x is not found or either y is not found then we will go to this condition and we will simply reset the x exist and y exist value 2 false again because now we are in the next level so we have to make sure that in the next level uh both x and y should be found right we uh i mean this can be the case that x is found in this level and y is found in this level so we are returning true no that's not the case so if you have jumped into the next level if you are processing the sub q now you have to reset the x exist and y exist value to false so that you can immediately determine if both x and y actually exist in the same level and then q dot add all uh sub q so simply you are assigning the sub q to q and sub q becomes equals to a new length list so that you can process the further nodes in the next level so now that this while loop is completed you can simply return x exists and y exists if both x and y exist and you didn't return from here then you can simply return ah x exist and y exist value if both are true it means they are cousins if both are if any of them is false it means they are not cousins so let's run this code guys let's see if this works and you can see that it is get getting accepted for one test case and uh hopefully yeah you can see that it is now accepted for other test cases as well so uh that now let's talk about the time complexity guys so the time complexity for this solution is going to be order of n because again we are traversing all the nodes let's say if my x and y they both exist in the last level so in that case i would have traversed all the nodes once so that's why the time complexity is order of n now the space complexity is also order of n because as you can see here we have maintaining two queues and one queue is having certain nodes at a particular time and another sub q is having certain nodes at the particular time so if we are assuming that we are having half of the nodes in q and half and sub q then again the space complexity will becomes equals to order of n okay so that was the solution guys and i hope this solution was clear enough for you and i hope your coding practice became a little bit better if it did help you guys then please do not forget to like this video and share this video with your friends again i want to request you to subscribe to my channel and hit the bell icon for future notifications if you have any questions comments suggestions any better solutions for the same problem please do not hesitate to write in the comment section below everybody is going to benefit from that thank you so much for watching guys i will see you guys in the next video until then take care and bye
|
Cousins in Binary Tree
|
tallest-billboard
|
Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`.
**Example 1:**
**Input:** root = \[1,2,3,4\], x = 4, y = 3
**Output:** false
**Example 2:**
**Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4
**Output:** true
**Example 3:**
**Input:** root = \[1,2,3,null,4\], x = 2, y = 3
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `1 <= Node.val <= 100`
* Each node has a **unique** value.
* `x != y`
* `x` and `y` are exist in the tree.
| null |
Array,Dynamic Programming
|
Hard
|
2162
|
1,704 |
hey everybody this is larry this is day seven of the april eco daily challenge uh one weekend hope you're still hanging out sharing solving problems hit the like button hit the subscribe button join me in discord let me know what you think about today's prom determine if string halves are alike so i usually solve this live if you're new here uh feel free to fast forward or watching 2x or whatever but you know if you're just looking for someone to explain someone in the problem pretending that they knew from the beginning then you know you can find it on the video i guess but anyway so today's problem is determine if string halves are like what does that mean you're given an s of even length swing the two halves of equal length a be the first half and second half if they're like they're the same number of vowels okay so that's okay so there i mean this seems pretty straightforward right uh i don't think there's anything tricky about it um yeah i mean i think the hardest part is about implementation and i think the standard way is just using a for loop or two for loops and a couple of uh a couple of variables and just you know count them i think that would be the most efficient um of course you could also try to go for one-liners which are less efficient one-liners which are less efficient one-liners which are less efficient but uh but maybe you know a little bit shorter because they sometimes you know create copies of the strings or something like that um but huh i wonder if this count huh um but yeah um yeah i think that's pretty much it uh i don't really have anything to say so i think it's israel is a python thing but even if not that's fine so let's just say we you know i'm going to try to i mean if this is a contest i don't know what i would have done because i could go you know either way to be honest because this seems pretty straightforward you know i decay so maybe i do follow up sometimes and maybe i just try to do them one night or sometimes i don't know how i feel about that but not by the case i think the first thing i would do is to change it to lower case um the reason why we change it to lower case is so that we don't have to worry about um you know uh checking two sets of things um because now everything's consistent and we don't have to care about anyway of course this is a little bit annoying because um well it's not annoying but it complexly white technically is a little bit more inefficient because it creates another copy of the string and then now you could play around with um yeah hmm there's a couple of ways to do it i guess yeah i mean i guess i would just have a count thing uh maybe i'll try to work on readability um and then count you have a string and this is just canvas say um and then now you can do you know return count of x for x and s if x is in a e i o u right something like that and of course i could be one liner but i like to do it this way and then you can just do count vowels of um of s from the first half and then the second half how to do okay fine let's just do n is equal to length of s and of course you can um you can this is this yeah i'm always a little bit sketchy but off by one of course you can you know um you can do things to kind of make this one line of course but i am just writing it like this textbook and merry christmas i think what's the other one right and then there's an ae why is this taking so long is that my computer that's a little bit awkward maybe lead code server is having issues technical difficulties one thing that i'm actually bad at during the contest is switching to different problems one lag times like this because i just i don't know when it farms in my head i have to start with otherwise i can't get out of my head but here maybe i'll just like add in a debugger line just for fun um and maybe copy and paste this to an offline thing and then so i could refresh the page that's very awkward though okay let's refresh this is my computer my parties technical difficulties is it me are my other internet sites up maybe it's me all right let me connect and disconnect my wifi real quick you know this is live because any reasonable person would edit this out but uh but it is what it is i hope you fast forward for uh through it if not that's okay thanks for hanging out uh okay let's see okay um i'm just copying and pasting my thing back here okay see much quicker um oh a number is required wait what oh that this isn't count this is uh what do i want length i think i was thinking about not i don't know i had another language in my head for some reason or something okay fine this is annoying uh i think technically you could also do like something like this and then some if you don't want to convert it to a list from a generator um but that's so that technically is slightly faster but um okay so that looks good um and then we have this point now so that we can verify that this is correct this is one this is two uh and so forth i mean in this case it's not necessary obviously but um you know let's give it a submit and hope that i don't have forgot a silly case yay uh so what's to come practically here i'll leave that to an exercise at home because i think this is um yeah this is kind of um there were some hard problems in this week i'm just looking at them now from the left side and i don't know why this one is so easy um i don't know if i missed anything but yeah let me know what you think let me click on the hint okay fine that's a hint um yeah let me know what you think and i'll give you an early night uh hit the like button the subscribe button join me tomorrow join me on discord draw me wherever well maybe that sounds a little creepy but uh yeah i have a great night and i will and yeah to good health and good mental health i'll see you tomorrow bye
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
174 |
today we will solve a dungeon game problem it's very interesting problem here you are given a grid it's a dungeon and here in each cell either you get some reward or you get some devil waiting out for you so if you get a reward your health increases and if you face a level or some adverse situation like fire or other things your health decreases there may be some empty cells also where health is not impacted at all so there is a knight and there is a princess so princess is captured here in the bottom right corner and this is the princess and this cell may also contain some reward or some devil or zero so the knight has to start from here top left corner and the queen is at bottom right corner queen or princess whatever you like so the condition is that the health of night should always be more than zero if the health of knight is equal to zero or less than zero then the knight dies so it should be strictly more than zero so this is the condition so uh you will be given some numeric values instead of these so for these you will get negative values for these rewards you get positive numbers written here so when you have a reward of let's say 5 here and this is plus 1 then at the end of this after reaching this you will get 6 since this will be added and again if it's negative it will be subtracted and at no point of time it should go to 0 or less so the question is that what should be the minimum health of the night before starting here before entering this dungeon so let's look at an example then it will be more clear so for example the knight will enter here and the princess is here so let's say the knight enters with a health of five so the knight will come here its health will become three then it will go either here or here if it goes here it will become zero so it will die if it goes here it will again die it will become minus 2 and the direction that the knight can take is only right and down these are the two directions so you see that 5 was not enough so the answer should be more than five so let's see how we can find that so let's start from here this is the destination so the knight can reach here either from this one or this one there is only two choices either this is the second last cell or this is the second last whatever is the cell uh for entering this before entering this the knight should have a health of plus six if the knight has at least health of plus six then if it reaches here its health will become six minus one minus five whatever was the earlier health subtract this value negative value if it's positive add that value so it will be one so one is the bare minimum health required so the knight should have at least six health whether it's coming from this or this so now let's assume that the knight comes from this so for this we have the solution that if it wants to reach here from previous one it has to have a minimum height of six so let's create a solution array also of the same size so you can clearly see we are using a dynamic programming approach here and we are solving it bottom up so for entering into before entering into this cell the knight should have a health of six now uh it will enter from here or here so let's solve all this in the this last column so for entering what should be the minimum health so that it can reach here so if it's health before reaching here is let's say five no matter from where it comes then its health will become six and now if its health is six it can go here if its health is not six at least then it cannot reach here from this so what should be the minimum health required before reaching this cell in order for it to go to this destination so here we already have plus one so what is the extra required five so it should have at least five while coming here either from here or here so minimum requirement here is five so if you enter this cell with a health of five your health will become six and if your health is six you are eligible to go here if your health is less than that you cannot go here so we are keeping track of the minimum health required uh so that from there you can make a progress to the destination so now we have solved till this so if we reach here with a health of five we can reach the destination successfully similarly here it's already 3 so from here what should be the minimum health required to reach here it should be 2. so if you reach this cell with a health of 2 you can always take this root go here it will become 5 then if you reach here it will become 6 and once you have 6 you can reach here then it will remain plus 1 that is the knight will be alive now let's solve for this row so what should be the minimum health here so that you can enter here that's six so you need a minimum health of 6 then only you can go here you already have 30 so what is the remaining so if you enter with a health of minus 24 although that's silly because you cannot your health cannot be negative you will die but let's say the night's health is minus 24 before reaching it so after reaching what will be the health minus 24 plus 30 that is 6 so now it can enter this one but we will apply a cap on this lower cap floor on this so that it cannot go below one so one is the floor there is no ceiling and then below this floor is 0 and minus 24 will lie somewhere here but this is blocked by this floor you cannot go below this so it will be 1. so if you enter this cell with a health of 1 your health will become 31 and then you can easily go here because minimum requirement is just 6. so here it's 1. now what should be the health here you just need a health of 1 in order to advance make a progress towards destination so what is the remaining minus 9 again 1 since it cannot be negative so we are subtracting whatever is the requirement of this cell so if we are at we are trying to find for this cell let's say this value is x and when we are here we would have already solved this part and this part since we are going from bottom to top so um so for this you will need the minimum of these and these we have already solved the health requirements so whatever is the minimum health requirement let us say this is h1 and this is h2 so what we will do uh min of h1 plus h2 since from both of these you know what is the minimum requirement to reach the destination so let's say from here you need just five health to reach the destination from here you need 10 units of health to reach the destination so where you will go this one so that's why min of h1 uh and h2 now what is the remaining so we had uh subtracted this current value that is x from the cell where we want to go so min of this and minus x but it can go negative since in this case the requirement was 6 here and here we had 30 so 6 minus 30 is minus 24 so we will limit one so max of these two if this value is more than 1 then we will pick this if it goes below 1 we will pick 1 this is the limit that we had applied so that's why we solved this row and this column so that for any cell in between we have these values and we can simply pick the minimum of these two which we have already solved minus the current value and if it goes beyond below 1 we pick one and finally we will advance here let's complete this problem so here it's one and five so we will pick one and one minus ten is eleven so eleven and one which is maximum 11 so we will pick in 11 so you need at least 11 for reaching here so once you enter with 11 your health will become plus 1 since it 10 is subtracted then if you have 1 you can go here since the requirement here is minimum one so you will come here and again ah here you will your health will become 31 30 is already lying here so 31 then you can go here now let's solve uh this one you need this and this minimum is this so 1 minus 5 that is 6. so you need 6 before entering into this and now let's solve this minimum is 2 so 2 minus 3 that is 5 and here we came from this so let's keep track of this also this we got from this and here we got from this or rather it's the opposite way if we reach here we go here from this cell we will always check this path since the minimum of these two was two the requirement minimum health required among these two is this one so you will go here and if you are here you will go always here this will not exist and if you are here you will always go here and from here also you will go here now we need to solve this 5 and 6 which is minimum 5 so 5 minus 2 which is 7 is more than 1 so pick 7 put 7 here and we picked this one this was the minimum so from here we will go here so now let's verify the night will come here with a health of seven so night outside has a health of seven when it enters its health become 5 now its health is 5 and we see that it will go always this side so itself will become 2 then from here it will go this side so its health will become 5 from here it will go down so its health will become from here it has just one path it cannot go right so it will go down so its health will become 6 and from here it will again go here with a health of six and finally it will be left with a health of one so it will be alive and it will reach the princess so you see that here we go reach with a bare minimum health so 7 was correct any larger value of 7 will work but we have to find the minimum health so that's how we will write the code for this so let's write it in c plus java and python number of rows is dungeon dot size number of columns is dungeon zero dot size then we keep a solution matrix exactly of the same size so vector of hint let's call it solution r vectors of hint each of size c so this is r cross c now we will solve for this uh bottom right cell so if it's negat if it's positive then you can enter with any valid health that is even if you enter with a health of one it's fine your health will only increase but if it's negative then you should enter with one more than its absolute value that is you need at least 6 before entering this so this is our minus 1 c minus 1. if it's greater than 0 then you need the minimum health that is 1 else 1 minus dungeon r minus 1 c minus 1 you can also take the absolute value and add 1 to it but if you subtract it will become positive that is absolute value and add 1 to it so 1 minus this so we have solved for this now we will solve for our last row and last column so let's solve for the last column so int i equal to r minus 2 r minus 1 is the last row but last in this last column we have already solved this so we start from this and go till top here column will be fixed c minus 1. so we will add one for the max so it should be at least one it will not go below one and the first one will be uh whatever is below it so if the requirement here is x here it should be x minus this value so it's solve i is 1 minus i plus 1 that is one cell below it and this column will remain same similarly we will solve for last row so int j equal to c minus 2 j greater than equal to 0 minus j solve here uh rho is constant so it's our row number is r minus 1 so r minus 1 and j is varying and again the same logic max of one right cell is j plus one minus current value so r minus 1 j and 1 so it will not go below 1 so now we have solved for minimum requirements for these and these now we will start from here and go till top solving it row wise this row in this row and finally we will return this value since the night will enter from here so he should know beforehand what is the minimum requirement for entering here so that i will reach the destination alive so here we will see what is the minimum requirement for this and pick the minimum so min of i plus 1j i j plus 1 and from that subtract current value just like this one only thing is that here we pick minimum here there was just one choice so from here you can only go down right is not allowed so that's why we just we were just bothered about this cell here we can go only right not down so here we did not need that but here you can go two in two directions so we are taking the minimum every other logic remains same minus dungeon i j and again we will take the max so that it does not go below 1 and that should work let's return solve zero and this matches with expected value so submit and the solution is accepted so let's see the time it's 79.75 percent it's 79.75 percent it's 79.75 percent let's try once more if it improves it's pretty close to a higher end so it can easily reach so it does not change so what is the time complexity here we have a number of rows number of columns so we are solving for each cell so the time complexity is of the order of r cross c now let's write the same thing in java and there is no not much change in syntax here size becomes length and this remains same this becomes math.max so the java solution is also accepted and here we are right in the top runtime is one millisecond now let's write it in python 3. so and max is valid here now let's so from c minus two vote till zero this is excluded and take a step size of minus one and max is valid max and min so no change is required here one if dungeon rc is greater than zero else okay so this out of range that means 0 times c so each row holds a list of size c so let's allocate it now it should not be out of bounds and this solution is also accepted and it's also time is quite good it's right here towards the higher end only
|
Dungeon Game
|
dungeon-game
|
The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately.
Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).
To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step.
Return _the knight's minimum initial health so that he can rescue the princess_.
**Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
**Example 1:**
**Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\]
**Output:** 7
**Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.
**Example 2:**
**Input:** dungeon = \[\[0\]\]
**Output:** 1
**Constraints:**
* `m == dungeon.length`
* `n == dungeon[i].length`
* `1 <= m, n <= 200`
* `-1000 <= dungeon[i][j] <= 1000`
| null |
Array,Dynamic Programming,Matrix
|
Hard
|
62,64,741,2354
|
118 |
Hello Bhai Ji gave birth to develop numbers of password triangle subscribe pass Colors channel subscribe to I will pass to friend hotspot on Russia 's hotspots of shoulder and blast 's hotspots of shoulder and blast 's hotspots of shoulder and blast box for other cities fuel's Surya film first and last boxes for Dawood what About The Meaning Of Equipped If Time When Color Was So Let's Consider This Box OnePlus One Easy-to-Read Answer December Plus Two Easy-to-Read Answer December Plus Two Easy-to-Read Answer December Plus Two A Freelancer Producers 131 Dancer Software Always Grabbing The Boxes Above Pillar Box Blue 1000 Years Pet 6 Clear Interest Vansh-Kul Namaskar Interest Vansh-Kul Namaskar Interest Vansh-Kul Namaskar Now Listen Then The Pankaj Friends But How To Yatri Ko Its Leaders Good Taste Simple To For Bluetooth Positive Work For Representing In It Limit For Example High Quality Of One Of The Nation From Share It Will Keep Changing Eyelids The Number Of That A This Processor Keep Increasing Rep Slice Printing Pt 12345 This Particular Value And Will Have Another Very Much Flat Se Representing Towards Liquid One Point Collect So Let's Another Very Close Support Settings This Particular Mister Sorry For The Box This Thing 2012 Anand Quite Like Subscribe And Subscribe Let's Get Started Loot Hai To Hi Aap To Retail Pack Of Person Sameer Widow * Switch Off 299 Plus Leggy Dancer Sapna Decided To Go Through Subscribe Must Subscribe 280 Voucher Us Maz Point I Ko Follow I Lashes Sister Name Roshni Prashna Tu Mere Ko Worker Roman Rains Wave side do India building press subscribe electrification quality epoxy medium size and this net chicken example reach these brings cosmic kind election 2012 size one to you are two back side plus one with arp 60's mark quite amazed at come mean next raw First and last boxes vacancy meaning in there red color first and last but sarveshwar tyothar very smart and women in society that slamming bad sogdu this tells you about your height red lipstick adjustment from dekho jo deep 700 decorative 98100 first box already known singrauli will not enter Blast box in thoughts before a friend vijay b and c plus no water drop oil ready for this is to jaskirat singh statement simple vegetable this constipation should now how to give an answer that west 150 grams answer and giving r previous us word speakers us Language it a friend do first form bloody mary dividers visual properly and on phone a true this is what is pe ruk previous life index of life - but super previous life index of life - but super previous life index of life - but super fun and graphs peru i - ko fun and graphs peru i - ko fun and graphs peru i - ko like and even if this photo to the parameters which will be First to the current prime minister and also just pregnant woman in a relaxed enough for advanced hoagie and cognitive science book of birth and drop oil notifications liquid her control is equal to briggs left right to wheeler third convenience and through relationships interpretation all value Sswar Problem Change Amazon OnePlus Work How To Make Changes Suggest Iqra About Boxes Of The Great Difficulties Pest Control Equal To Equal Than Plastic High Quality 250 Years In 3D Through Witch To English Loop A Super Power Current Intact Bit By Friends And Placement Suresh Schedules And Job - Par Slide Sidney Comment Play List EMA Hai To Friends Latest Ki Aapke Kuch The Factors And Find Him Like This Actor Neeraj Nothing Imran Subscribe Preach Admission Latest Hello Friends Pe Aa Ki Jis Previous Song Phir Se Zameen U On The Sets Of Hua Hai that this video should be made international
|
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
|
226 |
think we're I think we're recording so let me just check sorry about that um stop recording okay yes we're recording so how's it going guys Nick white here I do tech and live coding stuff on twitch and YouTube so if you want to check that out check the description this part of the leaked code series I'm going through every problem and explaining it right now we're doing a java solution for a number problem number 226 invertible sorry about that invert a binary tree so this is a really popular question I guess asking a lot of interviews and you know we have this cool piece of trivia down here they give you in the problem description it says this problem was inspired by the original tweet by max Howell and max Howell is the person that wrote homebrew and you know the quote is by Google and it's you know obviously it's a joke but ninety Google 90% of our engineers but ninety Google 90% of our engineers but ninety Google 90% of our engineers use the software you wrote but you can invert a binary tree on a whiteboard so you know f off but you know I'm not sure if that's a true story the Mac and Google didn't hire max Howell because he couldn't invert a binary tree I'm sure it's not because you know it's a pretty simple tree algorithm but yeah it's pretty funny tweet so you know we have this is a really simple one there's not that many tree algorithms so I encourage everyone to go just trying work through them all this is a you know pretty easy you know basically we're doing a tree right a binary tree and you know with four to seven you know we have all these numbers and what we want to do is kind of flip the nodes at each layer right so you know we see a four to seven you know seven and two will get flipped and then you know we have another subtree down here and we're gonna you know obviously just you know swap the leaves of this subtree so it's kind of like swapping the leaves of a subtree in the button the binary tree that we're giving so you know first thing that we're gonna do and what we're gonna do in most tree algorithm problems is we're gonna see that we're taking in a node right it's gonna be either a tree node or no they call it whatever at each time and you know is the tree node class we have a value a left and a right left you know like a left child and a right child and not a value of the current node right so you know first of all if root is equal to null then really there's nothing to invert here right guys so we can just return either no or root they're both them also no that's it and then next what we're gonna do is you know we're gonna do another pretty standard thing and tree algorithm problems and we're gonna traverse down the left and right sides of the tree right so left is equal to you know invert tree root left and then tree node right is equal to invert tree of root right that's just traversing down the left and right side so you know like basically what's gonna happen is we're gonna get our tree we're gonna go through actually I'll explain it in a second but yeah we're going on the left and right side we're gonna reach every node it's just a tree traversal I'll explain it in a couple seconds and then we're gonna want to do is you're gonna want to set the root dot right equal to the left and this is where the swap occurs right so I should maybe say that clearly and then the root dot left is going to be equal to right so yeah this is the swap right here and then all you're gonna have to do is return the root right so we're not changing the root or anything you know the roots always gonna be the head we're just swapping all the child the children right and that's exactly just doing the swaps on the children we return the root everything's work perfectly so first of all let's run this I'll show you guys that it works right passes this test case right here's the input here's the output here's the expected perfect and then we'll do a submission zero milliseconds faster than 100% of solutions a hundred percent 100% of solutions a hundred percent 100% of solutions a hundred percent greats okay so let me kind of explain it now that you know that it works you know basically what we're doing is we have a root note right so we'll you know we'll take in for in this case right then we're gonna traverse down the left side so you know we're gonna hit this line first right and it's gonna pass in root dot left well root dot left is gonna be two right and then two is gonna come back around and it's gonna hit so basically it's doing like you know a depth-first kind of a situation here now depth-first kind of a situation here now depth-first kind of a situation here now obviously not breadth-first obviously not breadth-first obviously not breadth-first we're not hitting the set - then seven we're not hitting the set - then seven we're not hitting the set - then seven we're hitting we're going right from 4 to 2 to 1 right so it's gonna you know Traverse down the left side and then you know it's gonna hit 1 so you know say we have 1 and then you know it's gonna hit both of these but you know one root dot left one root is one well roots equal to 1 well left and right is nothing there's nothing there so it's just gonna return null right so it's actually gonna make it to these this point now right so it's gonna set the 1 dot left in doubt right to null and null right and that's perfect because one doesn't have a left and right you know then it's gonna end up back at 2 right because you know that's how recursion work it's gonna go you know back up to where it was so we're back at 2 now and you know this time it basically goes like that in a pattern it's gonna you know set the left and right to the swap every single time so you know this time we're gonna have left and right as 1 and 3 but we're just gonna swap them around when we have to is the thing and we're gonna say you know weird out right is equal to left so you know twos - you know - is gonna now you know twos - you know - is gonna now you know twos - you know - is gonna now have a 1 and on the right side and then a you know a 3 on the left side so that's pretty much it I hope I kind of explained that I know I'm not like that great at explaining things I'm gonna get better as I go along I'm still in the easy problems so we'll see where it goes but I thank you guys for watching please subscribe check out any other leak code problems that you might be struggling with and you know make sure to follow me on Twitch if you want to see these videos live thanks guys see ya
|
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 |
452 |
hello and welcome back today we have four or five to minimum number of arrows to burst balloons it says here there are some spherical balloons taped onto a flat wall that represents the XY plane the balloons are represented as a 2d integer array points where each point is the start and end of that stretched up balloon and we don't care where exactly along the Y AIS this balloon is we do care how long it stretches along the x axis and the reason we don't care about the Y AIS is the premises we have some number of arrows which we can shoot up directly vertically and uh there is no limit to the number of arrows that can be shot and each shot will keep traveling up infinitely so whether a balloon is lower on the Y AIS or higher on the y- AIS as long as AIS or higher on the y- AIS as long as AIS or higher on the y- AIS as long as it crosses the same x axis that same balloon will be shot eventually because this Arrow keeps on going infinitely and bursts any balloons in its path our goal is to return the minimum number of arrows that must be shot to burst all balloons okay then given all this our goal really is to find as many overlaps as possible and whenever we know that we need to find as many overlaps the first thing that should come to mind is sorting so given this input we have let's say that's our first input then we can draw along our x axis okay and this one goes from the largest one to 16 so let's say that we have zero 5 10 15 20 so let's draw that 10 five then really the first thing we want to do is sort and we want to sort by the ends the reason why we want to sort by the ends is so that we can take advantage of the fact that whatever is ending um in order for there to be a gap and for another arrow to be necessary uh whatever the ending value is should not overlap with the beginning of the next Arrow or the next balloon um so let's complete this and it will become more evidence so the next one is 28 that's the so this one ends in six this one ends in eight next one this one's lower so 712 and then the last one is 1016 okay so when we have these guys and it ends like so we notice that the first balloon this first guy right here starts at one and ends at six the next one now we know that six is our end of the previous balloon the next starting location is before or equal to in this case before it's before the end of the current balloon so we can actually know for a fact that we can indeed whatever Arrow uh that shoots this balloon and burst this balloon can also be used to burst the next balloon because whatever range there is covered uh under um so the next balloon start is covered within the range of the previous balloon so if we have 1 to six and this one is 228 let's say that it's 2 28 we can essentially shoot anywhere between 2 to six but notice that we sorted by the ends for a reason and that's because essentially whatever the end is would be the optimal place to shoot the arrow so that we can cover as many subsequent balloons as possible so if we had more than these balloons and let's say besides 28 we also had maybe a balloon that was going from 3 to five and another one that went from let's say 6 to 7 as long as the start this one starts at three this one starts at six as long as the start is less than or equal to the end of the previous balloon it can be covered under the same rank okay so we have the one six the two 8 the 712 now the 712 goes from between 6 and 8 7 to 12 and then 10 to 16 okay now the balloon that begins at s can't be burst with the same arrow that shoots this balloon because there is a gap there is no overlap and uh if this one is 7 to 12 and this one is 10 to 16 we can see however that the end of this balloon is 12 and the beginning of the next balloon is 10 which is before or equal to the end of the previous balloon so these two can be shot with a single balloon okay so this one we can basically shoot up at the we're optimizing by using the last balloon um whatever the current uh arrow is the last furthest rightmost location we can shoot at to cover as many balloons as possible since this is already sorted anything that starts before or equal to the end of the previous balloon will be covered with the same Arrow so one Arrow we shoot up here and then we burst these two balloons the next Arrow we can shoot up here and first these two balloons and that way we use exactly two balloons okay and to use another example two is uh if you see carefully there's actually no overlap so we have one going from one to two another this one ends at two this one begins at three 3 2 4 see there's no overlaps another 5 to six 5 to 6 and another from 7 to 8 uh these are clearly not to scale but the point being there's no overlaps there's no overlap here 2 to 3 4 to five there's a gap there's another Gap and hence we need four arrows okay however let's say we modify this so that instead this one uh one to two this one began at two then this is the shared point then we can shoot up one Arrow here to burst this balloon and then it was 3 to four that's the one two balloon so let's say we have a 3 to 4 and then another one add 4 to five then clearly we can shoot up one here to cover both balloons okay this is one of those problems where it might actually be clearer just to go to the code so let's do that all right what we did basically was we have some number of points and the first thing we want to do is sort by the ending location because we want to optimize as few arrows to burst as many balloons as possible so let's do that first point. sort and we're going to sort by Lambda X and we want to sort by the end so that's going to be at one okay and the other is we're aiming somewhere and the first point we're going to aim at is the first sorted uh end so if this is our end then that's let's do that real quick just to demonstrate okay so this is a sorted version then we want to start our aim at the end position of our first balloon so that's going to be points at zero and the end position of that then we just want to iterate for I in range of one we've already done the first one so let's start from the next one to the last points and as long as the beginning of the next balloon is on or before the end of the last aim position we can essentially continue uh let's see shot starts at one we need one shot to shoot the first guy and we'll say if the current point at I if the beginning of that point is less than or equal to our last aim position then great it's you know it's covered in their current aim um within that shot so it's okay we can continue however uh once we get to a point where our current points uh starting position no longer overlaps with our previously aimed position then only do we update our aim to the ending position of our current balloon so aim will be updated to points of where we are currently and its ending position at one index and we will have to use up another shot and ultimately we want to return the total number of shots used up in order to burst balloons so submit okay and this is basically 452 minimum number of arrows to burst balloons the time it takes is n log n because of the Sorting so o of n log n and the space let's see we do this in place we have some constants so the space should be over one and again the main idea is we're using the fact that we can sort by the end location then essentially we're just iterating straight and saying whenever the next starting position no longer overlaps with the last ending position so the last ending position is saved and we keep iterating and uh just like the example if we have you know like 56 and let's say 67 all of these would be counted because the start of the next balloon is before the end of the last aim balloon the start of this one is once again before or at the end of the last aim balloon and so these would then be able to be shot with the same Arrow okay thanks so much happy cating see you next time
|
Minimum Number of Arrows to Burst Balloons
|
minimum-number-of-arrows-to-burst-balloons
|
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_.
**Example 1:**
**Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\].
- Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\].
**Example 2:**
**Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\]
**Output:** 4
**Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows.
**Example 3:**
**Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\].
- Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\].
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `-231 <= xstart < xend <= 231 - 1`
| null |
Array,Greedy,Sorting
|
Medium
|
253,435
|
1,838 |
hello guys welcome back to the channel today we are solving another lead code problem that is one eight three eight frequency of the most frequent element before jumping into the solution I would highly recommend you should read the problem statement on your own and give at least 15 to 30 minutes to this problem so let's get right into it what problem is asking that you are given a array and what you have to do is get the possible frequency maximum possible frequency and as you can see it is not possible in this state but you are given a case okay using that K you can increase a number by one how many times at most K times you can increase any number by one at most K times for example let's see let's take a 4 there is no other four except this one can we make this one to four yeah we can how we do that operation three times we add plus three when we add plus 3 what we get 4 8 13. that is the max we can do in order to make the frequency of 4 larger we cannot decrease eight or three so this is our limit that we can do so we have a frequency of 2. now let's take a eight can we make four to eight yeah we can if we add plus 4 can we make one to eight no because we have left only 1K we have used four times only one operation is left in one operation we can get one to two at Max so still maximum frequency is 2. if we take something like this 13 can we take 8 to 13 yeah plus five but we have zero we have no operation left so what we can do nothing so what is the maximum frequency that we are getting it's two 13 and 13. so this is what you have to do you have to just return the maximum frequency by selecting a one number and see if we can get other number smaller than him to that number we have selected equal to that number we have selected this is the problem that we have to solve so first thing first observation that what we have to do is we can when we select a number we can only increase and when we can only increase we should select smaller than them so how we get smaller than them we do sort and you can see in the problem it is nowhere written it is sorted but in the test case they are having sort sorted order but there is nowhere written that it will be always sorted so we need sorted also okay also what we are doing we are making a segment we are making segment so whenever you have something like this making segment which algorithm is best when we do such kind of thing which algorithm strikes your mind in the case of it this was our segment which algorithm I think the sliding window let me just close that I think the sliding window but now the case arise it is not something like substring yeah it is not but how are we gonna take the decision when to move end and when to move start because in sliding window we use start and end pointer but how we gonna take that decision let's see let's take this example 1 comma 2 comma 4. and we have given K is 5 let's see if we take one we can do nothing because we cannot decrease any one we can only increase so nothing to worry about one let's see we took two now it will convert something to like this 2 yeah so if we get this 2 what is the sum 4 and what was some previously three if we add plus k can we get to this easily we have eight we have four we can get to that so whenever we are able to attain that some that ideal sum that perfect sum when everyone is equal in that segment in this segment if we are able to achieve that what we will do store it that we got two frequency and what we do we increase it and we will check can we get better can we get more frequency because as you know what we are doing we have sorted so only when we took two we have only one smaller so how to get the frequency higher is we take a little larger number and see if the smaller number can catch up to the larger isn't it so let's take one two four now segment is this what is the sum over here seven and what will be the sum if everyone is equal it's 12. if we do plus 5 can we reach it yeah we can reach it so how much is the frequency now from 2 to 3. so this is how we are getting we will be using some not some we will do the sum and see if we add K because basically we are adding plus 1 if we add a plus K and if we are able to reach this ideal thing where everyone is equal so what we do we just increase the end if we are not able to do what we do we have to shrink this window what do we push the start forward that is pretty much clear so what we will do is we will check if the current sum plus K will fetch the ideal condition where everyone is equal so that much is clear that's how we gonna do this so let me write the algo first is we do sort you know why next is we have start and end and we will have some current sum so what we will do is we'll start iterating start it rating over the array for the array and what we will do we will have the current sum and we will check if the current sum plus k is less than the element we have selected into the length that's how we are getting this sum for example 4 into 3 how many times four three times so also the length is 3 we have taken this number four so how much should be the sum is 12 so basic maths so this is what we will do and if that happens what should we do because we did add it so we have to remove it how we remove it by start increasing start you will know the syntax but this is how will increase the start and minus it also this is what we gonna do and if let me and if this condition never strikes what we do if this is where we can get if this is reachable what we do we just calculate it how we gonna calculate it just basic thing if this is the length we are not talking length but still the length you can say how many four you have three basically same thing frequency length similar length so length comma n minus start here we have Max so what we will do is and this is n and we just written the answer the length so what we are doing let me Zoom it out a bit what we are doing sort it basic start and or sliding window current sum will start iterating over the array calculate the sum we will check if it is the current sum is able to reach with the help of K to that what we will do we will just calculate it and if we were not able to what we will do shrink the window size so we are shrinking and also subtracting the start and from the sum if we write if I write it properly and the start is also increased I hope this much is clear let's see the code and I will dry run that to have a better understanding so basic thing result one is the minimum frequency that you can have because why not one because you are present so one should be the frequency so basic common sense yeah start and some sort it as discussed why not gonna repeat just iterating calculating the sum and what we check if the current sum was able to reach it we will go over this if not we'll just subtract what we had did previously that's it while long because it can get long we are doing multiplication so that's why for no overflow so let's take this code and dry run it let's take this code and write in it and this is the code and this is the test case they are dry running so one two four and K is 5. already sorted s is over here and you can see n plus watch it and is increased when it is plus so sum is now 1 and E is over here now because it increased and current sum is plus one you can also see we have selected one same thing we have selected one so sum is currently one and K is 5. and we will check what we will check which number we did take one n minus 1 that's why n minus 1 points to 1 which number did we took one into what is the length is zero one two one n minus start one it's six we can we are able to reach it so what we do and minus start 1 minus 0. and result is 1. what will be the max 1 so for that our result is still one now what we will do we will compute two now sum is 3. this time 5 plus 3 8 and which number did we select two we are seeing how many two we can have we did select two as you can see n minus 1. e would be over here my bad as you can see e and plus we did so and N minus start 2 minus zero 2 minus 0. 4 we can reach 2 8 so what is the length now again Max is one n minus start result is now 2. foreign now e is pointing to three now we add four what is the sum 7 plus 5 12 and we have selected four what would be the sum in this condition if everyone is 4 into length and minus start as you can see end is on 3 and start is on zero so n minus start so 12 is not less than 12 so as you can see again 2 comma 3 minus 0. result is three and after that we just written because we got greater than num size is 3 so I hope I was able to make my intuition pretty much clearer and we are getting three and also in the test case you can see we are getting three so let's submit it and see if it is submitting or not yeah it is submitting I hope I uh I was able to make you understand my intuition you did understand the algo the code and if you did so consider subscribing to my channel liking this video and sharing with others so you have to do what you have to do so keep grinding you guys are awesome see you in the next one bye
|
Frequency of the Most Frequent Element
|
number-of-distinct-substrings-in-a-string
|
The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105`
|
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
|
String,Trie,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
143 |
Sohe gas welcome tu code off so our next question is re order list so the question will be something like this, in this I understand you guys like we will have a link list given, a link list will be given and we They have to be re-ordered, will be given and we They have to be re-ordered, will be given and we They have to be re-ordered, how to re-order them, like how to re-order them, like how to re-order them, like first note will come and then last will come, so like what came after van, four came because whatever was four is in the last, okay, then second note will come. The second note came and then after that in the second last, something like this, what do we have to do, we have to re-order this link list and do, we have to re-order this link list and do, we have to re-order this link list and we have to return the head note of the re-order list, so we have to return the head note of the re-order list, so we have to return the head note of the re-order list, so these are some questions which are called end questions. I am going to pass one more note, what is given is that you should not modify the values in the list, we will not change the values like if you not modify the values in the list, we will not change the values like if you not modify the values in the list, we will not change the values like if you people are thinking that what do we do instead of yahan pe tu. Do four and here, what do we do in place of 3, if you do that then it means that we should not change the value, we have to change the entire node, we have to change the main pointers, don't you understand that we have to change the value. We don't have to do this, we have to change the entire note, it is okay to change only the notes in the dem, so we have to change the notes, okay, how will we solve this, then see, we will have this input and if we re- this input and if we re- this input and if we re- order it, then our What will be the pass output, will it be one, give the last note, then the last note is 5, give the second note, which is the second, then the second is the last note, then the which is the second note, which is the second, then the second is the last note, then the second last note, which is four, and give three, then this will be our order. This list will be our ordered list, so some of it has to be returned to us, okay gas, so now look at the gas here, understand this, now understand here that we are returning as if the van was three, okay. Like here, if we write 1 2 3 and then what we are doing is 5 and 4. What are we doing, we are shifting 5 and 4 to the alternate position, then like we are in the next van. What are we doing by putting it on 5? Give it to 2 in the next 5. Who are we putting in the next 2? If we are putting it on a four, then in this way we are losing something. So the thing to be seen in this is that what are we doing, we are first going till the middle, we are going till the midway and then what are we doing, we are starting to replace, we are changing the notes. If you are starting to do this, then first of all, what are you guys seeing? Gas here, if I keep writing the steps, then first of all, what is visible is Find middle of D link list, go till the middle, then till the middle element. What will happen to us if we leave? 1 2 3 This will happen because look, you guys know how to get the middle, I have already told you how to get the middle and if you guys don't know how to get the middle, brother, then you guys go and watch my video. You can think, I think there was a third lecture, it was our third lecture in which I had told the middle of D link list, so you guys should see that first. If you guys do n't know how to find out the middle element then it's okay, so in the middle, I had told you guys that. So what do we do in this, if we do the slope of the fast pointer, then the slow increases by one, the fast increases by two, then the slow which is ours, will be here, the gas which is our fast, will cross the link list, which will be our slow. It will be on three, okay, so slow, ours will be on three, so we need these notes, which notes do we need, now we need 4 and 5, okay we need 4 and 5, so if we do dot next, if we do dot. You can do next, you will get 45 A. Okay, so what will be the first step? By doing next, what will we get? Then we will have 4 and 5, this list will go to A. Okay, now look, now what is our simple savings, now our simple. The less saving is that from here, like before, we give it as L1, let us give it as L2, so what is our saving now that in the next van, we put five but gas, but Now understand the problem here, our link list from Let's is something like this and Let's suppose there are more notes in it, our link list from Let's is like this, we have written something like this, okay now we have such a link list. Now look, what do we have to do next to this gas? Who do we have to put next to the van? We have to put the note at this end, but the note at this end has a point, so we do n't have it. Don't you understand the problem here? This is what we have to put the five in the van next to them, but how do we put the five in the next van because we do not have the point for the 5 note, so what will we do now which From here we understand that from here we understand that what we have to do is to reverse the second list, what we have to do is to reverse what is visible for Android. What will be the second step here? Our second step will be that what should we do reverse this second reverse the second then the link list of the second one which will be our link list which we will come out, what will we do with it. If we reverse it then how would our L2 look like? Our L2 would look like this. Next to four will be five. Okay, so we have these two. Gas, we have L1 and L2 and so far. We have not done anything new, Gas, keep in mind, you guys, I have already told you about middle nickling, the third video was the end reverse nickling, I have already told you how we do reverse. If you want to post any link then hashtag three. Watch the third video and watch the fourth video. Now in the third video I have told how to get out the middle and in the fourth video I have told how we do the reverse, so this is less, I am not here samjhaunga gas, is the video already made, so these two I will not tell it here, so you guys must come after watching the video, it is okay, so now see, what new thing we will do here, what will we have to do in this question, now we have two lists from L1 and L2, now these two What do we have to do, merge and merge, how to match in alternate fashion, like there is a van, okay here, man, how did I write this four five, here it will be 54, because our link is reverse. So it would be 54. I had written 45 by mistake. Okay, so what I was saying was that we have to match, in what order we have to do it in alternate fashion, so like what will go next to van? Next will go to five A, then you will come to us and give you connection, four A will go and give three A, so what are we doing in alternate fashion, so now look, now I have killed, let me write the code here. How will our merge code be? Let's see what we are doing here, we are merging, here we have two link lists present, L1 and L2. Okay, now look at the gas. Now look at this L1. And this is L2, so I write L2 down a little so that we have space, so this is 11 and L2 here I write L, what are you, 5 and 4, now look at , if L1 If we do dot next, now look at , if L1 If we do dot next, now look at , if L1 If we do dot next, then what will happen to L2? The note of van, the point of van next to it, will be broken and the next point of van is worth finding 5, so if we reduce it then What will we do? = L2, we have done this less, = L2, we have done this less, = L2, we have done this less, okay, now it is done, now look gas, what do we have to do now, we have to find you in the next of five, but this was the point, so we, This pointer will get lost even after storing it, so what will we do about it? First of all, we will store this pointer here, then here we will take it No 1 and here what will we do L1 Dot Next Here we will store your point so that the next time when we are on Tu, its point gets rotated, then in L1 dot next we will store this point. So now which note is pointing to this here? Demonetization is ok, now what do we have to do, you have to point to the next 5, now the one next to 5 is pointing to four, so what do we do here? Will do L2 dot next equals tu L2 dot next question so this is good, before this we will have to make one reduction. Before breaking this note, before breaking the 5.4 note, we will have to make one reduction. before breaking the 5.4 note, we will have to make one reduction. before breaking the 5.4 note, we will have to make one reduction. We will have to store this also. Because what do we have to do next time, in the next tu, we have to sign four, so if this point does not get lost, then we will store it also, so note tu equals tu L2 Dot Net, so what have we done, we have stored this note also and this will be our note, okay, so now see what we are doing, L2 dot next equalas tu mince, who is next in L2? The point is being made, now you have got the point, okay now what do we have to do, now we have to simply change L1 and L2, then we will sign L1 as ours and not as van and L2 as ours. Will sign with note 2, now see what will happen, now L1 L2 was pointing to these two, now L van L tu whom you are finding, then L1 equals tu note van, so L1 is now finding this and L2 which is Now we are finding it, we have to close the four, now next time again the loop will run, what will be the gas? L1 dot next mains, what will be next to you, what will be 4 A and what will be the next to four, what will be three A, then this. By the way, if you want anything else then this is a simple code for our merging and I hope it is clear to you, it was a very simple code, we are not doing anything, it is just a game of pointers, gas is generally in the link list. There is a game of pointers, so if you people will understand this, then once again linklist is nothing. Believe me, links are nothing for you people, if you only believe in pointers, then you people have learned linkllies very well. If you catch it then this was the code of our merge. Gauge and I hope it is clear to you, so let me show you its code. So before showing the code, let's check it here. We can finish it very quickly. So step van tha kya tha step van tha ki middle extract middle of de link list find middle of de link list step tu kya tha step tu tha ki second link list jo tha second link list how will we get like slow pointer here If there is a second list then how will we get it? We will do slow dot next. If we do slow dot next then we will have this link list which will come. So what will we do after the second list comes? We will reverse the second list. Day 20 Second Link List both the links So this was the gas Our three step and two step code was already known to you people, just the code of the third step was a little new for you people and that too I explained to you people So look here we had the function Reorder List. In Reorder List we have Notification, so what to do. Okay, so this was the base case, so leave it. Now see what we will do. We will go out first, then go out mid. You guys know slow and fast point, we do that, slow We will pass the type because whatever is slow dot next will be our second English. Gas because whatever is our slow will be on you and tu dot next. If we do this then we will get second English. Okay, so we have reverse one. The function is written because we had to reverse this list, because if we want four and three, then I had mentioned it here in the fourth video, so you guys go and watch it, so here I am telling you guys the reverse one. The code comes in here, what have we done, we have reversed which second link list, where was the second link list, slow dot next, so here we have assigned it to L2, so here what we have. Here we have the reverse link list. Here we have the reversed second link list. Okay, so L1 and L2 got gas. Okay, now here we are slow dot next equals tu tap why are we doing this because look here. Look, like our slow pointer had already run out of gas on the third day, so now we have to tap it because otherwise what will happen then, otherwise the first link list will remain complete, so what should we do? Three dot next question will have to be nailed because this link list is one and this one is another link list, so we need a link list for this one, so what will we do, we will mail three dot next i.e. what will we do, we will mail three dot next i.e. what will we do, we will mail three dot next i.e. slow dot next. So this is what we are doing here, then what are we doing, we are giving the sign to the head in the list note van, so look here, which is L1, it is pointing to this. If it is L1, we kept signing it, head not ko, then which one is head this wali note thi van, so in L1, we people kept signing it, head ko to head this wali note thi van tu ho jaayegi because slow dot next So what will A go to in L1? A will go to 1 2 and 3 in L1. Okay so 123 A will go to 11 and then what are we doing? In L2 we will have which A will go to reverse second in English and Our simple question is less, then what is left is that what we do is we merge L1 and L2, so look here, I will show you my code, so we will run a loop until our L2 is what it is. Not equals, you become null, why are you taking it here because the size of our link list, which is our second link list, will always be small and in the size of both, this link list will also be of the same size. Link Tu also but in the case of OD, the size of Link List Tu will be one less than the size of Link List Van, so here we are simply managing L2, whatever is L1 will become automatic because L2. The size which is there will always be less, so now we are preparing here the note van next tu L2, so what will happen with this, the van which is next will start finding 4 and similarly then we will L2 dot next question note. Let's do 'and' and then we are question note. Let's do 'and' and then we are question note. Let's do 'and' and then we are changing L1 and L2, so this was a simple code, gas, in this we just reduced this one, gas is new, we just reduced the merged one, rest of these two are reduced. You guys already knew how to reverse the gas and you guys knew how to find the middle, so this one is just new here and I hope this complete discussion is clear to you guys, so let's do it. Once we submit, it will get submitted because I have already checked, so now let's talk about its time complexity. If we erase all these a little, then what will we get in Bigo of N/2? In what will we get in Bigo of N/2? In what will we get in Bigo of N/2? In this Big of N/2, it will take us to this Big of N/2, it will take us to this Big of N/2, it will take us to leave the middle, so if we talk about time complexity then what is coming first, if we are leaving, then the time to leave the middle will be City of N/2 because we People go till mid only, N/2 because we People go till mid only, N/2 because we People go till mid only, our slow pointer is there, chanting comes till midway, so end bye, we have got the middle, I am fine, after that what are we doing, after that we are doing reverse, so what in reverse? It takes big of N, it takes give, then we are merging, so I thought in doing chilli, how much will it take for us, it will take of N/2 how much will it take for us, it will take of N/2 how much will it take for us, it will take of N/2 because till where we people are running the gas till L2 which It is not equal to you, it is L, it is what it is, it will always be half of the gas of a lincolist, so big of ny2, if we get involved in it, then it will be its overall time complexity and space complexity. If we talk about it, then it is a constant which because we People are just playing in pointers, we as extra office ladies are not doing it, so this was the gas, its complete explanation and I hope this complete discussion must have been clear to you people, so Justin, how to do the video. Did you like the gas? Like the video and subscribe to the channel so that you can get any latest notification from me. I will meet you guys in the next video. With one more link list question, that was all for this video, so I will meet you. Thank you guys in the next video
|
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
|
767 |
Hello Gas, what is told to us in today's question that we will have a given string and we have to convert and rearrange the string in such a way that two characters do not adjust, if adjacent characters get mixed, that means we cannot rearrange it in any way. Can do in which the characters are not together then we have to return antisocial so here like if there is A now then A now A can be done but here triple A is B so we cannot do it in any way that we have two adjustment characters. Don't come because two A's will always go to A. Okay, so for this I have taken an example for you, A B C, so for this we will not directly tell you the approach, so what is there in the approach, we will make a map, first in the map. We will store the frequency. Okay, once we have stored the frequency in the math, then see when it is storing the frequency because we will try to find out the highest. If you understand the example, then how to make maxi, you can make it a priority, if you make it properly, it will be the highest, then it will come. A has more pregnancy, A is the most, we will sort on the basis of frequency, so basically we know what to do in priority, first we will always have two characters, then A and B, A will go, then now in the next station, we will get top again, pregnancy zero. And if the frequency of C goes to zero then it would have been removed from here. Any character will play in the last. We will check its frequency. If the frequency is greater than one then nothing can happen because see, we had to make a unique edition character in that, we have made the frequency here. If you were there is no story here that you can insert Yes, but character is meant for the director and what will you put here Greater Than One Kar Have taken Just -1 has to be done for 3 seconds too. If frequency is last basically our last character is ok then last character should be given priority. If it is given greater one in the map then brother return is ok So A Jo It will work, It will work, It will work, yes it will work, so the example we took here is Triple A, Double B and Double C, so this is also a try let's go but the same Let's run it Friends, what have we done Submitted, I have completed 3 consecutive days, you guys also keep doing it, let's thank you
|
Reorganize String
|
prime-number-of-set-bits-in-binary-representation
|
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same.
Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_.
**Example 1:**
**Input:** s = "aab"
**Output:** "aba"
**Example 2:**
**Input:** s = "aaab"
**Output:** ""
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
|
Math,Bit Manipulation
|
Easy
|
191
|
1,945 |
hi everyone welcome back for another video we are going to do analytical question the question is sum of digits after converts you are given a string as consisting of lowercase english letters and integer k first convert s into integer by replacing each letter with its position in the alphabet replace a with one b with 2 g with 26 then transform the integer by replacing it with the sum of its digits repeat the transform operation k times in total for example if s is g b a x and k equal to 2 then the resulting integer will be a by the following operations convert g b a x to 26 to 124 to 262124 transform number one two six two one two four to two plus six plus two plus one plus two plus four equal 17 transform number 2 17 to 1 plus 7 to a return the resulting integer after performing the operations described above let's work for the code we can solve the question with helper functions we first need to convert the string to integer based on alphabet we then transform the integer by replacing it with the sum of its digits repeat the operation k times thanks for watching if this video is helpful please like and subscribe to the channel thank you very much for your support
|
Sum of Digits of String After Convert
|
finding-the-users-active-minutes
|
You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum of its digits**. Repeat the **transform** operation `k` **times** in total.
For example, if `s = "zbax "` and `k = 2`, then the resulting integer would be `8` by the following operations:
* **Convert**: `"zbax " ➝ "(26)(2)(1)(24) " ➝ "262124 " ➝ 262124`
* **Transform #1**: `262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17`
* **Transform #2**: `17 ➝ 1 + 7 ➝ 8`
Return _the resulting integer after performing the operations described above_.
**Example 1:**
**Input:** s = "iiii ", k = 1
**Output:** 36
**Explanation:** The operations are as follows:
- Convert: "iiii " ➝ "(9)(9)(9)(9) " ➝ "9999 " ➝ 9999
- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36
Thus the resulting integer is 36.
**Example 2:**
**Input:** s = "leetcode ", k = 2
**Output:** 6
**Explanation:** The operations are as follows:
- Convert: "leetcode " ➝ "(12)(5)(5)(20)(3)(15)(4)(5) " ➝ "12552031545 " ➝ 12552031545
- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33
- Transform #2: 33 ➝ 3 + 3 ➝ 6
Thus the resulting integer is 6.
**Example 3:**
**Input:** s = "zbax ", k = 2
**Output:** 8
**Constraints:**
* `1 <= s.length <= 100`
* `1 <= k <= 10`
* `s` consists of lowercase English letters.
|
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
|
Array,Hash Table
|
Medium
| null |
1,171 |
alright welcome back to another discord question the question of today is a medium difficulty remove there are some consecutive notes from linked list given the head of a link at least we repeatedly delete consecutive sequences of nodes that sum to zero until there are no match sequence after doing so return the head of the final linked list you may return any such answer note that in the example below all sequence are serialization of off list node object okay for the example one we have one two minus three we did it's one two minus three because the sum is zero and we keep three and one but we can also have this answer one to one because let me see one two one because we did it three and minus three the sum is zero for example two we have one two three minus three four we did these two guys and we have one two four for the example three okay we did it two minus two because sum zero and we need three and minus three because sum zero and we keep one okay how we can do it let's visualize our linked list we have one dot next easy so dot next is -3 then three then one okay now to solve this problem let's add a dummy variable a dummy liquid list here 0 that's linked in our head then let's build a hash map that contains the node 0 and the prefix sum is just the sum of the previous nodes values of nodes so for the node 0 we have 0 for the nodes 1 we have one before adding any perfect sum we check if this prefix sum is seen before or not one is not seen before so we add in one then for the node two plus one is three sub three not same before we add injury then for minus three plus three is zero there we see him before so we remove all the nodes after the node that we already seen so now we have this hash mark this one says also that contains just node zero with the value zero now we are here we are in the new three plus zero is three is not seen before because we are removing this and this okay now one plus three is four is not seen before so our new linked list is just three and one we're removing the dummy variable okay so make this more clear let's do another example this one for example okay we have one the next of one is two the next of two is three the next of three is minus three the negative minus three is minus so let's check if i was incorrect here it is okay now let's add the dummy variable that the next is the head and now let's build our hash map okay for the nerd zero the value is zero for the node one the prefix sum is one plus zero is one is not seen before so it's cool for the node two 2 plus 1 is 3 is not seen before so it's also called for the node 3 our sum prefix is 6 so it's also cool for the node minus 3 we have minus 3 plus 6 is 3 is same before so we are removing this guy and now for 4 minus so for this minus node plus three is one is seen before so we are removing this guy and finally the result is just one it's just this node because we are removing also the dummy variable okay i hope this makes sense to you the time complexity of this algorithm is big o of n and the space complexity is also big o of n because we need to write the hash map one last thing this has map we care about the order so to know which values we will remove so we'll use collection dot dick dota i guess order is dict okay now it's coded we need first current equal so dummy equal to list node zero then we need let's make a dummy dot next equal to head so connects our dummy under linked listed let's initialize the prefix by zero there's some prefix that name is just prefix let's name the hush map scene because that name makes sense to me collections okay now while current is still alive that's mean the next of the note is not newly prefix we add prefix to prefix plus currents dot value and then if our prefix not seen before so not in scene that's me that's easy we just add the prefix in our hash map okay otherwise it is the hard part we need first so we need first to be here so our note is to be equal so scene prefix and then we just make dot next if we have any value like this so not next if we don't have any value like this like here so we are next into none or nearly okay not that next equal to currents dot next and now let's remove the guys in our hashmap okay sorry for the voice while listed we are converting our husband to list syndrome's case we took the last one if it is different than our prefix and now we are just pop the item and we need to create a quantum current dot next and finally let's return dummy dot next when we do w dot next we are removing dummy and you take the next value which is one which is connected so connected to none okay i hope this makes sense to you now let's run the code something wrong with collections with ants i hope this work okay now let's submit okay good i hope this video was useful for you and hopefully see you soon
|
Remove Zero Sum Consecutive Nodes from Linked List
|
shortest-path-in-binary-matrix
|
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)
**Example 1:**
**Input:** head = \[1,2,-3,3,1\]
**Output:** \[3,1\]
**Note:** The answer \[1,2,1\] would also be accepted.
**Example 2:**
**Input:** head = \[1,2,3,-3,4\]
**Output:** \[1,2,4\]
**Example 3:**
**Input:** head = \[1,2,3,-3,-2\]
**Output:** \[1\]
**Constraints:**
* The given linked list will contain between `1` and `1000` nodes.
* Each node in the linked list has `-1000 <= node.val <= 1000`.
|
Do a breadth first search to find the shortest path.
|
Array,Breadth-First Search,Matrix
|
Medium
| null |
895 |
That's guys welcome back to my channel and this video we are going to solve maximum frequency stack so what is wheat statement hair design astek like data structure tips elements to this track and poverty most frequent elements from distic implement difficult figure stock class friction trucks and Empty Frequency Stag Avoid Such Interval Position And Interior Value Too On To The Top Of District Indiapop Remove This Removes Irritants The Most Frequent Element In This Track Is That Is It I For The Most Frequent Element Also Element Closest To District Office Removed And Returned OK So What to do in this problem is that we have to form an extract which will be completely different from the normal track. In this you can push the element normally but when you pop, it will take the top element and here we will select whatever is the most frequent element. What will we do about the most frequent element and top it? Okay, if I too may have one or two elements whose frequency has increased, then what will we do in that condition, which will be recent edit, not recent. I will do whatever is on the laptop. Okay, so how will we solve this problem and let's see what happened to me here. Given an input and an output, this is just for the sake of example, we will see what we will do with one. I will use yours, which will look at the frequency, we will use another map of all the elements, which will be a map of steps. Okay, and what will it do in this, we know that I your key and value is the platform, so here we have action instead of met. Dip in it, the frequency will still be there, it will bird on one side, okay, when till now I have got 12351 C, then the key over there, which will be the form here, we will do it by doing 123 and the value which will be here in actual, how will this value be straight, if any. If there is any element with one frequency, then for the key of one frequency, there will be some step for the number of frequencies in this set. Whatever element is with two frequency, what will we do for it, we will make two keys and extract key for all that element. If we do the form, then this is my one, I will become you, I will be the office text and one more, we will take it not only here, which will keep in mind, what is the maximum frequency of the element till now, in the city, this is I of MG Road. Okay, what is the confirm operation to be done here is five, so you set five here in the map and its frequency will be one. Okay, so here we will put one five elements with one frequency in the tag and 1 is of Diwali here. File, my value here is ok, then intake is here, please do it and here you have to update it also, you have to update the maximum frequency one till now, then pushkarna is seven, set seven inches, here its frequency is one with one frequency. Agreed here, ok, then what is the use of me here, if I fail here then sorry in advance number five, here we will make it two, okay, if there is a strike here, it will be one strike, then here we will make five strict, this is fine till now. The maximum frequency of is broken, I will make it two here, then what to do here, Pushkarna, I have to please my mother, what will be added here, if it becomes two, then this schedule will go in the two one, it is okay here, after that, if there is a phone here then To please the whole, the support lineage is 241, so this for adventure in the forest, the maximum frequency here will be two only because till now you are the one or the maximum frequency to this or what about mine, 5.5 will be free here, so for three keys, 5.5 will be free here, so for three keys, 5.5 will be free here, so for three keys, we Will do another straight from, it is fine here, this fiber is fine, it has become short, so here we will update the maximum frequency, now we have started, after that, if this is an app, then what will you do with the pop-up, after that, if this is an app, then what will you do with the pop-up, after that, if this is an app, then what will you do with the pop-up, fist comment element, three is thrill. If there is a maximum frequency, then the steps for this three keys will be done on the top element, then make the appointment five-five, done on the top element, then make the appointment five-five, done on the top element, then make the appointment five-five, here, then five, this way, this five will be quartered from here, along with this, we will remove its sequence from here, okay, two. Here you are done, what will we do after this, if you see that there is an operation app, it is also pop, then in that condition, this is the maximum frequency till now 3S is here, then it will fix and check, the entry of the first step is not there but What is this input here, so what will it do here, you will remove it here, you will do it, then toe plug will stop, it will be seen, this is Preeto, it is not Puri, then how will its top element give 797 quota, all this here, change the frequency of P7 here. But will reduce it, 2012 will go, okay, it is opened, then what is after this is the maximum frequency payment, pop here, if you want to have coffee, only then there is two, will check this cricketer, the two step is here, is there MP, if not family, then the top element. Okay, fiber is done, what will happen after that, freedom fighter is done, whose specific here will be reduced here, it is one container, what will happen after that, here I have a gift, so the most frequent element is the note till now f -35, if the f -35, if the f -35, if the maximum number of women is two, then we will see the number of two, but if the number of two has been melted, then it is here - we will do it - unmarried, here we will is here - we will do it - unmarried, here we will is here - we will do it - unmarried, here we will do it for ₹ 1, then here we will see the photo do it for ₹ 1, then here we will see the photo do it for ₹ 1, then here we will see the photo or an ex. Or we will remove it because friends will give the vacancy here. Okay, then we will return it finally because all the operations done till now are over. Now here you will see that there is a tap here because here we are doing push operation. There are 575 youths, there are 575 okay, so now let's vote, how will they do, what have we taken, we, I, you, take care of the left, neither I, you, and strong sense of class 6, on a map, gift pack, poetic sacrifice, I am entering that here take MP ok and one more endeavor we are taking maximum frequency in Sharma carrier which is decided after this what we are doing is frequency value at that time we will press plus what will we do after this In this set, one of the strike frequencies value will be happy here, this rally has been done, then the maximum frequency also, we will see how much is till now Maths Tricks C and D Question Value Yes, is it ok or will we update the maximum frequency? After that, before flipping, we will see whatever my decision is that dates max frequency is not skates pimpri to aa suggested track will be there for which type of entry is it not anywhere then max frequency is to be combined - - do max frequency is to be combined - - do max frequency is to be combined - - do Okay - - done, what will we do after that, let Okay - - done, what will we do after that, let 's see, what is the element, 's see, what is the element, 's see, what is the element, History Maths-Maths sequence Maths-Maths sequence Maths-Maths sequence was top, then what do you have to do for this pick, for this value, the top element is the element which is at the top of the front. Its frequency itself - - will have to be done - - will we do frequency itself - - will have to be done - - will we do frequency itself - - will have to be done - - will we do then what will we do, will we pause it, okay I will express E Yes, everything is fine, we will do it, we will mix it like this and give X a proper treatment Aishwarya, now let's talk. If it happened to the code then is it right here Clear and used oil OK I have used the strike and let's do the thing and tell me a Muslim state do you use it for the step I have become habituated to the max here What happened to me was that today we talked, then for first aid I just went ahead and said that submitted to thank you.
|
Maximum Frequency Stack
|
shortest-path-to-get-all-keys
|
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the `FreqStack` class:
* `FreqStack()` constructs an empty frequency stack.
* `void push(int val)` pushes an integer `val` onto the top of the stack.
* `int pop()` removes and returns the most frequent element in the stack.
* If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.
**Example 1:**
**Input**
\[ "FreqStack ", "push ", "push ", "push ", "push ", "push ", "push ", "pop ", "pop ", "pop ", "pop "\]
\[\[\], \[5\], \[7\], \[5\], \[7\], \[4\], \[5\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, null, null, null, null, 5, 7, 5, 4\]
**Explanation**
FreqStack freqStack = new FreqStack();
freqStack.push(5); // The stack is \[5\]
freqStack.push(7); // The stack is \[5,7\]
freqStack.push(5); // The stack is \[5,7,5\]
freqStack.push(7); // The stack is \[5,7,5,7\]
freqStack.push(4); // The stack is \[5,7,5,7,4\]
freqStack.push(5); // The stack is \[5,7,5,7,4,5\]
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,5,7,4\].
freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes \[5,7,5,4\].
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,4\].
freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes \[5,7\].
**Constraints:**
* `0 <= val <= 109`
* At most `2 * 104` calls will be made to `push` and `pop`.
* It is guaranteed that there will be at least one element in the stack before calling `pop`.
| null |
Bit Manipulation,Breadth-First Search
|
Hard
| null |
210 |
so hello everyone welcome back to our graph playlist and today's topic is topological sorting pass let's say a graph is zero one and two guys right we have jobs where it is saying that one cannot be executed before one before zero right otherwise right so we have jobs dependencies of the jobs we have to let's say finish the project such that dependencies are followed right is so since one and two is dependent on the job zero the first to zero will be executed and now since 0 has been executed this one and two has no relationship or dependency between them right so is the same and that is why okay multiple answers right let us see that second example so let's say you have this 0 2 3 1 3 and 4. so definitely 0 and 1 doesn't have any dependency right will be pointing edges in the head towards them right so success equal to zero and one since zero executed two and three were dependent on zero because they have a Edge from 0 to 2 and 0 to 3 but since 0 and 1 have already been executed so two or three to execute cutting them now this order two of three it can be three two also right you keep two and three have no edges between them so there is no dependency among them so now two and three quarters um then only we can execute two three but since we have zero and one have no dependencies two three and then four I hope we are clear right so similarly is zero one execute together dependencies so here you can see that the zero is our first job graphical dependency negative for zero executive one zero is executed the job one and job two are dependent on it the home pair is executed either you write one two or two one once one and two is executed the another job that is three was dependent on it right other one or two don't execute exactly they have an s23 but B three b x equal to Value three execute okay and then once three is done four and five will be done so four and five you can write it four five or five one and that's why it has the multiple answer okay graphs directed A cyclographically H is valid right and that is why here we have a use case detects cycle detection easy directed a cyclic graph ICS is technique is a more intuitive approach complexity same okay right V plus C and V plus c take care so please pause the video and try to think of approach that how we can you have been given an input graph like this and we can solve the topological sort okay so that's the pseudo code of data political sorting and the idea is that we will keep on printing uh we'll keep on printing the nodes which have been degree as zero right zero and one quick dependency they do not have any edges right any up incoming edges to their nodes and that is why I can say that these jobs will execute first and simultaneously I can say since there is no edges coming towards them so that means in degree 0 right in degree of that particular node okay for the better understanding I have written all the in degrees associated with all the jobs here so first we have to print the nodes which have in degree as zero so these two nodes that is 0 and 1 will have the in degree as zero so first we will print that right so first we will print those nodes and we'll push it in a queue as well okay at this point of time that we will have zero and one then what will happen the second stage is that we will pull or we will remove the first node of our queue and then we will reduce the in degree of all the adjacent node of that particular node so 0. right by one each by one two or three key dependency of dependency degrees figure so this will be the second iteration again we will have the zero community and then what we printed out so we printed first of all zero because we have removed that particular job or here which we have reduced in degree one to zero and then three to two right similarly the iterations will follow up please try to complete the iteration and then we will see ahead so let us see the next iteration similarly M9 is Q major elements say one and two one right and then reduce three and four and three has the Integrity two which is now 3 has the integrity and now which has been converted decrease by one that is one similarly decrease then we again pull out from our q and then this time 2 gets out of this q and then 0 1 2 would be the here the final output uh for this iteration and then two neighbors two can neighbors three right the two has a directed Edge towards three to three nine degrees zero okay and then since this job has been degrees and then again we pull out the current uh we pull out the first node in the queue again so it would be zero one two four and then this 4 has no neighbors as you can see this four has no neighbors has no directed age from 4 to any other node so that is why we do not reduce any in degree for that particular uh neighbors of the four clicking right and now the queue is empty and we have stopped here and you can see that this is our answer zero one two four and three is our topological sort for this one of the answer of the topological sort for this particular graph right and what is this time and space complexity time complexity is that for each and every vertices we are uh we are moving to its neighbors and then we are decrementing the degree by one so it will be V plus e right and what is the space complexity that we are pushing all each and every vertex in our queue so it would be o of v and as we discussed here time stays V plus C and space complexity is O of V okay great so let us move ahead and see the implementation in Java and then we shall see what the code how the code is reacting okay so that's there's a question on the gfg name as the topological sorting I will mention the link in my DSA uh sheet you can access it whereas you can access the syllabus in this uh what you say Microsoft Word link your description that we made a queue and how the graph is given to us in the 2D array list right how it is given let us see uh so this one zero three and two right so for the zero yep okay so how it is uh represented in the 2D error list is let me show you that first okay so the graph given us to is like this right so we have 0 in the middle node and then one two and three is pointing towards it right so that means that if we have to complete 0 then we first have to complete the jobs of one then two and then three right now this one two and three has the in degree of zero so it can be computed in any order like one two three two one three that's it but 0 will be executed only and only if one two and three jobs are executed right so let us see in the output as well so you can clearly see that topological order for the graph is three two one and zero it can be one two three zero as well two three one zero as well right okay so how this thing is stored in our adj in our 2dr list is that we are getting this index one and then we are adding 0 to it similarly so this is the array list add list again it has the arraylist right so it's a vertical error list and then for each and every entry we have one more released in the horizontal direction right so one we have zero so for two is also we have zero and the three is also have zero so it just indicates that job one can only be done and job zero can only be done once the job one is executed right similarly it has a dependency on two and three as well so what's happening is that we are making an in degree array and then we are iterating in this array list and for each and every what to say for each and every entry present in the horizontal error list that is index 0 1 and 2 right so this zero has we can clearly see the zero has the indic in degree of three right so that means whatever is present in this the second part right we need to increase the in degree of that particular thing so that is why we have a for Loop here that first of all we are iterating in the array list right and then in text dot adj dot get of I then we are for each and every entry there is one more error list right so we are using this integer X we are iterating in that particular list and we are increasing the in degree so that means in this particular example we are increasing the in degree of this 0th node and if we have increases three times right okay so the Second Step was in the pseudo code that as soon as if the in degree of any node is zero we have to push it in a queue we have done that and then the third step was but while Q is not empty we need to keep on removing the first node of the cube right and we have to store it in our answer right so we have an answer array here of size V that is the number of vertex that is the number of nodes in our given graph and we are storing that particular U that whenever we remove stored in our answer and the Second Step was that for each and every neighbor for that particular U how we can do that since it's a 2d list so we will use D dot get of U that means we are traversing in the error list for the entry u right and we are getting all the neighbors and we are decreasing its in degree and once you can see we have done the pre uh pre operator here so we first decrease it and if after the decrement by 1 if it is at equals to zero then we again add it in the queue and this process keeps on repeating and we have the final answer like that right so this is the process we already explained we already get that part right okay so that was it and again the time comes today is V plus C and the space quantity again the overview because we are using a queue to store all each and every node let us compile and run and we will see and then we will hit the submit button to verify if all the test cases has been passed successfully so great the compilation has been successful let us hit the submit button also meanwhile it is submitting let us analyze the constraint as well that the time constitute is V plus C right the time complexity is V plus C so we can see the constraint as well the V is pointing to what 10 power 4 and E is nothing but n star n by 2. so however if you sum this V and E according to the constraint it will not exceed 10 part and that is the reason one more reason that the code is getting submitted right so as you can see all the test cases have been passed successfully so this was the standard topological slotting uh that is done by the BFS technique also known as the Khan's algorithm right also known as the cons algorithm okay so let us move back to one variation of this particular question which is present on the lead code with the problem number as 310 I guess okay go schedule two so you can let us read this question and then you will see that how it is related to our topological sorting so you are there are total number of courses you have to take label from zero to num courses minus one we are given any you are given an array prerequisites where predecurrence of I represents two values a i and b i indicates that you must take course B of I before first if you take a course a as you can see here is the dependency so you can take B of I only if you have taken the code say that means there is a directed Edge from E of I to B of I right for example 0 and 1 indicates that you have to take code 0 it indicates that to take course 0 you have to take the first core one that means uh this is the first job that is to be executed so one has a directed Edge to zero right and that is how we need to find if there's any so we return the ordering of the courses you should uh take to finish all the courses if there's any valid many valid answer it is so that's why they are saying as well many valid answers so if it is possible to finish all the courses let's return an empty array right simple says but the code which I just showed you in the gfg let us follow that boilerplate and let us make a 2d array and then the same code will remain same so how we can make the 2D array here okay so how is the graph made is that one and zero they said that this is the first job that is to be completed that is 0 Hazard dependency on one so we will have zero we will have a directed Edge to one similarly zero will have a directed H22 so that means this is like this the graph is uh looks like this when we have completed this two cells so one dependency one two three is also there so one two three and then one to two is also there right so how we can do that so we just have to connect this cell right so one two is also done right so what is the topological sort for this particular answer so what's the in degree let us Define the integration degree here is 0 and then this one will have the in degree as one similarly two has in degree S2 because there is two incoming edges and three has the Integrity as one right so we have to first print who's the integral is zero uh who is in degree zero so the job zero has in degree zero so let us print that and reduce the Neighbors in degree by one so the two becomes one and the one becomes zero now so 0 1 will be printed then reduce again the neighbors of this job one by one right so one the neighbors are two and three so again decrease it to one that becomes zero and similarly three becomes zero right so definitely you can write two three or three two right zero one three two you can also write it like that right so this is your answer and you can clearly said that these were all the courses they are denoting the different courses so definitely if we have a particular topological sort right which is with which has let's say this is an answer array which has the length equals to the number of courses was given right so if the length of this answer is equals to number of courses that means there is a path that the there is a path all right that's what is happening we are making a 2dr list right we are making the directed edges um we have just passed this graph that is present in this 2D error list and the code remains same that I just explained even the GLT right the step one step two one step three like I have exactly copied the same code from there once we have understood once then we can just apply it somewhere else as well right at last foreign as said by the question else you just have to return that answer right okay great so let us hit the submit button here as well we will verify it and then we'll end this video and we will discuss that what are all the next question would be that we'll be taking up so great as you can see that the solution has been accepted so let us get back to the syllabus of the graph so I have directly jumped to this question is so once you are done with this topological sort uh using the Khan's base algorithm that is the 11th number of question this sector 12th number question is very simple we just have to follow the same code and you have to see that it will count if the count is not equals to the number of vertices that means we have a cycle in there so let me give you a slight um exam one example that how why it is not possible for the uh a site the cyclic graph right so let me take an example for you okay so let us take this example let us take let me draw the example and come back to you okay so let us this example where the cycle exists as you can clearly see yeah uh this one two and three is making a cycle right how we can say that there is a cycle but it's impossible directions you can clearly see there is a circle making there right so that's why I'm saying there is a cycle into one two and three and I have mentioned the in degrees as well so zero is zero for the one there is three uh edges coming to it so that's three and for two there is only one so that's one and for three there is one incoming edges so that's one again and similarly for four so for four it would be zero it however it can zero one so zero right so first what we will do that we will print the edges uh we will print the vertex which has the zero in degree so it would be zero and four right so let's say we have we've been processed this zero and we will decrease the in degree of all its neighbor power and so what's who's the neighbor of zero is one let's decrease it in degree by one so three becomes two right now we will process four again now we will again remove the uh we'll process which one four so uh at this point of time it will have zero and four so once we print the 0 right then the Q will have four just four right because decreasing the neighbor didn't get me any answer of in degrees equals to zero now we process the 4 right he process the phone what is the neighbor of four that's only there is one node that is one right so let's decrease the in degree even a decrement the feed in degree by one and that becomes one right so now there is no node in my queue that's empty right so what to do now definitely you cannot now you do not have any node because right so that is why I said that is why it said that it is not possible for a cyclic graph right cyclic graph and that's our second question in our syllabus that to detect a cycle in uh which one indirected graph right answer if that is equals to the number of nodes in that graph but if my answer length as you can clearly see my answer is just 0 and 4 with length is 2 and 2 is not equals to the number of nodes in this graph that is five so definitely there must be a cycle topology right so I've just given you two hamare ugly uh and similarly we will follow this all the questions ahead right till then keep learning keep going goodbye and take care
|
Course Schedule II
|
course-schedule-ii
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return _the ordering of courses you should take to finish all courses_. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** \[0,1\]
**Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is \[0,1\].
**Example 2:**
**Input:** numCourses = 4, prerequisites = \[\[1,0\],\[2,0\],\[3,1\],\[3,2\]\]
**Output:** \[0,2,1,3\]
**Explanation:** There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is \[0,1,2,3\]. Another correct ordering is \[0,2,1,3\].
**Example 3:**
**Input:** numCourses = 1, prerequisites = \[\]
**Output:** \[0\]
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= numCourses * (numCourses - 1)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* `ai != bi`
* All the pairs `[ai, bi]` are **distinct**.
|
This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
207,269,310,444,630,1101,2220
|
564 |
hey everybody this is larry this is me doing a bonus question for the day an extra question hit the like button hit the subscribe on drama and discord especially like if especially if you'd like to see more of this um it's me trying to random one that haven't done before so i do it to do but some of these are as you can see premium so i have to keep cooking until i see one but yeah let me know what you think because i don't know i might not do it anymore if people don't you know if it's not something people want to see but either way i like to do a few more problems for so for today it's just uh additional good practice anyway today's farm is 564 find the coast is palindrome i haven't stopped this before because okay given the end as energy we turn the closest integer not including itself which is a pendulum if this is the tie return the smaller one so it could be bigger or the smaller one so that's why okay uh which is not itself that's a little bit awkward okay so this is that it fits long that's fine uh okay let's see right well i mean okay let's i guess first i'm gonna it this is one of those problems that i feel like will be uh um this is one of those forms i feel like it will be uh um will be like uh what i was what am i looking for the word was constructive algorithm right and what i mean by a constructive algorithm is that you have a strategy try to figure it out and then maybe just find some proof 4c way and kind of put it together for me i or like some kind of strategy right maybe sometimes it's greedy and sometimes you just do it to figure out how to like if you're able to prove first in a smarter way and and the question that i and one idea that i have and i don't know if this is true but let's just say i have like a big number like this is my numbers say then i'm thinking that you know the answer has to be well i guess my question is does the answer have to be um like do we take the prefix one at a time meaning okay let's just say you know let's just say we this is the prefix then we would try to convert it to three four five three two one right it's still not a possible solution um yeah we could do is that really it i mean there's obviously the other way of you know trying to do the prefix but i don't know that makes sense like if you commit it to nine eight seven six five uh six seven eight nine or something but you can even if you're consistent about it you could just generate this and it'll be the same thing but the idea behind the minimum difference is that you only want to do the suffix i think right and then the question is let's just say we do use this algorithm then the idea is can i do is there a way that i can do better i don't think that you can well okay so in this case this is worse right clearly but let's say you have another number right let's say your number is 987654321 um i guess it's still the same way right i was going to say that you can try to choose a smaller number right but of course in this case your difference is like eight hundred thousand so then it won't really make sense and so even though you get a bigger number you still want something like this right okay so the still question though is can you do better like and they will maybe a little bit tricky right for example maybe we can do something like one two three five three two one right what is the difference between here um i mean this one is gonna be a bigger number because we bigger difference just because this one number changed and that's a more significant digit right is this good enough to yolo i think for i think one digit is the only case where you do this funky thing um so maybe we can do something even just lazy if length of n is equal to one then we return into n minus one and then string of this or something uh and this length is zero then it has to be uh okay fine if enter n is oh it has to be one okay so we don't have to worry about it i'll just look at the constraints oops um it's okay and if not do we always just return it um okay this is what i'm going to do i'll show you this is i'm going to try to do this and then what i am going to do is um what i am gonna do there may be some really tricky ones right i think the tricky thing is what happens if it's a palindrome i think that's the answer that an answer for example what if we are already given this number right then what's the next biggest number i guess in this case we would have to change this one because then now we change this one right so i think that's maybe the idea um and then also this is a even oh sorry this is the odd digit thing so we have to try some even digit numbers so let's say we only go up to eight then we go one two three four three two one and then to get the next one we get choose this one number so okay so i think the idea here is now take the first half okay so maybe that's right maybe i don't even need this to oh actually i messed did i mess up well no i mean i not yet anyway because i said that for here i can go 4-4 but and said that for here i can go 4-4 but and said that for here i can go 4-4 but and then we go to 5-5 but we would also then we go to 5-5 but we would also then we go to 5-5 but we would also maybe test both three uh well in this case actually the five is in the middle so i lied what we could have done is just change this to six or change it to four in this case um yeah maybe that is the answer is that we take half so left is equal to and the length of n over two okay i think that rounds down so let's try some examples really quick uh i'm always very bad at using this note notation just something i'm not used to i suppose coming from c plus or something so one two one i guess the one okay so we are definitely messing missing the odd number okay um uh the one got skipped earlier maybe we don't need this actually oh for now so yeah okay so that means that we want this i think that's probably what we want okay right so maybe just to kind of minimize the number of possible mistakes in generalization let's uh let's actually just change this to if this is yi if this is even then we have this thing uh i mean this form is right and then we have this thing right just reverted this so this is the right side and then we have uh try uh this is attempt maybe this is go to left press right and these strings are at most like nine characters so we'll be okay and then here we just have to check if a temp is equal to n then we have to go do another thing otherwise we return the temp because that's good or maybe we just do this um and then if a temp is you go to n then what do we do well we take so left is you go to end of left um do you wanna choose plus one or minus one i guess plus one n minus one has the exact same thing so and in that case we'll choose minus unless it is a and this is something weird right because for example let's say we have uh one zero um and then now and then this is the right half um if we try to subtract one then we have nine well i guess that's no because then now it would have two fewer digits which is great for getting a smaller number but then now the difference is so big versus just um you know one zero one i mean that's even i mean that's pretty good too okay so i guess we just tried both i think that's the idea um i maybe could prove it but i think this is just safer right so okay so i just try uh let's just say x is equal to um into left minus one i'll just say new left maybe yeah and then you're right is you go to um you know just minus one and then you just have new number is the new number is equal to into nf plus and right yeah okay uh and this is maybe we'll do negative maybe that's what it means and then now we have plus one of this so we do the same thing this is i probably should uh you know make this cleaner but i'm just trying to this is more of a proof of concept and it's okay when you're you know you don't have to write queen code the first time i mean you should know you strive if you know what you're planning out you should do um of course in software engineering and regular software engineering you generally try to think about the problem a lot more before coding but for me for this one for this particular problem it's more about like the exploration right so the code maybe is a little bit ugly but you know you can improve on it later and then anyway so if um okay i need to do a little bit about that so let's just say current as you go to enter n um so if absolute right and we know that this number will be smaller or this number will be smaller so anyway so if this number is greater than this number then we return uh p num right else we return the pen num uh i think this is mostly right but i'm there is some uh action that we can do here but we'll see so now let's say we have odd number of digits i think we do the same to be honest so maybe i don't oh i think the difference is this part the reflection part um yeah okay maybe for now we just copy and paste this is very yucky though do not advocate this but nonetheless um how do i do this uh let's just say we skip the last number and then we flip it i always don't know the exact notation that's why this is a little bit awkward um but nonetheless and we're only dealing with 9 10 digits so that's why we can get away with being as lazy as possible with these things this looks good for these inputs but you know that doesn't mean enough if you ask me and then i'm just like banging on the keyboard of course um all right let's give it some spin okay so we definitely have a wrong answer that's uh not great but expected is this how do i try this so i turn it to 1000 on the left side right maybe i just do just wrong i mean i'm i know there's a pseudo cheating but we could have checked this one thing that i was going to do is actually write a brute force method um and i was going to maybe highlight it but now we can just debug this part for now but let's see uh okay well this is the only case where this came up which is actually really awkward but i only have did i only have odd number digits by accident yeah well or at least once that did not oh i guess this part is the case um okay but this is why i put this in there right so we did try both these scenarios did i have a sign error why do i return this number if the absolute value of this is greater than this and we and it is right this is two thousand this is two huh did i mess something up did i add an extra c oh hmm that is the tricky part okay so because this is now a thousand we don't try to okay so we have to be a little bit careful that's fine um because if you have even number of digits if you create a new digit that actually creates two new digits by eyebrow test i actually didn't mind them up but now that you know i see it that makes sense um okay i mean that's fine what we want to do then is um just maybe do a third one i suppose uh where um let's see okay well in this case if we subtracting a digit i think is fine right because we know that the to plus one will fix it right because the because if we subtract an extra digit that'll give us a number that's too big but also not so good right because if i don't know that i put this in an example and the thing now that i think about it maybe i can do it i was trying to be lazy but i think i had this here but i didn't do it for even digits so even digits is the pain in this one because in this case what i expect is a lot of nines but it might not be because it thinks that it only has six digits so it really eliminated it so yeah okay so okay this is expected given my input so yeah so that's good that we caught it and this only happens for even does it only happen to even digits let's see right if we have yeah i guess so because with odd number of digits if you lose a digit no well uh trying to think well i mean i think the thing is that now we just try all four things right um yeah okay so that means that in that case there's no difference between these two we could rewrite this it's fine um we have to because now we can just do these things in a good way um okay so that means that did uh well okay then we can do something like we can rewrite this part real quick just put it here for a second because now everything is the same except for the top part and then now we want to just try all four possibilities really i'm a little bit lazy so i'm just going to do something like uh possible as you go to do um let's just say uh and num uh apps of current minus and num uh actually the other way around so that we could sort by this in case you know you haven't seen it yet and then yeah and then now we i'm still gonna do it this way but i'm gonna make it a little bit more copy and paste friendly uh maybe in this case we can even do something like for x in when in uh negative one we do this thing and then now we can just do um plus dx right and then here we can also do we use this anyway um the same idea but now we only this is the only different thing but that's fine maybe i'm okay with just leaving it like this for now and then back to putting this and then now we uh we saw it real quick or you could just get the minimum element i guess but anyway you get the possible uh of the first element and then one and then we want the string version of this and that's maybe it we'll see oh huh i thought i tried all the possibilities but maybe i missed one oh i still have wrong one i thought i tried to do that um so now we have maybe i didn't think it i mean i did make the code tighter um and that's what i mean by sometimes you know once you finally finish exploring the queen called between it what i need to do is going from even numbers of digits to odd number of digits um that's the point that actually i didn't remember to fix it because here it just um it handles the other one where you have odd number of digits and then now you want to you know uh there's like some mosquitoes i'm trying to kill okay you gotta it's not mosquitoes it's like a mini fly thing maybe somewhere again but uh but yeah we have to get it to odd digits um and because the way this so the other thing that was attempting was 999 or something like this but six digits so let's print it out real quick i just i'm just curious uh okay yeah so it can it was it one the uh pattern is 1000 so it tries to do uh 10111 that's fine this was fine as well huh did i miss a digit here maybe that's why because then it goes 999 but it's not enough digits that's the thing that i initially said uh and that's fine what we how do we want to do it is that you know if we lost a digit we add a nine is that weird uh okay maybe that makes sense okay let's give it a spin then uh would it be this one or the other one so we have four digits we lost a digit and we want it to be so if we have four digits then we want to get it to seven instead of six right in that case it would just be this because it'll be even yeah and then it'll be just plus nine right because you lost a digit um let's see if that works i don't know if this is a good enough hack to be honest uh is that we still want the same answer no wait what are we wrong on that okay so this is an early one i did we just skipped over it um did i not do this one i thought we did this so for our number we have one thousand thing and then we cut it to 999. here we only do this part because we want to do it but then now we want to get rid of one of the digits no wait why is that one oh no uh of 999 but then the way that we did the reflection it would only be that but i thought that this would fix that huh let's see all right let me put it in again which one was that one i guess next to five two three whatever so it's this input and i guess oh i see now this is right i think we generate the right thing we just didn't minimize the uh huh doesn't it all right i'll just put this in the back to see what it's doing i think maybe it's still right but maybe i'm and i just didn't like sort it correctly or something but that should be okay maybe let's see okay so here we have and one million uh clearly we're oh i see we're just returning early that's why oh i see because we're returning early we're using our original strategy this actually folds us because we don't add it consider it to the other thing okay i guess what we do here then is just add it to one of the possibilities and we don't really terminate that's basically it uh yeah possible. uh absolute of attempt minus oops get away um and i think that should be good i said now it should sort by because i didn't think that sorting okay i have to make sure that uh and because i didn't think that was a sorting issue even though it didn't make sense because this would have one the number one and then this would you know um this would be the actual number which is a bit bigger than it wouldn't hybrid correctly but uh okay what are we doing wrong here still who am i returning oh wow we're wrong in a lot of places but why oh we have to get rid of the zeros i guess that's the okay i guess that we had an if statement here but then i just took it out for some reason uh with a temp it's equal or not you go to current then we do this thing that's what i meant to do but i think i was just so focused on making sure that this is right i forgot about it um oops like something like that making a silly mistake there but it's an annoying problem but that's what i meant by i had this feeling that this is a thing where you just this is a thing where you try a lot of combinations and one of them will have to be good using a combination of heuristics um oh no did i mess this up oh this oh huh okay i guess the two-digit case is very okay i guess the two-digit case is very okay i guess the two-digit case is very weird um this is a very easy to mess up one even as we spent a long time i was focused on these other weird cases that i didn't consider to the one the cases of one number and stuff like that i should have added more though i just kind of got distracted about it let's see okay so yeah uh two is quitting well which maybe i shouldn't even look a bit all right let's think about how do i want to do it i mean i don't think these are special cases i don't know why i can move this left and right but i can't move this up or down just to look at more test cases which is very sad but okay 11 what is 11 doing all right let's put it back out again that's also why i forgot about this part because that's why i wasn't putting out as much as i thought um okay so we were trying out for 11 i guess i could just print out 11 as well the answer is nine i think i thought one of these would generate nine for 11 because then um the left would be one minus one would be zero i think nine is just a possible answer in general so maybe we should just try nine always uh because if it's two digits it could really be messy um yeah it's kind of like this one i suppose in that way okay nine and i guess that's 11 10 okay let's just always add nine and see if that fixes it oops okay so there's still a wrong answer and that is on oh well if i am such a dum-dum if kern is not you i am such a dum-dum if kern is not you i am such a dum-dum if kern is not you go to 9 i suppose though we should just filter out the zeros but all right let's give it a spin hopefully this is right maybe i should have tried three digits but yeah okay i thought that just gets figured out isn't that one of the things that we test i don't get it don't we take half and then try to oh huh i guess we missed that one then don't we most of this isn't just oh no this is it's right but we just don't um because it tries to do 99 for odd numbers and they try to do 100 but then it tries to do um so if wow this is sloppy but hard in general but yeah now it's it goes to 99 tries to do 100 which it tries to do this and then also uh you know this but it never tries to do this um yeah so i don't think i mean this is probably more than this case they're just i did just wear this as well um ah yikes what do you think i think in that case i wonder if it's like worth doing like an all nines like always check for or nines or and always check for one zero one or whatever it is um i think these are the only weird edge cases as well so maybe i should do that what do you think i know you can answer me or at least i can't hear you so yeah i think that's the way i'm gonna do i think that those are the older edge cases anyway and we could have written things in a way that would address it but is that really is that good enough because the problem isn't getting a pallet drum it's about getting the closest one and yeah this one is a little bit awkward with respect to uh everything is incremented you can even think about a thousand and a thousand i guess a thousand would fix but not 999. um all right let's give it a try i don't know if i you know um yeah i don't know if i you know whatever but i just say 20 it doesn't matter because i'm a little bit lazy if now and then yeah someone like this right that's for one way and then we want to do the other one where um you know maybe someone like times or plus times x right plus one right something like that and we could even just make it equal it's fine but all right let's give a spin let's get let's give it us oh we already did put it in okay let's give her a quick submit i'm really worried about just like carries right but this is a double caviar i think that's the issue um as you can see we finally got accepted um we do a lot of stuff uh but this is mostly right i suppose um yeah what is the complexity well this is i want to say constant-ish but maybe all i want to say constant-ish but maybe all i want to say constant-ish but maybe all of x where x is the number of bits which is log of n the number of digits so in theory this is linear ish it's not very pretty linear for sure but it's linear-ish it's linear-ish it's linear-ish though maybe you could say this is quadratic maybe um because the 20 is maxed by the number of digits of n so this is o of n and this is also of n to generate so yeah maybe this is n squared but either way yeah let me know what you think this is a very hard problem let me know what you think stay good stay healthy to good mental health i'll see y'all later and take care bye yeah this is tough
|
Find the Closest Palindrome
|
find-the-closest-palindrome
|
Given a string `n` representing an integer, return _the closest integer (not including itself), which is a palindrome_. If there is a tie, return _**the smaller one**_.
The closest is defined as the absolute difference minimized between two integers.
**Example 1:**
**Input:** n = "123 "
**Output:** "121 "
**Example 2:**
**Input:** n = "1 "
**Output:** "0 "
**Explanation:** 0 and 2 are the closest palindromes but we return the smallest which is 0.
**Constraints:**
* `1 <= n.length <= 18`
* `n` consists of only digits.
* `n` does not have leading zeros.
* `n` is representing an integer in the range `[1, 1018 - 1]`.
|
Will brute force work for this problem? Think of something else. Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible? Do we have to consider only left half or right half of the string or both? Try to find the closest palindrome of these numbers- 12932, 99800, 12120. Did you observe something?
|
Math,String
|
Hard
|
1375,1997
|
1,487 |
hey everybody there's a slurry you're watching me solve this problem live during a contest I'm gonna stop the explanation and then it's going to go into some code review some times and then just me working on a palm let me know what you think about this format hit like button to subscribe one join me on a discord link below and I will start now cue to making filenames unique so this one the tricky part is that a couple of edge cases and the second trickiest part is that the N is 5 times 10 to the 4th and what that means is that you cannot do a quadratic time algorithm meaning no n square you have to do an of n or n log n depending on what language you're in and that's it so that I do and I actually got just wrong the first time but the idea is that you first yeah if you look at the name and of the name you haven't seen it before then it's good you did and then you keep track of the like that you or you if you use it again you have to watch it again right and then later if you do see the name then you look at the counter that it was previously incremented by one so that the next time you see the name will be +1 and then you just keep on looking be +1 and then you just keep on looking be +1 and then you just keep on looking that way and that's pretty much it really you just increment it and then just check to see if it's in it if it's not then and this should I think this should always be okay otherwise it just had a few times but this already makes it this in fee we could still be n square ish but it's fast enough yeah so that's cute too but just keeping track of the previous one and here we can actually even and we should have keep track of the previous one as well but yeah actually I don't know I did it this way because if did I think I just kind of did it really so how I would do it again is that if this is the case that I would to counter is you go to previous name and then just do something like the same thing as before yeah and then previous plus one and then just keep going right so we've you do something like that you get down to linear time the space is also going to be linear B because you have one entry in the previous for each string and that's pretty much it's pretty hard for up to two but on an interview problem this is a query a little bit harder than I would expect only because maybe in 45 minutes is okay but it's still a little bit harder than I would expect in competitive I guess it's okay it is what it is yeah and especially but this contest I thought that this was as contest as it goes but yeah to making file names unique give me a way of string names out of this one yeah so this one I to be honest I looked at it I was like okay that looks straight for it I made a really silly mistake and that I didn't look at the end constraint order constraint n so I actually just do it didn't ieave me and then I got a time limit exceeded which cost me five minutes but not a big deal for this form o contest because the rest of the contest was a little bit slow anyway okay but yeah so basically what I'm doing now is I was just like oh yeah they're student naive album that seems play straight for some of this is because usually for q2 on Alico this is straightforward and you just don't have to think about it and it is usually right but I had to but I just had a blind spot there's no way about it I didn't think about doing this and I was like okay let's just do it over you know yeah in the indecision on the implementation but that's pretty much what I do this is incorrect it gets time to me to exceed it and as soon as I saw that I was like ah and then I looked at n which it you'll see in a second this is just implementing little bit slow actually to be honest bit so I rented it looks okay let's a minute but this time I get time limit exceeded unfortunately well now tiny makes it so I was like oh I mean the first thing I did was I looked at n I was like oh yeah of course I'll be time to make seeded so basically what I did after that was just create a lookup table that allowed me to remember the last number for a given name that's surprising I was checking for you I was just like okay let's just have a look up table well you know don't worry I'm also just double checking on the constraints so that I can make sure that I am able to do what I wanted to do yeah and here I'm just trying to make sure that my I'm not getting off by ones and stuff like that little bit slow right now but I think I was just in this size of it as to what I wanted I wasn't sure that this would be good enough yeah I went a code I was like this isn't right and was a little bit sad but basically I just have a typo on line seven that took a long time to catch just one of those days this was a bit of a hard contest for me I was like there's no even SS not even in theirs and somehow never went so there must be other issues when nothing print I was looking up and to be honest I think it was just that something order comes like the autocomplete on the thing on the editor god made like I don't think that was me but I mean I'm well because why would I do that and I was like ah this is nice I wonder code it looked like it finished pretty fast so I was like okay the answer looks good let's just submit spent about 2 min
|
Making File Names Unique
|
cinema-seat-allocation
|
Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets.
|
Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families.
|
Array,Hash Table,Greedy,Bit Manipulation
|
Medium
| null |
191 |
hi guys welcome to algorithms made easy today we will see the question number of one bits write a function that takes an unsigned integer and return the number of one bits it has this problem or this particular thing is also known as hamming weight the follow-up given with this question follow-up given with this question follow-up given with this question is that if the function is called many times how would you optimize it in the example one we see that there are three number of one bits and so the output is three while in the second example there is only one present and thus the output is one in the third example there are 31 set bits and thus the output is 31. now let's go ahead and see how we can solve this question the first approach is looping on each bit and counting if it is a set bit so let's take this example and here given n equal to 11 that is 1 0 1 i am just taking 4 bits for now but in the actual scenario it would be a 32-bit integer 32-bit integer 32-bit integer so we will have 0s on the left so let's take this example and we know that when we perform an and operation on a bit it gives a resultant 1 when both the numbers are once for example here this both are 1 and so 1 and with 1 will give me a 1. this can be useful for finding whether the bit is set or not so this is what we are going to use in the first approach so let's see what we are doing over here we are taking the number and we are taking a mask would be a number that has a one in the bit position that we are going to check so we'll start with the last bit and we'll keep on shifting this one bit one place in the left in each time we are looping it so the shifting of one bit would eventually turn out as checking of that particular bit position in our original number so in this first one we are checking this number and since this is not equal to 0 which means there was a 1 present so we increment the count now we take another mask wherein we shift the mask one bit to the left and check the second bit since this is also one we'll get a one in the result also and so the result would give a non-zero and so the result would give a non-zero and so the result would give a non-zero number and since we have a non-zero number and since we have a non-zero number and since we have a non-zero number we increment the count similarly we check for third bit and here as the bit was zero in our original number we have got a result to be zero and so we do not increment the count and move further checking for the other bit and here we get a non-zero number and we increment get a non-zero number and we increment get a non-zero number and we increment the count to three so what we are doing here is we are taking a number a mask and at each step we are shifting the one present in the mask by one position to its left for the result we check if it is a non-zero number that we check if it is a non-zero number that we check if it is a non-zero number that means the bit was 1 in our original number and thus we increment the count so this was the first method in this particular approach how many times are we looping we would be looping 32 times as we have got a 32-bit integer despite we have got a 32-bit integer despite we have got a 32-bit integer despite of the number being 0 or 1 we always have to check that particular bit in this particular approach so how can we optimize this let's see another approach which is flipping the least significant one bit in this we are taking the number and we will do an and operation with number minus one this operation would give us a result with the flipped bit for the last one that was present in the original number so this is the least significant one present in our number and in the result it got flipped so in each time we are flipping we will be incrementing our count so this given number is 11 its and operation with number minus 1 which is 10 would give us 10 as our new number now we need to count the ones in this new number so we take it as a num and we do its and operation with number minus 1 which is 9 and this would give us 8 which is our new number with this we'll increment our count as we have already flipped the last one bit again we will do an and operation and this time we will get the number as 0. now since we have got 0 we know that there is no one present in this particular number and so we can stop so if you see the difference the number of times we looped in this particular approach is the number of ones present in the number the worst case for this particular approach would be 32 which is of one but the best case would be the number of ones that are present in the given number so these were the two approaches one was the name and one was the optimized approach so now let's go ahead and code it out so let's start with the first approach wherein we'll take count and mask now we'll take our loop which would be from 0 to 32 in here we check if the and operations give us a non-zero number or not so we take n a non-zero number or not so we take n a non-zero number or not so we take n and with mask and whether it gives a non-zero number or not if yes we do non-zero number or not if yes we do non-zero number or not if yes we do account plus and then we also need to update our mask so mask becomes mask left shift by 1. finally we return the count let's run this code and it is giving a perfect result let's submit this and it got submitted the time complexity is of 1 and the space complexity here is also o of 1 but as we already talked about it would always loop 32 times so now let's go ahead and improve this approach so we will take a count variable for our result which would be initially 0 and we loop while n is not equal to 0 we'll keep on flipping the least significant set bit so we do n equal to n and with n minus 1. with this we will also increase our count at the end we need to return count fine so let's try to run all the test cases and that is accepted let's submit this and it got submitted so the time complexity for this is also o of one so now we'll try to convert the solution into a recursive call so for that we'll take a base condition that would be our exit condition if n is 0 will return 0 if n is 1 we return 1 and this while loop goes away and we recursively call the same function with n and n minus 1 and each time we also need to add 1. so let's run this and it gives a perfect result let's submit this and it got submitted so the time complexity remains the same we just converted it into a recursive solution instead of iterative one so that's it for today guys thank you for watching this video if you want to learn a similar question you can go for hamming distance the link for which is given in the top i'll see you in the next one you
|
Number of 1 Bits
|
number-of-1-bits
|
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)).
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
**Example 1:**
**Input:** n = 00000000000000000000000000001011
**Output:** 3
**Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits.
**Example 2:**
**Input:** n = 00000000000000000000000010000000
**Output:** 1
**Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit.
**Example 3:**
**Input:** n = 11111111111111111111111111111101
**Output:** 31
**Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits.
**Constraints:**
* The input must be a **binary string** of length `32`.
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Bit Manipulation
|
Easy
|
190,231,338,401,461,693,767
|
226 |
Google ninety percent of our Engineers use the software you wrote but you can invert a binary tree on a whiteboard so off well Max how well got rejected because he didn't know how to invert binary trees in this video you will learn how to invert binary sheets so you can get into Google during the interview we know that a binary tree is a tree in which every node has at most two children and to invert a binary tree is to swap the position of the left and right children of each node the intuition behind this problem is to use recursion to break it down into similar sub problems with a smaller input a key observation we can make is that inverting a binary tree is the same as inverting a lab sub tree and the right sub sheet and then swapping their positions for example suppose we want to invert this binary tree rooted at 4 we first want to invert the left sub tree rooted at 2 and invert the right side tree rooted as seven then swap their positions so now we have two sub problems with two smaller inputs we then continue the process with the same approach and we observe that to invert these sub trees we only need to remember two Leaf nodes which can be done by directly swapping their leaves after finishing inverting these subtrees we'll go one level up and swap their position so how do we come up with a formal way to solve such a problem this is where recursion can sing we can define a recursive function that takes in the root node of the tree the base case is that if the Runo is known we return none otherwise we invert the left and right children with two crazy calls and then swap their positions the recursion continues until we reach the leap nodes of the tree at which point the function Returns the lead node stem cell and the leaves are swapped it as a result the function is able to invert the entire tree starting from the rule node and working its way down through the tree to the leaf nodes this way we can invert the entire tree in a single function call this is the full solution to problem in verbinary tree I hope you found this video helpful please like subscribe and leave a comment thank 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 |
518 |
today we are solving coin change problem we are given an integer array coins representing coins of different denominations and an integer amount representing total amount of money we are supposed to make and we are expected to return the number of combinations that make up the amount it is important to note that we are expected to return the number of combinations not the permutations and they also mentioned we have infinite supply of each kind of coin let's try to solve this example how can we make five bugs using coins one two and five one way is to use all ones the second way is to use three ones and one two Third Way is 1 one and two tws the last ways to use just one five you can verify that these are the only four ways to make five bucks um there are no other ways that amount to five bucks so how can we come up with an algorithm to do this task the hint to this question is in the question statement itself where they expect us to return the total number of combinations so we have to figure out all the combinations possible that make up the expected amount just to save some time I've already written down all the combinations for the given example I have represented this problem as a function make that returns number of ways to make five bugs using cons one 2 and five as you can tell you can divide this problem into these sub problems where this sub problem indicates number of ways to make five bugs using just the coin one just the coin two just a coin five coins one and two one five 2 five and all three coins as you can see you can divide these sub problems into more sub problems for example number of ways to make five bucks is equal to number of ways to make five bucks using just the coins one because we picked Z coin two plus number of ways to make three bugs using just the coin one because we picked one coin two plus number of ways to make one Bucks using coin one because we picked two coins too similarly number of ways to make five bucks using all three coins is equal to number of ways to make five bugs using coins one and two because we picked zero coins 5 plus number of ways to make zero bugs using coins one and two because we picked one coin five you may be able to recognize a pattern here the way to divide a problem into sub problem is by picking zero coin of final denominator by picking one kind of final denomination two kinds of final denomination so on and so forth you may be able to also see that some of these sub problems are repeating for example this sub problem is same as this problem and this problem is same as this problem so this clearly indicates this is a dynamic programming problem and we should be caching these results of these sub problems so that we can reuse them in the recursive relationship and based on these problems I have written down this recursive relationship where number of ways to make amount a using coins 1 to coin n is equal to number of ways to make amount a by picking zero coins c n and keeping all the other coins from C1 to CN minus one plus number of ways to make a minus CN amount by picking one coin CN and keeping all the coins from C1 to CN we keep using this recursive relationship until we hit the base case where we have to make amount zero using any number of coins and there's only one way to make amount zero is by picking no coins at all now let's write the code for this problem we have been given n different denomination of coins where n is one the coins and we are expected to make amount of money and we're expected to return number of ways number of combinations to make that money so we defined this function make before that Returns the number of combination number of combinations to make the amount using all the coins and the way I represent the usage of all the coins is by using the indices here n minus one where n minus one in indicates that we're using all the coins starting from index zero all the way up to index n minus one so we return this next we have to define the function make which accepts an amount and the indices up to which we are allowed to use the first thing to write in any recursive function is the base case where if the amount we're making is zero there's only one way to make an amount of Zero by picking no coins um next we have to write the recursive relationship which we derived before I'm going to put that on the bottom left corner of the screen so number of combinations to make amount a up to index I is number of combinations to make the same amount a without using the F coin of the final denomination plus number of ways to make the amount a minus value of the final denomination and that's our recursive relationship um in this we need to make sure we take care of some of the edge conditions where in this case where we do not pick the coin of the final denomination so we get rid of this coin So eventually we would have gotten rid of all the coins in the list so that's when I is less than zero we return zero because there are no more coins left to pick and also the another age case is uh we can only pick a coin if the amount we are supposed to make is greater than or equal to the value of the coin otherwise we return zero so that's our recursive relationship um let's try to run this let's see again oh okay here I missed an argument I okay to run this now let's submit this is most likely going to return a time limit exceeded error that is because we are not caching the results of the sub problems there are a lot of overlapping of problems yeah as you can tell we got the time limit exceeded error because there are a lot of overlappings of problems and we are calculating them every single time so the way to fix this error is to cach the results of overlappings of problems in a dictionary so if we overlapping some problems is if we have if we call the function make with the same a and I again and again those are overlapping of problems and if we have already seen those arguments before we just return the cast result if not we save the result and then return it so this should fix the error there we go this is the top down approach of solving any dynamic programming problem where we started from the final amount we are supposed to make and then divided it into multiples of problems um and Tackle those sub problems individually and then finally combine the results of that this is the top down approach the other way to solve this problem is the bottom up approach where we solve for the sub problems first and then combine the results um of those sub problems so that is an iterative approach um I usually prefer the top down approach to solve any dynamic programming problems but it's good to understand the bottom up approach as well next let's try to write the code for the bottom up approach I'll comment this part out um in the bottom of approach we have to iterate through all the possible of problems so all the possible values of a and I and then cache them so let's define a two-dimensional array to Cache these two-dimensional array to Cache these two-dimensional array to Cache these results of sub problems where one of the dimensions is the amount we are trying to make M plus one is because our arrays are zero index um and the second dimension is the number of coins so this is the three dimension array where we save all the results next we iterate through all the possible values of amount and the coins for oh before that we need to um we need to save the base cases first where the amount we're trying to make is zero um for I in range one DP of for any number of coins left if we are trying to make the amount zero there's only one way to make it now we iterate through all the possible um all the possible coins and the amount we are trying to make I in range one and next we're trying to make the amount a in range one to the final amount as you can notice we're starting from the lower end of the range and then building it up towards the final problem so let's copy the recursive relationship here this is the recursive relationship we uh want so DP of I and a indicates the number of combinations to make the amount a using I coins is equal to number of combinations of making the same amount a without picking the final coin that means we have IUS one coins left plus number of ways to make the amount a minus the value of the final coin IUS one because I indicates the number I indicates uh the number of the coin and I - one is its indices so the amount we I - one is its indices so the amount we I - one is its indices so the amount we are trying to make is Aus coin of i - are trying to make is Aus coin of i - are trying to make is Aus coin of i - one with all the coins left so these this is the recursive relationship and we can use the final coin only if the amount we are trying to make is greater than or equal to the value of the final coin else it will be zero so this is the recursive relationship and eventually we return the solution for the final problem where number of ways to make amount a using all the coins so this is the final result let's try to run this passes all the test cases submit this okay and as you can see the submission went through so but there's one way to optimize the bottom of approach um as you can see in this recursive relationship um the current state which is the number of ways to make amount a using I coins is only dependent on the previous state I minus one so we do not need the entire twood dimensional array to find the value of the current state we just need the value of the previous state so we can use one dimensional aray we don't need both the dimension and that Dimension is the amount so let's try to change this array into a onedimensional array with just the amount we can get rid of the coins Dimension so the same here we get rid of the coins Dimension number of ways to make an amount zero is there's only one way um same here get rid of the coin's dimension same in the return value as well try to run this passes all the test cases and the submission went through if you found this video to be useful please like the video for the YouTube algorithm and if you want me to discuss any specific problem please comment on the video I'll make sure to post something on that and I will see you in the next video thank you
|
Coin Change II
|
coin-change-2
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
Array,Dynamic Programming
|
Medium
|
1393
|
108 |
Jhal Ki Hey Guys Welcome To Versions Myth TV Serials Is Related To Subscribe My Channel And Tried To Solve Problem From List Code You Can Find Land Acquisition In Description Problem Statement Balance Oil Olive Oil Property Video Zara Tonight And Liked My And Sales And Come Back The Way Request All The Route Of The Day Routine Subscribe That Is You Came Up With Something Else You Dance Will Also Be With U Jai Hind Records Mithila It's Pregnant Then Tunnel Calculate The Route Of The Solution Class 9th That Daily Star Choosing Root Will Find A Minute And Creating Nodal Sign In Its Root Fan Dry Fruit Selected For A Question Subscribe Thank You A
|
Convert Sorted Array to Binary Search Tree
|
convert-sorted-array-to-binary-search-tree
|
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** nums = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted:
**Example 2:**
**Input:** nums = \[1,3\]
**Output:** \[3,1\]
**Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs.
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in a **strictly increasing** order.
| null |
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
|
Easy
|
109
|
59 |
hello guys welcome to algorithms made easy today we will be discussing the question spiral matrix part two in this question we are given a positive integer and we need to generate an n cross n matrix filled with the elements from one to n square in spiral order in the first example we can see the pattern in which we need to fill up this matrix of n cross n in the first part of this problem we were given the matrix and we need to return the values in the spiral fashion while in this we are only given the n and we need to generate the matrix so both the problems can be solved using the same technique let's see the basic idea of how we can solve this problem so this is the matrix given to us and this is the fashion in which we need to move so we can see that if we give the row and column coordinate to the corners point we have zero comma two and two comma zero so what this means is the rows can be from 0 to 2. there can be two variables to use that and there will be columns ranging from 0 to 2 as well we need to fill the matrix in the layer fashion we will be filling the outer layer first then we will move the inside layer when we will be done with the explanation we will see how the logic of only one layer will be used in the inside layer as well so just we need to create a logic to fill up one layer of this matrix for the first row we'll start from r1 and go all the way from c1 to c2 that is from zeroth column to second column when we will fill this we will reach the zeroth row and second column now we need to move downwards so in order to do so we will pick the c2 column and go from all the way from zero to two we will reach second row and second column then we need to move into this r2 row which is the second row for now and move till we reach the c1 column that is the first column so we fill up to that once we are done we will need to fill the 0th column starting from r2 till r1 minus 1 and when we are done with it we will be at value 8 all filled up and now we need to move into the inside layer so we need to fill 9 now so how to fill nine as we can see that the logic that we used to fill the outside layer will also be valid for the inside layer as well but since the square will now shorten up what needs to be done is this even will be incremented to one position and so the starting will be first column the ending will also become shorten up by one so c2 becomes one and same with the two rows as well so now only the overlapping area of these columns and rows need to be filled up and we will again apply the same logic and get our answer so let's see how we can code this as discussed we need to have two values for the rows r1 and r2 r1 being 0 and r2 being n minus 1 and same with the columns as we need to store the values we will need an array so we'll create a two dimensional array and we need a value to be put into this array starting from 1 so we'll have a value variable also we will loop till the range of columns and rows are at least one that means now as discussed we need to start our looping from r1 row starting from c1 column up to c2 so we'll do that this is moving left to right now we need to move down so we discuss that we need to move into the column c2 starting from r1 plus 1 till r2 now we need to move from right to left and then move up so this two condition only possible if there exist any range that needs to be filled up so we'll have two conditions over here that r1 should be less than r2 and c1 should be less than c2 so here we move right to left so we discuss moving from right to left we need to move in the row r2 starting from c2 minus 1 till c1 plus 1 so to do so and then we need to move up and we discuss we will be moving in the seventh column starting from r2 till r1 minus 1 that is once all this is done we discussed that how we need to shorten our window equally from all the sides that means the r1 will be incremented and the r2 will be decremented c1 will be incremented and c2 will be decremented once all this is done we just need to simply return our array that is all so let's run this code so it gives proper result let's submit this so it got submitted successfully the time complexity of this algorithm is open square while the space complexity is of one we are not considering the output array in the space complexity that's why it is constant thanks for watching the video see you in the next one you
|
Spiral Matrix II
|
spiral-matrix-ii
|
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 20`
| null |
Array,Matrix,Simulation
|
Medium
|
54,921
|
1,061 |
hi everyone welcome back to the channel and today we're going to solved code TV challenge problem number 1061 lexographically smallest equivalent string so in the given problem we have to basically find out so smallest equivalent string lexically and we have been given two strings S1 and S2 and you can say that like a is equals to c b equals to B C equals to B okay so these two strings are basically symmetrical okay or equivalent sorry my bad you know these strings are equivalent and they have given a proper definition of uh equivalence over here and this is the topic of set theory and algebra like uh if we talk about discrete mathematics so these are few properties which they have given and we have to find out the minimal or the smallest equivalent lexically uh smallest equivalent string Works base Str so I'm gonna use uh the approach called Union and find in that what we will be doing is we will be basically mapping out each individual pairs okay and we will find out what is the smallest character which can represent a particular chain for example in this case uh KRS right these three like can be obtained from each other using the rules of equivalence okay so we have we will find out which character will be used to represent uh the KRS in the base string okay so that's what we are going to do and yeah it's gonna be uh little complicated if you don't know about Union and find method uh the code the implementation will be a little simple okay so let's start that and explain the code uh on the go okay so first of all I want to Define a representation okay so we can use init as well but I'm going to directly just Define that representative and I want to keep like this will basically represent here all the characters although yeah all the characters in your lower case or ABCD okay so there will be 26 characters right in 26. oh sorry this should have happened over here like in the init call basically okay we are done over here next thing what we want to do is we want to perform a union on all the edges so think of each mapping for example uh Parker and voice let's take an example Morris think of this P and M as vertices and the relation between them as in edges okay so we will basically find out or we will do the Union on all the edges okay so to do that let me first build a different function called perform Union okay which will take two parameters uh let's name them X and Y for now Okay so um we will have to basically find out uh like for X this will be a character y also will be character and we have to find out what or the character will be used to represent this X and Y okay so to find that let me Define another function called fine okay this will take a single value called X okay so we are good till here okay let's define these uh functions so this will be used to this return method will be used to return the representation of the components or characters component slash character X okay so what we'll do is we will simply check if representative will have to use Save also the dot representative of we are looking for X if it is X then we'll simply return the same value otherwise what you're going to do is we're going to recursively call this find method text say dot fine representative of text okay build I try to find out the minimal value which can represent the this component this particular component foreign Union is basically your clubbing uh all those vertices together which can be obtained from each other support X I can't say that because this x can be represented using whatever results we get from fine or Y as well okay pause check I want to do it this both X and Y belongs to the same group or if both are same then we need not to do anything otherwise like whatever is smallest either X or Y I want to update the representation of that character into this uh array which we have to build okay if X is lesser than y then self Dot representative let's exit this thing right then I want to update the representation of Y 2 x otherwise the other way around okay so this is done like we have upon the Union on all the edges now uh in the last I want to call this function for each pair like for each vertices in our mapping for example for P and M I'm gonna call uh this function once for a into I'm going to call response okay first i m range S1 and S2 will be of same length so I'm gonna use space one for now perform unions and like over here we are using numbers right 0 1 2 3 4. so to do that what I'll be doing is I'll be using uh oid function in Python which gives you the Skype character code for particular character okay and to map that with uh the indexing in Python which starts with zero I'm gonna subtract out the uh ski character code of a small a okay so to do that order of S one of I okay this subscribed it out yes order of a okay this should be the first parameter or the second parameter we're going to do the exactly same thing but with S2 okay so now uh like once we call this perform Union method we will know uh which smallest character can represent or character in the given strings now we just have to prepare our results so I'll initialize that with infinity string and I'll just simply iterate through the base string which we have received and we will just keep on appending that into our result so I'm using this car as we have the this your numerical representation of each character right so simple step star to find now we are using C right then I'm going to use the same logic order of speak minus order of T okay but to get the actual character we will have to add order of a in the results which will get from the find function right because we have all the representation where we have subtracted out so yeah this is it and at the end I'll just simply returns the results let's see that you know in this case it gets false okay there is some issue so I'm not clear that's fine I think okay What if I they've been so long yeah so let's initialize it with windows okay let's try this I'm trying to see their demo okay make sure goes more sorry yeah so the test cases got triggered let's submit for the evaluations yeah so the solution accepted and we outperformed like we did very well we have to perform 97 of submitted Solutions so thanks again guys for watching the video and stay tuned for upcoming US don't forget to subscribe to the channel thank you
|
Lexicographically Smallest Equivalent String
|
number-of-valid-subarrays
|
You are given two strings of the same length `s1` and `s2` and a string `baseStr`.
We say `s1[i]` and `s2[i]` are equivalent characters.
* For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`.
Equivalent characters follow the usual rules of any equivalence relation:
* **Reflexivity:** `'a' == 'a'`.
* **Symmetry:** `'a' == 'b'` implies `'b' == 'a'`.
* **Transitivity:** `'a' == 'b'` and `'b' == 'c'` implies `'a' == 'c'`.
For example, given the equivalency information from `s1 = "abc "` and `s2 = "cde "`, `"acd "` and `"aab "` are equivalent strings of `baseStr = "eed "`, and `"aab "` is the lexicographically smallest equivalent string of `baseStr`.
Return _the lexicographically smallest equivalent string of_ `baseStr` _by using the equivalency information from_ `s1` _and_ `s2`.
**Example 1:**
**Input:** s1 = "parker ", s2 = "morris ", baseStr = "parser "
**Output:** "makkek "
**Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[m,p\], \[a,o\], \[k,r,s\], \[e,i\].
The characters in each group are equivalent and sorted in lexicographical order.
So the answer is "makkek ".
**Example 2:**
**Input:** s1 = "hello ", s2 = "world ", baseStr = "hold "
**Output:** "hdld "
**Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[h,w\], \[d,e,o\], \[l,r\].
So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld ".
**Example 3:**
**Input:** s1 = "leetcode ", s2 = "programs ", baseStr = "sourcecode "
**Output:** "aauaaaaada "
**Explanation:** We group the equivalent characters in s1 and s2 as \[a,o,e,r,s,c\], \[l,p\], \[g,t\] and \[d,m\], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada ".
**Constraints:**
* `1 <= s1.length, s2.length, baseStr <= 1000`
* `s1.length == s2.length`
* `s1`, `s2`, and `baseStr` consist of lowercase English letters.
|
Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position.
|
Array,Stack,Monotonic Stack
|
Hard
|
2233
|
24 |
hey everyone welcome back let's solve another problem today let's look at swap nodes in pairs so we're given one linked list and we want to swap every two adjacent nodes and then return the output and they tell us we cannot modify the values it would be really easy if we could just take the values and then swap them but unfortunately we are gonna have to do some pointer stuff so we're gonna have to update the pointers instead so this isn't too difficult right like just go through every pair of nodes so the first pair is one and two we can just take this link and reverse it right and then we look at three and four take the link and reverse it but we also see that we have to do a little bit more than just that right like this one has to be connected to this and the three is now going to be the end of the list so it's going to be null and we see that the output is basically in this order right 2 is now our head so we go 2 1 4 3. so you might be able to tell the annoying part of this is going to be pointer stuff and there's going to be a lot of edge cases that i'm going to show you how to eliminate of course we're going to use a dummy pointer or rather a dummy node we're going to create a dummy node at the beginning and we're going to do some other stuff that i'm gonna show you right now so to help us out with the edge cases let's create a dummy node just give it value zero and now we're here so this is like our start point right we first wanna make sure that we at least have two nodes for us to reverse right because we're gonna reverse these two then we're gonna reverse these two and then we're gonna see that we have nothing left so we're done right but hypothetically what if there was a five over here then we come here right there's not even two nodes there's only one node here and nothing over here so we don't reverse in this case we can stop so this is our previous node and this is our current node and we're going to reverse some right so we can take this pointer and reverse it we can also take this pointer and reverse it but where are we going to reverse it to where are we going to set this pointer are we going to set it to null are we going to set it to the dummy node probably not the dummy node right well i'm actually going to set this over here right basically what we're doing is we saw that we two had a next pointer set to three but we got rid of that and what we're really trying to do is take this node and swap it with this node so if we want to put this over here we should set one's next pointer to three so that's great we've reversed these two nodes and we want to now shift to the next positions and actually one more thing we want to do before we end up shifting our pointers is see that we swapped these two nodes our dummy is gonna point to the head of our list initially it's pointing at one because one is the head but we replaced it with two remember so what we want to do is now set dummy.next equal to set dummy.next equal to set dummy.next equal to the second node and this is getting kind of messy so i'm actually going to redraw what we have up here so this is what we currently have right and now we want to reverse these two nodes well we know 4 is pointing at null but we want it to point back at 3 so we can reverse this pointer but what about 3.next we definitely want but what about 3.next we definitely want but what about 3.next we definitely want to change this pointer but what are we going to set it to this time are we going to set it to null and the answer is yes because we're replacing 4 and 3 we're swapping them we know 4 was pointing at null before so now we want 3 to point at null and the last thing we want to do is take the pointer over here and instead set it to four because if we want to replace these two we know that one was initially pointing at three but we're swapping the three with the four so we want one to point at four now and so i'm just going to take this redraw it over here so we got a two a one four and a three a little bit messy but we know that this is the output right because we see it over here two one four three so we have our result we have our dummy pointer pointing to our head which is 2 and we were able to do this in big o of n time so we are going to create another node which is our dummy the value is going to be 0 because we don't really care about the value the next pointer is going to be head the second parameter is what we're setting to the next pointer we're also going to initialize some pointers previous and current initially previous is going to be set to dummy and current is going to be set to the first node in the list and so now basically we're going to start looping and reversing every pair of nodes so we're going to keep doing that until we reach the end of the list so while current is not the end but we're also going to make sure current dot next isn't the end because we want to make sure we have at least two nodes to reverse not just one node so since we are making some changes to pointers the first thing i'm going to do is save a few pointers that we're going to end up changing because we want to have them stored in a temporary variable before we break any pointers so i'm going to save the next pair of nodes that we're going to need to reverse and that can be found in current dot next right so shifting by 2 from current we can get the next pair which who knows it might be null but at least we have it stored here and we know that current is the first node in our pair so i'm going to get the second node by doing current dot next so now that we saved those pointers now we can actually reverse this pair of nodes so i'm going to take the second node and set its next pointer equal to the first node which is just cur and since we're swapping the positions we know that the first node is now going to be in the second position so the next pointer should be set to the next pair that we have right and we're taking the second note and putting it in the first position we to finalize that what we can say is previous dot next is equal to second so that means the second node has actually been put in the first position we've actually swapped the nodes now and before we start the next iteration of the loop we should update our pointers so that we can actually reverse the next pair of nodes so previous is going to be set to cur and cur is going to be set to the next pair of nodes and once all that is said and done we can return dummy.next because we know we can return dummy.next because we know we can return dummy.next because we know that dummy.next is always going to be that dummy.next is always going to be that dummy.next is always going to be pointing at the first node in the list and it was pretty annoying we definitely had to draw a picture to understand what we're doing with all these pointers but it works really well we did it iteratively we didn't really need a lot of a lot more memory the memory is big o of one the time is big o of n because we're just looping we're doing a lot of pointer stuff but we're only looping through the list one time i hope this was helpful if it was please like and subscribe it supports the channel a lot and hopefully i'll see you pretty soon
|
Swap Nodes in Pairs
|
swap-nodes-in-pairs
|
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[2,1,4,3\]
**Example 2:**
**Input:** head = \[\]
**Output:** \[\]
**Example 3:**
**Input:** head = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 100]`.
* `0 <= Node.val <= 100`
| null |
Linked List,Recursion
|
Medium
|
25,528
|
1,615 |
hello everyone welcome back here's van Thompson so uh today we are going to tackle a liquor daily challenge uh Maxima Network run so I assure you this problem has some very insightful concept to grasp so uh let's start by understanding the problem at hand so we have been given a set of comprising of any cities uh interconnected by several roads and our mission is to ascertain the maximal and network rank across all the city pairs so to visualize it we have a circles so our cities and lines the rows connecting them and the concept of the network rank between two distinct cities is the cumulative count of Roads directly linked to either of the two cities however there is a subtle Nuance so if a road directly connects both cities we only count it once so let's look at example so given this graph so it's represented by the list of lists uh and those are connection between our cities uh the maximum possible connection is for and why is this so it's for City zero and one and we have one road uh second third and fourth and this road fourth uh is counted only once uh so as you can see those Road has a four connection if we put pick another roads for example uh or another cities uh the value will be not as big and as in this case so for example if we pick a number three and number zero there will be just one road uh second and third so it will be free so that's why we choose City zero and one with four Intel connected uh rows okay so now when we understand the problem our first task uh estudia translate uh it to a code and think how can we solve it uh so for first let's compute the degree for every city and essentially we will come compute and count the number of Roads so yeah uh each city is connected to so it's a linear and straightforward step so let's do this so step number one compute the degree for each City and it will be just a degree zero times n and four a b in roads degree a plus one degree B plus one and using a set to store the rows a 01 lookup and throats set will be set Tuple Road Four roads in roads okay so to enhance our solution efficiently I'm going to employ a useful trick so by achieving the archiving at the roads in a set data structure we can instantly verify if two cities share a direct Road saving a computational time so now for the most engaging part we will Loop through all potential power of a city Computing the network rank so as we proceed we will keep an eye out for the highest rank observed so let's do this so max rank will be zero and step two iterate over all per of cities four I in range and 4 J in range I plus 1 and calculate Network rank so rank will be degree I degree J and if there is a direct stroke between I and J subtract one because it's overlapping so if i j J in Road set or J in wrote Set then rank minus one as simple as this and step number three so keep track of the maximal network rank okay so and now for the most engaging part we process every Rank and as we process we will keep the rank updated and the last part is full so maximal rank um okay maximal rank will be rank uh yeah between Max Rank and rank and return finally Max rank so this is our implementation so a really simple logic yeah I think I missed you okay so let's run it to verify everything's work so uh yep all good so test case passed now we can submit it for unsynthesis cases so for unsynthesis cases we beat 81 with respect to a runtime and also 15 so much with respect to memory but it's quite runtime efficient maybe not so because it's uh yeah probably uh o n Square time complexity uh but yeah uh it's really straightforward solution and very intuitive and there you have it our solution in Python work perfectly but if you prefer other programming languages I will include solution implementation in Java go rust and much more and yeah in the video description and there we have it our code execute flawlessly and I hope this walkthrough was helpful and always remember each coding challenge uh give you a way for learning and growing and I appreciate spending your time with me today and if this video added value to your coding Journey uh yep please hit the like button and do subscribe for more in-depth coding subscribe for more in-depth coding subscribe for more in-depth coding exploration at tutorials and much more soon and stay motivated uh keep practicing happy coding and see you next time
|
Maximal Network Rank
|
range-sum-of-sorted-subarray-sums
|
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`.
The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either** city. If a road is directly connected to both cities, it is only counted **once**.
The **maximal network rank** of the infrastructure is the **maximum network rank** of all pairs of different cities.
Given the integer `n` and the array `roads`, return _the **maximal network rank** of the entire infrastructure_.
**Example 1:**
**Input:** n = 4, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\]\]
**Output:** 4
**Explanation:** The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.
**Example 2:**
**Input:** n = 5, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\],\[2,3\],\[2,4\]\]
**Output:** 5
**Explanation:** There are 5 roads that are connected to cities 1 or 2.
**Example 3:**
**Input:** n = 8, roads = \[\[0,1\],\[1,2\],\[2,3\],\[2,4\],\[5,6\],\[5,7\]\]
**Output:** 5
**Explanation:** The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.
**Constraints:**
* `2 <= n <= 100`
* `0 <= roads.length <= n * (n - 1) / 2`
* `roads[i].length == 2`
* `0 <= ai, bi <= n-1`
* `ai != bi`
* Each pair of cities has **at most one** road connecting them.
|
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
|
Array,Two Pointers,Binary Search,Sorting
|
Medium
| null |
1,905 |
uh hi friends uh welcome to my channel let's have a look at problem 1905 count sub islands so in this video we're going to follow our line of traversal algorithms to present a solution based on breadth first search here and we shall present a iterative format so this problem asks us to return the number of islands in grade 2 that are considered sub-island considered sub-island considered sub-island so this problem also explains what does it mean by a sub-island does it mean by a sub-island does it mean by a sub-island so an island in greece ii is considered a sub-island a sub-island a sub-island if there is an island including one that contains all the cells that make up this island ingredient too so with that said let's have a look at a example so let's look at example one so in example one so there are five islands in grade two so this is one and this yellow one here is one the two red ones are corresponding to two islands and this three uh orange uh land cells form another island so in total is uh there are five islands in grade 2 and 3 of them are sub-islands and 3 of them are sub-islands and 3 of them are sub-islands so this red one and also here the two red one here so the output is three let's also have a look at the costumes so the first two items are basically consistency assumption or it assumes that the two grids are the same in size so both the number of rows and the columns are bounded in between one and five hundred and the grid value in grade one and grade two are either zero elect corresponding to c and land respectively so with that said let's look at the method and idea so the method is a standard uh traversal algorithm uh in the large uh in big picture so the idea here is how to check so an island in greece two is a sub island so the idea is the following actually it directly uh comes from the definition so for an island i included two to be a sub island of ireland in see some island in green one if and only if any cell any land cell rc in i for this uh position so the corresponding cell value in gradient one must also be land so if van der waals position violates this condition then the corresponding island i will not be a sub island so with that said this procedure actually is very straightforward so first we'll write a breadth first solution with an extra flag check so when we are locating the number of islands in grade two so here is a notice or remark so this is exactly the same as we did in this code 1020 or 1254 video explanations so here i would like to introduce a technical treatment so when we visited a land cell in green one in grade two so where uh we're going to reset its cell value to be zero so this way we do not need to use a set abstract data structure to monitor the traversal so that's what we want to do so brother first with flag check and there's also a technical treatment in between so here the plan is that i will reach a format without writing a hyper function so this is just a choice of a representational format so we have different formats for this similar class of problems in the playlist so it's good to have a look at them so with that said first let's do the preparation so here i'm going to uh check the number of those number of columns and initialize a queue and a const variable so i'm going to do angles and columns and crew so and the cons so basically it's length grid zero so these two variables corresponding to the number of rows and number of columns in a grid one or two so let's use gradient one so uh the quill i'm going to so let's import a deck to play the role of a crew so import deck so i'm going to initialize a deck and then the initialization for the count will be zero so the count will be the variable whose federal state is what we want to return so without that we meet the preparation so next so we are going to fund the islands in greece uh great too so also we want to locate those islands that are sub island so for this i'm going to do iterations so for row in range and rows and for column in range column so um this is standard so when we look we will match a landscape in grade two so we're going to do the traversal so if grade two um joe column is one then we're going to do the traversal we want to check also the corresponding island containing this position you and column if it's a sub island so for this first let's introduce a flag so it's initially true and then we're going to introduce another variable called current island so we are going to use a set to represent this island and then so we're going to append the quill with the current position so that's row column so as we mentioned so when we visited a position we're going to set its cell value to be zero right so we're going to set grid to column equals zero so next we're going to do the standard iteration so that's a while loop so well crew first i'm going to get the position so it's clear pop left so here the left is the height of the crew so then we're going to check first if the corresponding cell position in grid 1 is land if it's a land so the current state of the flag is still true if it's not a land then we change the state of the flag to be false so if grid one so rc is zero so then the flag will be false so that's a check um extra check for uh if we compare with the standard traversal so next uh we're going to add the current position to the current island so next is standard so we're going to look at the four neighbors of this position so here let's write in a different format so let's check if r is less than n rows minus 1 and grid 2 see r plus 1 c is 1. so this condition basically said that i want to look at r plus 1 and c position so we want to make sure r plus one and c are in bounds right so if it's inbound so we're going to append the queue with the current position r plus one c meanwhile this position is going to be visited so we reset its value to be zero so grid true so r plus one and c equals zero so next we're going to do the same thing actually for the three name the other three neighbors so we're going to check if uh column is less than n in columns uh minus one and grid 2 r c plus 1 so if this is 1 so we're going to increase this position this r c plus 1 and then we're going to change the value of corresponding cell it's r c plus 1 to increase 2 to be 0. so we checked r plus 1 r c plus 1 then we're going to check uh r minus one let's see our if r is greater than zero and greater two so r minus one c is one so in this case we are going to include this position r minus one c uh we are also going to do the reset r minus one c equals zero so next we are going to check uh r c minus one right we want to make sure c minus one is in bounds so if c is greater than zero and bridge 2 r c minus 1 is 1 so in this case we are going to increase this r c minus 1 and then reset the corresponding position to be 0. so that's the main logic so after this while loop actually it's corresponding to a bfs search so then we are going to check again the status of the flag so if flag then we're going to increment the columns by when so that's actually it for this whole solution so the remaining part is the return so we're going to return the corn state so that's actually this uh this part actually plays the role of the a very first search help function so but you know we put this inside a double for loop so we finished all these things in one big two phone uh it for loop so uh with that said let's have a look at the test cases first do a special case check columns is not defined so for in columns yeah it passes a special case now let's look at the generic cases it passes the generic cases so let's check again so let's see it should be fast so anyway so that's a format of solution so in this solution actually we did uh the things enough in mango so there are actually different formats of solutions for this kind of problem so if all the formats actually are good to be aware of and uh you are also encouraged to try to write different formats and using different check methods so with that said i guess that's about it for this video thank you very much
|
Count Sub Islands
|
design-authentication-manager
|
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in `grid2` is considered a **sub-island** if there is an island in `grid1` that contains **all** the cells that make up **this** island in `grid2`.
Return the _**number** of islands in_ `grid2` _that are considered **sub-islands**_.
**Example 1:**
**Input:** grid1 = \[\[1,1,1,0,0\],\[0,1,1,1,1\],\[0,0,0,0,0\],\[1,0,0,0,0\],\[1,1,0,1,1\]\], grid2 = \[\[1,1,1,0,0\],\[0,0,1,1,1\],\[0,1,0,0,0\],\[1,0,1,1,0\],\[0,1,0,1,0\]\]
**Output:** 3
**Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
**Example 2:**
**Input:** grid1 = \[\[1,0,1,0,1\],\[1,1,1,1,1\],\[0,0,0,0,0\],\[1,1,1,1,1\],\[1,0,1,0,1\]\], grid2 = \[\[0,0,0,0,0\],\[1,1,1,1,1\],\[0,1,0,1,0\],\[0,1,0,1,0\],\[1,0,0,0,1\]\]
**Output:** 2
**Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
**Constraints:**
* `m == grid1.length == grid2.length`
* `n == grid1[i].length == grid2[i].length`
* `1 <= m, n <= 500`
* `grid1[i][j]` and `grid2[i][j]` are either `0` or `1`.
|
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
|
Hash Table,Design
|
Medium
| null |
153 |
hello everyone in this video we will be solving the problem 153 find minimum in a rotated sorted array in the rotated sorted array we need to return the minimum element in this array if you look at example number one the variable nums contains three four five one and two if you just skim through all the elements the minimum element is one if you look at the explanation the original array was one two three four five it was rotated three times which gave us the result as three four five one and two there is a note added to the problem that we need to write an algorithm that runs an o of log n time so we cannot write a solution that iterates through all the elements giving a time complexity of o of n let's switch to whiteboard session and think how we can solve this problem let's use this as an example if we just look at the input the minimum element in this array is zero and the simplest approach to find the solution is going to be like iterate through all the elements and compare it with a minimum value that we are storing somewhere in a different variable and after iterating through all the elements in the array return the value in the variable but the time complexity with that solution is going to be o of n because we are iterating through all the elements in the array another way of solving the problem is to compare the adjacent values and see if at any given point of time there is a decrement because the problem statement states that this is an ascending order or it is already sorted so the numbers are always going to be greater than the previous one so 5 is greater than 4 6 is greater than 5 7 is greater than 6 at any given point of time this condition is not satisfied like in this case we should return the next value which is 0 so 0 becomes the minimum element in the list that is also a potential solution but again thinking from the worst possible case the time complexity is still o of n because we will have to iterate through all the elements then return the result let's think if we can apply a different algorithm to solve this problem as the problem statement states that this is a sorted array and all the elements are unique maybe we can try to use binary search tree algorithm to solve the problem so in a binary search tree algorithm we usually compare the median of the array with the ends and see which one is greater so we can use that same logic in to solve this problem so here my left will be 4 my right will be 2 and my medium is going to be 7. if for example this was a sorted array my left is always going to be less than medium and median should be less than r if this is true it means the array is sorted correctly because this is a rotated array either of the condition is not going to be satisfied let's start with comparing the medium with the r element so my medium is 7 r is 2. is medium less than r so this condition is not satisfied it means that within this combination we have a minimum element because 7 should always be less than the element on the right hand side so because this condition is not satisfied i will have a minimum variable where i'm going to be holding the minimum variable that we have calculated so far so between these two numbers medium and r are the right r is smaller than 7 it means r is potentially a candidate to be considered for the minimum element so my current minimum before starting the loop is going to be the maximum value inch dot max if i compare this int dot max with this value 2 i will get the minimum as 2 as i know that there is a potential minimum value available only in this region i do not need to check anything in the first part so i can totally ignore this and i can update my l value pointing to the next element in the second section of the array because i have already looked at 7 i don't need to use it again so i can directly jump to the next element and use that as a reference so my new values of l and r is going to be l will be 0 r will be 2 with these l and r my median is going to be 1. now i need to compare if l is less than m and m is less than r like before we were looking at medium and r so this condition is met because 1 is less than 2 it means this part of the array is valid we need to look at the first section of the array with m less than r it means that the minimum candidate needs to be updated so i need to compare my minimum value with m as m was lower than r we need to compare 1 with 2 and get the minimum so my new minimum will be 1 and i will update the l m and r values i will not be updating l at all i will be updating r so now r will be pointing to 1 but now that i've already went gone through one in my previous iteration instead of doing one i will use the previous value before one so i will be using r as zero so my both l and r are pointing to the same value my medium is also going to be pointing to the same value my l m and r pointing to 0 is m less than r that is incorrect so i will update my l to point to m and then compare 0 with the current minimum element that we have saved in the variable so in this case my new minimum will become 0 and i will update my l to the next value of 0 so the next value of 0 is 1 so l will become 1 my r is still going to point to zero here's the breaking condition we will only run this loop until l is less than or equal to r whenever this condition fails it means we need to break the loop and return the minimum that we have calculated so far because if we continue further we are not going to get any new results it's always going to be the minimum that we have calculated so far so in this case we will break the loop after this condition is fail and return whatever the minimum that we have calculated so far i hope you were able to understand this approach we tried to use the binary search tree algorithm to our advantage and just tweak the conditions a little bit so that we can find the minimum element in the add to solve this problem we broke it down into three iterations we first did with median is equals to 7 then we tried with one as a medium and then zero as a median so we did solve this problem with three iterations only so our time complexity is o of log n where n is the number of elements in the array let me show you how we can solve this problem using c sharp here is the c sharp implementation in the main method we start with validating if the nums is null or not if the nums is null we written minus 1 as the result then we initialize the variables we are setting this return value as into 32.max setting this return value as into 32.max setting this return value as into 32.max the left index is 0 and the right index is num of net minus 1 so which will give us the last index then we are running a while loop until left is less than or equal to right if this condition is met the loop will be executed else it will jump off then we are calculating the mid of the range based on left and right values once we get the mid we compare the value at that mid position with the right position if the mid is less than nums of write which means it is in a right order then we update the right value to mid minus 1 because the second part of the array is valid then we calculate the minimum value based on the current return value and the current mid because the current mid value is proven is less than the right so it means it is definitely lower so we do that calculation and save the minimum value in this return value variable if the mid value is not less than right let's say the mid value is greater then it means that the first part of the array is valid so we need to update the left index to mid plus 1 and we update the return value and calculate the minimum between the current minimum value and the right value after the loop is complete that is left is greater than right this condition the flow jumps out of the while loop and we return the return value variable i hope you were able to understand this approach and how we solved it using binary search tree algorithm if you have any questions or concerns please feel free to reach out to me i will be adding the link to the source code in the description below so you can check that out as well thank you for watching this video and i will see you in the next one
|
Find Minimum in Rotated Sorted Array
|
find-minimum-in-rotated-sorted-array
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times.
|
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
|
Array,Binary Search
|
Medium
|
33,154
|
1,012 |
hello everyone welcome to quartus cam and today we are going to cover another hard problem from delete code that is numbers with repeated digits so the input given here is an integer and we have to return how many positive numbers that has repeated digit in that so the first input given here is 20 and the only number with repeating digits is 11. so we have to written one so here is a second example hundred from zero to hundred the numbers which are having repeated digits are 11 22 33 44 to 99 and 100 because 100 has two zeros repeated and there are total of ten numbers that has repeated digits so how are we going to approach this obviously our first approach is going to be brute force if we are given a number then we are going to iterate the number from 0 to n and check every number whether it has repeated digits or not if it is having repeated digits then have a counter that increments every time it come across a number with repeated digits and it iterate through all the numbers and finally return the count so this is going to be our brute force approach and here is the code that i have a helper method is having same digits and i'm going to take every number and add the digits to the set if the set contains the number already which means it has repeated characters so return truth every number that returns true our iterator is gonna increment and finally return the result this is a pretty simple straightforward solution but when you submit it the time limit exceeded so how to do it in optimal time so that is what is making this problem hard so let's see the approach now so instead of finding the numbers with repeated digits it's easy to find the numbers with non-repeated digits non-repeated digits non-repeated digits and subtract that from the given number so for example if you consider the n is equal to 100 the numbers starting from 1 to 100 have 90 non-repeated 90 non-repeated 90 non-repeated digits number so if you subtract it from 100 it is gonna be 10 numbers that are having repeated digits so that is going to be our answer so how are we going to do this we are going to do permutation of the digits from 0 to 9 to find the numbers with non-repeating to find the numbers with non-repeating to find the numbers with non-repeating digits easily and subtract it from the given number so before going into the actual logic of the problem let's quickly understand how permutation works if there are number of digits given and the possible permutation of the given digits is going to be n factorial that is there are four digits here the possible permutation is 4 factorial that is 24 numbers 24 different set of numbers that is going to be the permutation of the given number same way if we want to calculate permutation of given digits taken r at a time so here is the formula for permutation of given numbers taken r at a time so what is taken hour at a time if suppose there are given four digits and we have to take only one digit at a time and what are the permutations possible the possible permutations of one two three and four separately because we have to take one digit at a time so if we are taking two digits at a time then it is going to be four into three twelve possible combination of numbers that is one two one three one four two one and two three two four three one and etc because we have to take only two digits out of given four digits to calculate the permutation of the given digit so now taking three digits at a time would give you 24 combinations and again taking four digits at a time is going to give you another set of 21 combination of permuted digits so by using this we are going to calculate the permutation of taking one digit at a time and two digits at a time and further based on the given number three digits four digits and find the non-repeating numbers non-repeating numbers non-repeating numbers and separate or subtract it from the given number so here as the permutations does not include repeated numbers they have unique set of values every time using this formula we are going to calculate all possible permutations of digits from 0 to 9 the digits given here is 0 to 9 and calculate the non-repeated digits and calculate the non-repeated digits and calculate the non-repeated digits but there is one thing we didn't notice is that from 0 to 9 it is gonna get us all possible for formations that is it includes 0 in the first position for example 0 1 0 2 0 3 will also be included to avoid that we have to change this formula a bit different that is n minus 1 into permutation of n minus 1 r minus 1 so what is this n minus 1 is nothing but if we are given 10 digits that is 0 to 9 we cannot include 0 as a digit every place so we are going to take that separately and do permutation for rest of the numbers that is n minus 1 by doing so we will get the perfect permuted number combinations of values starting from 1 to the given number so for example our given number is 100 and we are going to find non repeated digits using this formula so we cannot include 0 so our digits are going to be 10 so it is going to be 9 into permutation of 9 comma how many numbers we are taking at a time so let's take one number at a time which means it is going to give you the value of 9 so yes by taking one number at a time it is going to give you 9 different values so far we have got 9 numbers without repeating digits so moving on to considering two digits at a time so if you consider two digits at a time using this formula we have got 81 numbers from 11 to 100 so in this case we have found 81 numbers without non repetitive digits so if you add 981 is gonna give you 19. so these many numbers are there without repeating digits and if you subtract 90 from 100 you're gonna get 10 that is actually our output so yes this formula is going to help us get the count off or the number of permutations of digits to get to our result so now let's get into an actual solution so yes if a number n is given we are going to divide the solution into two parts that is first for example if the number is 1 2 3 4 it is easy for us to find the numbers with non-repetitive digits the numbers with non-repetitive digits the numbers with non-repetitive digits from the range 0 to 10 and 11 to 100 and 100 to 1000 by using the formula that is every time the digits are going to be nine and we are going to calculate the permutation for considering nine digits as one at a time and nine digits as two at a time and nine digits as three at a time by using the formula we can easily find the non-repetitive numbers the non-repetitive numbers the non-repetitive numbers till the range thousand similarly if the number is 50 000 we are going to apply the formula for the range 0 to 10 000 to find the values for example if the number is 445 we are going to apply from 0 to 100 to find them easily using the formula but the real task is finding the non-repetitive numbers non-repetitive numbers non-repetitive numbers after the range 100 to 445 so we are going to see how we are going to compute the permutations from this range before that let's cover the code for permuting the first half of the problem and get back to the second half solution so as i have said we are going to deal with the digits we are going to have the digits in our list which will help us easily access the digits given in the number so i am going to declare my list and count which is actually going to have the count of numbers without repeating digits and which is what we are going to return finally by subtracting from the given number again so now we are going to save the digits in our list but instead of the digits in number n we are going to save the digits from number n plus 1 and there is a reason for that so if we have our example given as 444 in that case the given number n itself is included in our solution because it is having repeated digits so for that reason our algorithm is designed to consider only numbers less than n so we are going to add the digits of numbers n plus 1 as i have added the digits in my list i'm gonna write a permutation function which is help us calculate the formula the second half of the formula so now we have written our permutation function which helps us to calculate the second half of our formula so now we are going to do the first cover the first part of the solution we have discussed that is i am gonna i trade through my list size y list size because if it is three then the given number is a three digit number if it is four the given number is a four digit number as we have discussed we are going to cover till that range that is ten hundred and thousand we need to know how many digits is the given number so for that i'm gonna iterate till my list size and i'm gonna calculate my count as we know for the range the digits are going to be 9 i am directly putting the value 9 into permutation of 9 comma i so here i will actually do consider one digit at a time two digits at a time and three digits at a time and goes to the how many digits is the given integer is we have done the first part of the code so how are we going to approach the second half of the solution consider the given number is 456 and we have calculated the non-repetitive numbers from the non-repetitive numbers from the non-repetitive numbers from the range 0 to 100 so now our task is to calculate it from 100 to 4 for 56 so in this case if you start seeing the number 1 to 200 to 300 and so on you can see for the range 1 to 200 the first number is fixed that is the first number is going to be 1 and we have to calculate the rest of the numbers for mutations that is considering 2 digits at a time so in this case we know our first digit is going to be 1 so obviously our first number is not going to be 0 in this case we can include 0 as well so we are going to do simply n factorial by n minus r factorial so in this case we are going to consider all 10 digits that is 0 to 9 and we are going to keep our first digit as constant and gonna calculate the permutation of rest of the numbers for example if the given number is four five six in this case you will first calculate from the range zero to thousand and you will be finding from thousand to two thousand and two thousand two three thousand same way three thousand to four thousand and then four fifty six so for that you know the first digit is going to be hundred one here and the second digit is going to be two here and so on so in that case you will be finding the permutation of numbers three at a time and then two at a time and then one at a time and finally add the sum same way we are going to call our yen as 10 digits first and then considering the rest of the positions that is if it is a three digit number then if it is a four digit number then considering three at a time two at a time and one at a time if it is a three digit number then considering two at a time one at a time same way our functions are going to calculate ten comma two and 10 comma 1 and so on if it is a 4 digit number it will have one more iteration 10 comma 3 but there is one more thing we are going to concentrate is every time the digits are not going to be 10 because if you know the first digit is 1 you are going to ignore the numbers with the same digit because we are going to find the numbers without repeating digits so in this case if you know the first digit is 1 then you cannot include that 1 in the rest of the number so the digits are going to be 9 at the first iteration same way if you include some other number in the second direction for example if a first number is 1 second number is 2 then the rest of the numbers cannot include 1 or 2. so in this case our second iteration will reduce one more digit and becomes eight if our number is one two three and we have to add one more number that one more number should not be one or two or three in that case one more digit will be reduced so as the iteration goes we start from the maximum digits available and the maximum places and reduce both of them for every iteration and calculate all possible permutations and add the sum so how many times this iteration are going to happen the number of times the digit is so for example if it is a 456 then we are going to do it four times that is from 100 to 200 to 300 to 400 and 400 to 455 so if it is a first digit we are going to iterate it that many times the same way we are moving on to our second digit 456 then keeping five times the iteration that is from 400 to 410 to 420 to 430 to 450 so we are and finally 450 to 456 so we are going to consider the second digit and perform the same operation by keeping the first digits constant and doing the rest of the permutation for five times and finally consider the last digit and do it that many times so we are going to repeat the permutation calculation for the number of times the digit is hope you are getting the solution if not if you look at the code you're definitely going to get it so let's go to code the part two so now i'm gonna have a set which is gonna hold my digits in the given number because if we encounter a digit once we cannot include the digit again in that number so to keep track of duplicate values we are going to get the help of hash set and i'm gonna iterate through the digits and my j pointer is gonna start at 1 if the first value is 0 because we cannot have 0 as our leading number so if our first digit is going to be 0 then i'm going to start our j from 1. and it is going to iterate till the number of time the first second and third digits are so now i'm gonna check if the digit is already present in the permuted number if that is the case i'm gonna simply skip this loop if the digit is already there i'm not gonna calculate its permutation if not i'm gonna count i'm gonna call my permutation function that is starting from 10 minus i plus 1 that is for every iteration the digits are going to be reducing comma list dot size minus 1 minus i that is for every iteration the numbers considered also be reducing so every time it is going to calculate and in this loop i am going to check if the set contains the number already if it contains the digit then break this loop if not add the digit to the set so yes now it is done i'm finally gonna return my given n minus the count of non-repetitive numbers the count of non-repetitive numbers the count of non-repetitive numbers so let's run this face let's submit yes the solution is accepted and runs in one millisecond so thanks for watching the video if you like the video hit like and subscribe and let me know in comments what are the things to be improved
|
Numbers With Repeated Digits
|
equal-rational-numbers
|
Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_.
**Example 1:**
**Input:** n = 20
**Output:** 1
**Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11.
**Example 2:**
**Input:** n = 100
**Output:** 10
**Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
**Example 3:**
**Input:** n = 1000
**Output:** 262
**Constraints:**
* `1 <= n <= 109`
| null |
Math,String
|
Hard
| null |
1,432 |
Hello viewers welcome back to my channel I hope you are doing all the problem the time uploading now become history subscribe my channel and pleased to hide and subscribe and also share with your friends to date problem is max different skin get from changing anti a Fiber should give in the Journal of Butterflies Farfalle Previous Video then subscribe to the Page To replace all the Prince Vaccine Dashman representation of number of person to reduce a and watch what is the current affairs in the country with Sudhir and products and also on that one Ax An Controversy Final Number 19 2013 Play The Activist Wale Sudhir They Should Not Agree With Relief Operations To Number First And Were Told To Be Replaced By Name The First Time Fluid Suna Do A View To Return Max Different Boys Paid That's The Question Subscription Will Give Very Easier To Quite Very Much Electronic Looking Out For A Day From Number One Surplus Share Subscribe Button And Communicate The Number subscribe Video subscribe this Video give 104 In The Voice Of 120 Withered Hair 910 Means The King Is Not Really subscribe And subscribe The Amazing spider-man middle aged want to listen my voice recorder zero saunth and previous video phase election the subscribe 505 10 [ video phase election the subscribe 505 10 [ video phase election the subscribe 505 10 channel subscribe 502 idioms final 000 rang me rang le advice ki without 5.5 and rhythm one fact that 5.5 and rhythm one fact that 5.5 and rhythm one fact that is the number Brigade Video subscribe like subscribe to the Page if you liked The Video then subscribe to the Page That's the difference between that and 20 difficult tops but what they have to return that difference between that number of friends and widening deficits sexual more no transfer fee No 220 Veervar 1234 No What is the difference between the different from its 8etude maximum subscribe pimp subscribe by pressing the subscribe button to what is the number one to three different problems of the lap and look for the more examples subscribe for More videos number 100 number 91 12345 se subscribe and subscribe this Video Possible to understand them on you want and different maximum and sunao ko whatsapp diye big guide whatsapp depends on so with simple logic that they can see a pun here minimum number possible video minimum number possible and maximum number Number Possible With Water And Subscribe 1000 Minimum Number Team Is I One Is Minimum Number Possible Been No Maximum Number 64 Sudhar Different Says No What Withdrawal Gift Subscribe Thank You Can Get Maximum Difference Between Friends Tweet 12th Class 2nd Subscribe Maximum Number One Number Two Improvement Feedback Software Download To Veer With All Thee Here Example Number Is 125 Gram Paneer And Normal Person You Take Two Digits Minimum Possible Number To Our Problem Subscribe Now To Receive New Updates On Ki Vihar To Peech Girls And Replaced By 100 only numbers to F-22 is serial By 100 only numbers to F-22 is serial By 100 only numbers to F-22 is serial 1000 channels subscribed mostly registered blood you all subscribed can do the lowest possible for all can we the 11km by the lowest number possible president and lemon kabir and saunf agro and tried to understand what is number To 9 Number Nine Adhiveesh To Cash Withdrawal Different Techniques To Understand Problem No Problem Yes-Yes Okay What Is The Number No Problem Yes-Yes Okay What Is The Number No Problem Yes-Yes Okay What Is The Number Possible To Understand Them Hello How To Get Minute And Member And How To Get Maximum Number First Left Side Maximum Number Of Logic Pimple So What is the number from 0202 Don't See The Giver Number One Two Three Four Six Number Hai What Were Gone To Far S We Are Going To Replace The First Duty World No Veer Subscribe subscribe and subscribe the Big Number 66 That Dacoit Number Which is not noida withdrawal transform that is equal to what is equal to subscribe 92346 subscribe maximum number maximum possible only first number calling from ok good night thank you one dim number is question on that welcome to if minimum number in the shop a nine to three four Five Six Seven Eight Number Electronic Toll Get One More Examples Which 128 Subscribe Now To Find The First Division No You Are The Number Basically Play The First Key Digit Which Is Not Replaced Back And All It's A Friends Let's Go To Do Subscribe Minimum Number Of In The Number Is Short Life User Manual Number Subscribe To That This Remedy They Can Be Quite Explicit Qualities And Replaced With Simple Example In More Subscribe Number One Officer Subscribe A Main Pain Battering Ram 12345 700 Versus What Is The Meaning Of Do That Can They Replace The One With 09 Development A Side Leading Unemployed Na Chalo Replace Scholar Pimps 12345 6 Not Alone But That Bloody Mary And They Have To Live With This One Is Unfolding Space 123 456 Can We Do You Can Replace You love the king Riched the Rolls Royce There were 100 rooms There were 100 school pickups The subscribe To sales will remain minimal Do more sewing This is how to find the first digit Which is not equal to here 140 to Zafar Defensive 1000 We are not alone to Hell or video replace all the do n't forget to subscribe the water with just stay fit and different back side veer 205 and subscribe must subscribe to hai to inko and nurses replaced with zero do ki doctor media flat simple Half Hour Subscribe To 300 Plus 2 And Failed To Locate The Code Word So It's Just Follow The Same Thing Subscribe To All In Depression Done And Number Up To ₹100 And To All In Depression Done And Number Up To ₹100 And To All In Depression Done And Number Up To ₹100 And Converting The Number To Cars And Don't Used Cars Information 100 Number Will Be Sacrificed Her A Quarter Number To Do The Calling Apps Here Posted In The Number Subscribe To 234 The Maximum Number Vyapar Vriddhi Saare Na 100 Amazing Like Subscribe And Click Subscribe Button On This Side And That Safe Baje Equal To A New Symbol And Declare A New Spin Boldak Kiya Sanao Yahan Par Jo Brain Jo Number Aaj Lunges Number Is Not From Left To Right This Please Like Subscribe Aur Hai Jiske Will Get Beam The First Number Which Is Not My Par Gil All Number Nine Replacement Subscribe What Is The First Character Not The Character Of The Year Was Effigy Where Is The Replacement Character Bank Account Dr To Use Not If Subscribe Finally Returned Back To Subscribe To Minimum Purpose Only But Development But And 12345 10000 Subscribe One Thousand More Research Chal Thing Apps Tractor So Ifin Vwe Fight character number set whenever I famous scholar end and handsfree loop down bellow to do the children placement subscribe to that outside the finance loop 105 director replacing let's go off web skin must subscribe and check if it is not Equal to Zero Difficult 2025 Equal to One Vihar Vikrant Subscribe Worst Position Subscribing Loot the Character You Get 2018 12345 6 Replies Pay 12345 I Will Give One 203 Then Date with Aamir at the point Vikrant Replace 150+ Super-8 Replace 150+ Super-8 Replace 150+ Super-8 Subscribe 251 Plus Two Draw A replacement for doing so that without number calculations versus without works in the way of doing mischief website so let's go with him from president for this thank you right the number length number is number way on Thursday to two in This they all want to eliminate back tension from the to basically pigmentation the time complexity will be border our pure total quantity time's middle order when will the number and assured them what is the time complexity 5651 equations please post your comments on to Please Subscribe My Channel And Also Share Your Friends Also Don't Forget Trick Click On Bell Icon You Will Get Notifications For All My Feature Videos Thank You For Watching My Video Back With Another Video Very Soon Children Good Bye
|
Max Difference You Can Get From Changing an Integer
|
check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree
|
You are given an integer `num`. You will apply the following steps exactly **two** times:
* Pick a digit `x (0 <= x <= 9)`.
* Pick another digit `y (0 <= y <= 9)`. The digit `y` can be equal to `x`.
* Replace all the occurrences of `x` in the decimal representation of `num` by `y`.
* The new integer **cannot** have any leading zeros, also the new integer **cannot** be 0.
Let `a` and `b` be the results of applying the operations to `num` the first and second times, respectively.
Return _the max difference_ between `a` and `b`.
**Example 1:**
**Input:** num = 555
**Output:** 888
**Explanation:** The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888
**Example 2:**
**Input:** num = 9
**Output:** 8
**Explanation:** The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8
**Constraints:**
* `1 <= num <= 10`8
|
Depth-first search (DFS) with the parameters: current node in the binary tree and current position in the array of integers. When reaching at final position check if it is a leaf node.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
3 |
hi everyone welcome to my channel let's solve the problem longest sub string without repeating characters so given a string as find the length of longest sub string without remitting characters so in this example one we have string abc a cbb so if we see this is a unique no character so far is repeating but when we reach on this a second a which is repeated so the maximum long like so far we got three is the maximum length then we will remove this a and then look for this so now again is okay three and when this week came then v is repeated to this v so we have to remove this and then cab is also three another a b c is again three then b c b not three this two so the longest sub string of non repeating characters in this string we can get at max three length of 3 which is either abc or bcaa or cab so how we will solve this problem so the one of the brute force solution is like start from the length of the string which is n let us say length of our string is n start like check for whether this string is consist all the characters is unique or not so start from this length and then we will go up to the length 1 and we will try all possible service string like starting from this index like 0th index lets it call j and from 0 until we will try where j plus i is lesser than n and we will try all these a combination of all the length of service string like length of sub string start from n and it will go up to uh one so the first one is whole and how we will check whether this string is contain any repeated character is a straightforward you can create these set of these characters so if we create set of these character set of these characters and then we will check if the length of size of the set is equals to the length of our original string if it is then in that case all the character in our string is unique if it is not equal in that case this string is known so in first case what we will do we will start for abc so the size of the there are only three unique characters so the size of side will be three while the string length size is initially is eight so its not then we will try for seven of length seven then we will try for length six so continuously we will decrease and when we reach i is three the length of sub string is three then we will cut the first servicing which is a b c which is the unique character so hence we found the one sub string of length n which consists all the characters is unique hence we will return the j the answer i there itself if we find it so this is the knife approach and brute force solution so you can pause the video and try it out though it is will be give you time out in lit code because the input size length of here as you can see is 10 raised power force so let us see that what is the time so this is the code i have written for the brute force solution as you can see the first loop for loop is for the length starting from n and it going till the zero so it can be one is fine then we are trying all possible sub string is starting from zeroth index and then moving one by one to until when j plus i is less than what i explain and then we calling the method helper method check whether this sub string is from j to j plus i is unique or not so this is the one way we can check like creating custom side and fill all the characters and check the size of the set if it is equal to length another way if you are a java 8 fan you can directly write this full code in a one liner method like create the characters of from the string then map to the character object and collect them as a hashtag then check the size if it is equals that says so now let's see the what is the time complexity of the solution as you can see we are running two nested for loop here and then we are also running another ah for loop here inside the ah this if method call so the overall time complexity of the solution is o of and q and the space complexity of this solution will be the maximum of n is a number of length of our string or the number of unique characters so let us say number of unique character is capital m so it will be minimum of these two basically so that's it now how can we further optimize this solution so let's understand it so we will use the two pointer to solve this solid problem in optimal way what we will do we will initialize two pointer one is from i from zeroth index as well as j from zeroth index then we will move j right word first so what we will do we will check here okay a is this then we will also use the sad to check whether the repeatedness is occur or not so we will use a set and add all the characters unique character into the set now when we are on j first character we will check that this set contain no then increase j by 1 j plus if set is not contained then increase jy1 and add the character at jth index into this set then we will keep doing it then we will be getted at then c will be getted at as soon as our j will become 4 when j is equals to 4 its in index is 3 basically then we are getting the character a at j equal to 3 we are getting again character a now if we check into the set and this character is already exist so what we will do in that case we will remove the start removing character from i so we will remove the character whatever character on ith index which is a now we will remove from the set remove it once we remove it this j is still same we will not update in that case we will update our i pointer and then we again check if j is not contained if this is not contained if sat is not contained then we will increase j so j will move to the 4 after that so j will become 4 here and we got again v character and this a will be added again in the set so this is the way we will keep adding and removing by the two pointer and then now we need to calculate the longest length so for the longest length whenever we are not finding this character inside the set we will update our longest by the max of either the origin previous longest or the new length so the new length will be as our string contain non-repeated character string contain non-repeated character string contain non-repeated character from j to i so that's it so we will keep this in the maximum of this and we will keep so this is the optimal solution so let us quickly implement the code so for code what we will do we will use a first set of character for checking always whether the set is unique or not if there are and then we will also use the like this is longest will represent the longest length and i from 0 j from 0 and also the n length of our string so let us define all the variable now we will run loop it until i is less than n and j is less than n now we will check if ah set contains if set contains s dot care at our jth index if it is then what we will do we just remove set dot remove the character at as dot carrot i now after that in else case if it is not we will add the character at j sat dot add into add the character as dot carat j and increment j y one and then we will also update our and here also we will update i pointer and here we will update the jth ponder and then we will update our longest y math dot max of previous longest or j minus i so let us try it and let us return the longest the answer of our non repeated characteristics so let us compile the code and see so it is we are getting lets try some other custom test cases like empty space empty string and a b c and then a b c and other like take from other example test case this one so let's put it here and the string with same character let's try it out now and see so it is not done and we are getting the expected answer so now we can submit this code and it got accepted so now what is the time compensation as you can see we are running two pointers and both can go in worst case like up to the length n so this overall time complexity of this solution will become o of 2 n and the space complexity is same as our previous solution which is like minimum of length of string or the distinct number of character in the problem so that's it now as you can see we are running two times can we further optimize it yes we can do further optimization so here if you see every time we are increasing i y one like whenever we are finding duplicate character at this place we are incrementing i y one and removing that character at that index i so instead of that what we will do instead of set we will use now hash map so in hash map what we will do we will map the character and its index where it is exist in our string so that's it this is first we will keep our map here in that way fashion and now again we will iterate this string using two pointer itself again i and j but we will run only jth pointer and i we will update whenever we find the duplicate so let's say first we got a so we will add a at g index 0 then we will add b at index 1 then we will add c at index 2 now when j is 3 and our i is still 0 and now character we are processing which is a and which is our map is contain so in that case what we need to do we will update our i directly jump after that character or jump the next so instead of like marking the index of this character whatever exact index in our string we will add plus 1 so that when we jump i we will just get after the incremented one so we will add 1 over here 1 every time so we will add j plus 1 instead of j so we will update our i will be like map dot get if it is content get the jth character index or like there is can be the cases let us say if i have a string a b and let's say c yeah c then d and here it should be c and then v so what will happen in that case our map will be let's say i create map a is at 1 then we jump on 2 c jump on 3 and d jump on 4 then again we found out the c so in that case our i is initially here at 0 this will we get the jump from this index so now new i is at here which is at 4 ah it should be 3 actually 1 2 three jump at four yeah it's fine it should be so this from the c three it should be three actually so we jumped here and now we got again another b so the b is still present in our map but the jumping is 2 which is less than the current i so if we take directly this that will give us wrong so in that case that because of that we will take the max of previous i or the new jumper from the character index so that's it only the concern once we get every time then we will find out the length longest so longest will be always we will take either the longest or the jth minus 1 j minus i and the plus because we are keeping one eye ahead so this is another solution so if you see here is a code for that using the hash map so first we created a map then we initialize the variable same as our previous solution now we just iterating for the j index and every time we are checking if the map contain the jth character then up jump i to the next index for that characters or the maximum of or i previous i then here we will put the character j plus 1 as i explained so that we can easily jump on the next index and update our longest y j minus i plus 1. so the region of i like initially i will be 0 let us say example here a b c d a b so our i is 0 and j will be here till here until here we calculated already 3. so initial j is 0 we added here and we are increasing j later so that's the reason we are doing here plus one if you can increment first and then find out then you can do that so this is the second solution and here you are just running simply o often and the space is again same if you like the solution hit the like button and subscribe to my channel thanks for watching
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
500 |
hey everyone welcome back and today we'll be doing another Lead Core 500 Keyboard PRO and easy one given an array of string words return the word that can be typed by using the letter of alphabet on only one row of American keyboard like the image below the American keyboard the first row consists of character the first row and second row and third row you know how the rows are and the characters are in there in these rows and we have to just return the elements which can be make made by using the characters of a single row only so alasa can be made by the single row only and that can also be made by the single row only alphabets and hello and T is will be popped off because they require other elements from other rows to be added to them to make them so let's get started now so we'll be making an output list in which we are going to return and for every word in word we will just check if it matches with our set so our first set will be cured top okay then ending it okay then I now we have to make I lower KS because we can just make Global case and it is easy because it is at the same place it if it is uppercase it is at the same place if it is a lower case than it is at the same place and um and all the other elements are the same so that's it and now we can do the same for all other rows so read or match j k l and now we have to end it passing it I and making it lower case also or naughty dot match ing the third row first of all like yes c m b NM and ending it like this and passing it in like I or lower okay so this is it and after that we can just append to our output I if any of that is true and just return the output and that's it let's see if this works or not yes please yeah this works and that's it
|
Keyboard Row
|
keyboard-row
|
Given an array of strings `words`, return _the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below_.
In the **American keyboard**:
* the first row consists of the characters `"qwertyuiop "`,
* the second row consists of the characters `"asdfghjkl "`, and
* the third row consists of the characters `"zxcvbnm "`.
**Example 1:**
**Input:** words = \[ "Hello ", "Alaska ", "Dad ", "Peace "\]
**Output:** \[ "Alaska ", "Dad "\]
**Example 2:**
**Input:** words = \[ "omk "\]
**Output:** \[\]
**Example 3:**
**Input:** words = \[ "adsdf ", "sfd "\]
**Output:** \[ "adsdf ", "sfd "\]
**Constraints:**
* `1 <= words.length <= 20`
* `1 <= words[i].length <= 100`
* `words[i]` consists of English letters (both lowercase and uppercase).
| null |
Array,Hash Table,String
|
Easy
| null |
58 |
in this problem we have a sentence of different words so there will be word one then space word two space and so on and there may be spaces in the end also so we have to find the length of last word in this sentence so you can think of multiple ways so you can start traversing from left and you can tokenize this either using the split function in the languages like java and python or you can use a string stream in c list to separate the words and then you find the last word and return its length but there is a small optimization that can be done here is that let's say this sentence has many words it has thousands of words so we are unnecessarily kind of tokenizing it so this is the optimization that you can think of so we will start from the end so there may be some extra spaces so ignore them as soon as we find a non-space character non-space character non-space character we start our count from there and keep incrementing the count until we hit another space or in the worst case if this has just one word then we will reach the beginning so either of those two scenarios so either first space you encounter from this point obviously there are some spaces after that or you reach the beginning both of these cases we stop and return the length so let's take an example although it's not required for this kind of a problem so let's say we have hello space there may be multiple spaces world and let's say there are few more spaces and there are six seven spaces here so what we will do uh again uh it's up to you if you want to use a split or string stream you can use that but that may lead to some unnecessary tokenization so we will start from here we see it's a space and let's say our result is zero so it's a space so we don't increment it space now this is not space so we increment result to 1 again not space again increment and increment all the way till here till w then it will become 5 next when we decrement it's a space so we return this value if this is more than 0 in these all cases result was not getting increased so it was not more than 0 and we will anyway stop when we reach the beginning so we will return whatever is the result so let's see both of these ways and we will try to run both the cases one by tokenization and one by just traversing from the end and we will see if we can reproduce that kind of scenario where the time taken is more in the earlier case so while there is a word we will not do anything so this body this loop body is empty and in the end we return word dot length and let's see how much time it takes we may not be able to reproduce this scenario depending on the test cases so it's four milliseconds so looks like we are not that lucky to reproduce that scenario let's submit again four millisecond so now let's do the optimal case where there will we will be just starting from the end and we will stop as soon as uh we hit we reach the end of a last word so in that way we will not process the complete string and result is zero so this is the length of last word so n is not a valid index n minus 1 is the last index so minus n or you can also compare just n and then decrement it and then here we will need to add the check greater than equal to so if this is not equal to space then that means we are iterating through a word the last word else if it's not a space then we check that if result length is greater than zero then return it since we are now entering we have crossed the first word then only result was greater than zero else if we did not find any word or there was just one word then this loop will end due to this condition and not this case so we will return whatever is the result so there is one error here so n is not equal to space then we increment the result okay return now it's correct and the solution is accepted and we are here in 0 millisecond so you can see the difference although this difference may not be due to that but maybe this is the genuine difference here we have used optimized solution and we reached here zero millisecond in our earlier solution we tried twice and we never reached zero millisecond now let's write this optimized solution in python and java and the java solution is accepted and here also it's zero millisecond that is hundred percent finally we will do it in python three so its time complexity can be of the order of the string length although if the length of last word is very small compared to the complete string then time complexity will be of the order of word so time complexities of the order of word length i am writing l for last word but in the worst case there may be just one long word and which is same as the string itself so in that case it can go up to n but obviously for most practical cases it would be of the order of length of last word only and if you do tokenization it will be always often in this case of w and wn is less than or equal to n in space we are not using any extra space other than the result variable so it's o of one and the python solution is also accepted
|
Length of Last Word
|
length-of-last-word
|
Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._
A **word** is a maximal substring consisting of non-space characters only.
**Example 1:**
**Input:** s = "Hello World "
**Output:** 5
**Explanation:** The last word is "World " with length 5.
**Example 2:**
**Input:** s = " fly me to the moon "
**Output:** 4
**Explanation:** The last word is "moon " with length 4.
**Example 3:**
**Input:** s = "luffy is still joyboy "
**Output:** 6
**Explanation:** The last word is "joyboy " with length 6.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of only English letters and spaces `' '`.
* There will be at least one word in `s`.
| null |
String
|
Easy
| null |
778 |
welcome to june's lego challenge today's problem is swim in rising water on an n times n grid each square represents an elevation at that point i and j now rain starts to fall at time t the depth of the water everywhere is t so you can swim from a square to another four directionally adjacent square if and only if the elevation of both squares individually are at most t you can swim infinite distance in zero time of course you must stay within the boundaries of the grid during your swim you start at the top left square zero what is the least time until you can reach to the bottom right square of n minus one here i think this is a good example we can see that all these elevations it's going to require us to hit 16 if we want to get to the path that's going to reach the end here now at first glance it kind of seems like this is kind of a path finding algorithm and probably why don't we just start at the zero in zero starting point and just go to the direction that has the minimum point and just start okay we can go up down left or right we can go right here because this is less one and go two three four and just keep following that uh until we hit the end and whatever the maximum height that we had to hit to get to this point was that's going to be the output that's going to be how much time it takes for everything to fill up so that we can reach the end but the issue with that is say that we had some square like this um like if we just started at the zero right and said just follow the one with the minimum one well we can see it's going to go okay zero or we'll go to two then we'll go to three then we'll go to four but here at four the only direction we can go is down and that's going to be hundred and obviously that's not going to be the minimum one so what we'll have to do is uh here to give you a hint to use dextrose and we'll use a variation of extras here what we'll do is put onto a heap all four directions that we can go that's still inbound so here we can go either down to 10 or go right two and we'll put that in the heap then we'll pop off the one with the minimum amount the minimum height and we'll start from there and as long as we haven't visited the node we'll go okay go to 50 we can go three and put that onto the heap and that's just gonna move forward now as soon as we hit four it's going to put 100 onto our heap and we can see that well we have a path that we could have taken before that would actually minimize it less right so we'll go back to that we'll pop that off the heap and we'll start here now instead and see um we'll continue that algorithm trying to minimize the height that we can hit until we hit the end now it's possible that there's no other direction other than hitting this hundred and if that was the case that would happen in our algorithm all right so what we'll have to have is um some sort of heap structure to keep track of this and we'll pop off we'll have uh the let's see we'll have the height we'll put into a tuple we'll have the height as the very first item and the i and j are actually rolling column as the second and third item okay so let's see here let's begin first we are going to initialize n and m so n and m are going to be equal to the length of grid 0 and the length of grid next we need a heap so this just will be a list and we're also going to have a visited set here this will just be an empty set all right so uh well first thing we need to do is add to our list and this is going to be a tuple of um let's see starting with whatever values i grade 0. and the rolling column which would be zero and zero right all right so let's store our output which is just going to start at zero so while there's a heap we're first going to pop off the minimum height right at first there's gonna be zero here so let's first pop that off let's see which we call it we'll call it um i guess we'll call it max and we'll call this r c will pop off heat pop off our heat here okay let's first store our output to be the max either max or output and i'm going to create a list here for the directions i'll call it directions this will be a list of tuples let's see we can move four directions right this would be zero one zero negative one zero and negative one zero all right so four let's call this uh dx and d y in direction we're going to add to our rnc so we'll call this rx and r i'll call it rx and cx i guess which will just equal r plus dx and this will be c plus d y so if rx is in bounds so this is going to be the row which has to be m has to be inbounds of m so rx is within m and ry i'm sorry cx is within n c x within n and this tuple here rx cx not in visited let's add it to our heap heat push onto our heap the value at grid rx cx as well as uh rx and cx itself right so rx cx make sure to add this to our visited set to make sure that we're not going to hit any cycles so this would be a tuple of rx and cx now finally actually we need to have the indication when we know we want to break this loop right so if rc is equal to let's see m minus 1 and n minus one well then we've hit our end so let's break our loop let's break out of here finally we turn our output and let's see if this works okay so that does look like it's working let's go and submit it and there we go accept it so time complexity is going to be uh well okay let's just say n times n is going to be m all right so that's m log m pretty much right because at most we'll be traveling every node or every cell one time so that's n times n and we're going to insert to a heap which is going to be log n times n all right so i think um at first it looks like a really you know intimidating problem but it's actually not that bad if you know dixre's algorithm and simple path finding algorithms all right thanks for watching my channel remember do not trust me i know nothing
|
Swim in Rising Water
|
reorganize-string
|
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`.
The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.
Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`.
**Example 1:**
**Input:** grid = \[\[0,2\],\[1,3\]\]
**Output:** 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.
**Example 2:**
**Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\]
**Output:** 16
**Explanation:** The final route is shown.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 50`
* `0 <= grid[i][j] < n2`
* Each value `grid[i][j]` is **unique**.
|
Alternate placing the most common letters.
|
Hash Table,String,Greedy,Sorting,Heap (Priority Queue),Counting
|
Medium
|
358,621,1304
|
1,834 |
and here I present solution to day 29th of December lead quod Challenge and I hope all of you guys are following along the question is a medium level question on lead code and I totally feel the same it is one of the hot topics of Google and the concept that we will use to solve this question would be sorting and heaps together let's try and understand the question and then we will move on to the presentation where I'll explain it in detail along with the test case iteration the question says you have a single threaded CPU and these are the rules by which this CPU should abide so I'll be talking about these rules in the pp so let's not get into the details over here however just remember that once a task is started the CPU will process the entire task without stopping so you can't stop the CPU from performing any of the task in between the execution unless it is fully done the CPU is not yet available to pick more task also the CPU you can finish a task then start a new one instantly so as soon as a CPU gets free it can pick up another task from the available tasks and can perform them instantaneously what do we need to identify the order in which the CPU shall be executing these tasks so you need to return that order the question says we only have single threaded CPU so there's no parallel processing that can happen this is another important point to remember now let's quickly move on to the presentation and once you will go through the solution you yourself would feel that this question is not that hard although it looks very hard it is not that hard so let's quickly hop on to the BBD now let's get back to the problem the question says you are given task in the form of an array and each task has two attributes associated with it the first one is the time when this task is available to be consumed we call it NQ time or available time the other attribute is processing time how much time will this task take to be executed by the CPU for example this task will be available at the first instant and will take two units of time this task will be available at second instant and will take four units of time this task will be available at third instant and will take two units of time this one will be available at Fourth instant and will take one unit of time there was a very important property specified in the question let's go through that property if the CPU is idle and there are task available then the CPU will choose the one that has the smallest processing time what does this mean so let's consider a hypothetical scenario where the CPU has an option to choose either this task or this task since both of them are available at the first instant itself which task is CPU going to pick up it will pick the one that has lower processing time this one so this will be executed first over this is the meaning of the first statement now let's move ahead the second statement says if multiple tasks have the same shortest processing time then in that case it will choose the one that has the smallest index for example over here let's take the second case let's hypothetically assume that there are two task available the first one is available at the first instant it has four unit of processing time the second one also is available at the first instant and again it has four unit of processing time as you can clearly see that both these tasks have the same processing time then CPU will pick up which one out of these two it will select the one that has the lower index so this one will be selected because it is at the lower index and this one will be taken care later on from this analysis what do we observe what all we can extract from it let's try and understand index is becomes a very important property because of the second constraint and along with these two things available time and process processing time index should be stored because then only CP will be able to make decision in case of collision which task to pick another important attribute to analyze while reading the question while comprehending it up is that the task are not given to you in a sorted Fashion on the basis of available time these are randomly given and from the question it appears that they are given on the basis of sorted order on the property of available time or n few time however this is a myth it's not the question up front doesn't state it but you should be able to comprehend it appropriately by yourself so in the first go what we are going to do we will sort the entire array of task given to you on the basis of available time and since we are sorting the entire array up we have to keep track of the index as well so as to avoid collisions later on therefore I have a updated the input such that my each task has three attributes in it the first one is the index at which it is present in the original array the second one is the available time or NQ time the third one is the processing time now what I'm going to do I'm going to sort this array up on the basis of available time and after the Sorting operation is done my aray would look like something like this although it's the same as given in the original question but that's by coincidence now let's device the algorithm on the basis of which CPU is going to pick up tasks from our tasks array and for this let's hypothetically assume that this is the timeline that is given to us starting from the zeroth index that represents the zeroth time instant going up till the 10th time instant and let's start the operation what we are going to do we'll also store the available tasks that are there up till the timeline the current time that we have witnessed so far and we'll be storing those available tasks in the form of a Min Heap so that when we are pulling out elements from this Min Heap the one that has least processing time will be pulled out first and in case of collision the one that has lower index value will be pulled out first so let's keep these two points in our head and let's start building our timeline the current time interval that we have happens to be zero so at zero do we have any task available know we don't have any task available so let's proceed ahead at let's move to the next time interval which is one at one do we have any task available yes we have one task available so we will be making an insertion of this element into our Min Heap so this elements get added into the Min he 0 1 2 and what do we see that at the first instant we have one task available so what we are going to do we'll pull out that task from the min and we'll execute that task so this gets pulled out and since there was only one task available and we going to execute this task up how much time will it take to be executed it will take two units of time so the first task to be executed is this one and it is going to take two units of time so our CPU will be consumed up till the third time instant and what we are going to do parall while CPU is executing that task we will check for those tasks that are available so far made available so far so the next available time for the task happens to be two so this is available and this is less than three two is less than three that means this task this first task the first index task is available to us for execution so we will make an insertion of this task into our Min he the next task that we have is 232 and this is available at the third time instant since this is also this value is also less than equal to three this task will be added into our Min Heap so this gets added into our Min he let's proceed ahead the next task that we have is 341 and this task will be available at the fourth time interval as a result of which this task won't be part of our available tasks as a result of which this task won't be added into the min he now at the third time instant again CPU has got idle because it has executed the first task and again it will ask for the next task to be executed which one will be pulled out from the Min he the one that has lower processing time which one has the lower processing time this one has the lower processing time which is T2 so T2 will be executed afterwards and it will take two units of time so 3 + it will take two units of time so 3 + it will take two units of time so 3 + 2 gives you 5 now during this time phrase between 3 till 5 T2 will be executed so this task is done now our current time has been updated to 5 units because we are standing at the fifth time interval and we will again see what all task has been made available so far so if you carefully see that this task T3 task has been made available since it has been made available we are going to make an insertion for this task into the Min Heap so three 41 gets added into the Min Heap and now again CPU has gone idle at the fifth time interval it will again Ask Min Heap do you have any pending task the answer is yes which one will be returned the one that has lower processing time so out of these two task the one that has lower processing time will be pulled out so this is gone that means T3 task will be executed and the execution time for this particular task happens to be 1 unit as a result of which between fifth time interval till 6th 1 T3 will be executed awesome now our current time has been updated to 6 do we have any more task pending in the task area that are not yet inserted no we don't have anything pending and we will simply ask the Min Heap do you have anything pending in the Min Heap array yes one task is pending and it will be pulled out so the last task to be executed happens to be T1 and it will be executed up till four units of time as a result of which we can say that T1 will span over starting from sixth time interval till 10th now we have successfully completed all the tasks the Min Heap has gone empty and we will abort the process so what is the execution order that we have derived out of this the first task to be executed is t0 the second one is T2 the third one is T3 and the fourth one is T1 which is in sync with our expectation now let's quickly walk through the coding section and I'll exactly follow the same steps as I have just talked pointer is for iterating over my input array my index pointer is for building my result array and here I've created my result aray let's start the iteration and this is the core algorithm that I have written while my I is less than the total available length of task I have not added or seen all the tasks given in my input array what do I check whether my current time happens to be greater than or equal to my available time for my I task if it is greater than or equal to that means the current task is available for utilization I add that task into my Min Heap and simply inre increment my is pointer I less than task. length is a safety check moving ahead I check whether my Heap is empty or not if it is empty I simply update my current time to the available time for the is Task so this is for the initiation process let's proceed ahead if my Min Heap is not empty that means it has some elements then what I'm going to do I'm going to pull out elements from my Min Heap and this is the task that I have selected for execution I'll update it index uh the index that was stored at the Zer index and add it to my result array and I simply update my index pointer for storing the result array along with this I'll also update my current time to the processing time for this particular task so current time happens to be equal to current time plus current task at the second index which basically represents the processing time and once I'm out of the loop I again check if I still have any task to be executed in my Min he so that is another safety check that I have written I simply extract that task and update add it to my result array in the end we simply return the result let's try and submit this up so this is in sync with what I told in the presentation exactly the same steps accepted with this we have successfully submitted today's solution I hope you guys really enjoyed it and if you're looking for more problems on heap's uh concept then SD preparation sheet is there for you comes to rescue so go and check out this link this is specified in the description section and select the heaps or priority CU section you'll find enough questions to practice wherever you will be stuck you will have the video solution over there itself looking forward to seeing your feedback on these sheets and I will see you tomorrow with another fresh question until then goodbye
|
Single-Threaded CPU
|
minimum-number-of-people-to-teach
|
You are given `n` tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `ith` task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing.
You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way:
* If the CPU is idle and there are no available tasks to process, the CPU remains idle.
* If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
* Once a task is started, the CPU will **process the entire task** without stopping.
* The CPU can finish a task then start a new one instantly.
Return _the order in which the CPU will process the tasks._
**Example 1:**
**Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\]
**Output:** \[0,2,3,1\]
**Explanation:** The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
**Example 2:**
**Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\]
**Output:** \[4,3,2,0,1\]
**Explanation****:** The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
**Constraints:**
* `tasks.length == n`
* `1 <= n <= 105`
* `1 <= enqueueTimei, processingTimei <= 109`
|
You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once
|
Array,Greedy
|
Medium
| null |
1,170 |
hi everyone let's discuss about weekly contest under 51 second question compare string by frequency of the smallest character so frequency of smallest character determine value of a string so for example here set a set the smallest character is a with the frequency of 3 so the value of this string is 3 and CBD the smallest character is B with the frequency of 1 so the value of this string is 1 so we're being asked to query like from the list of war how many were that have the value more than this one so CBD the value is 1 because this Z a Z have the value of 3 so this word failure is more than this word so yeah when we query CBD how many were in the words array have fail you more than CBD do and say this one and see that second example so we have triple B here value of 3 CC fill of 2 and here the value is 1 2 3 & 4 right so we query BBB value is 1 2 3 & 4 right so we query BBB value is 1 2 3 & 4 right so we query BBB how many failure in the words have more than 3 which is only one of them so we return 1 and next we have CC which have the value of 2 so there are 2 or have failure more than 2 which is this too so we return 1 & 2 in that case we return 1 & 2 in that case we return 1 & 2 in that case so yeah to do this in a like normal way like linear way we do it by we checking it through like one by one right and then we found out like we do an end loop each time of the query to determine what is the value of each of them right so in that case then yeah it will require om but we gonna do and binary search so it's more efficient like what is the value of this one and the last one and we take the mid one so yeah we going to perform binary search so we can do it better than oh and complexity for each of the query so let's see how we can do that yeah so first we going to sort the world we're going to solve all of the world or lease by the value so what is careful you can fail you is a method to determine a frequency of the lowest character in that string so we mark the lowest character and what is the frequency and when we found a character that is lower than our lowest character currently we mark our current character to be lowest connector and reset the frequency to one but if we find a character that is same as our lowest character then we increase the frequency and we return the frequency one optimization we can do here is if we already computed that string before then we can catch it and then we can return it every time so we don't need to do this loop again in the game and yeah that's it for the get fail to step and we sort it based on the gate venue and after that for the output I create an output array of queries and then yeah I just do the query for each of them so we will end up on the index that is more than current character more than current the index the first the starting index of the string that have failed more than our character okay so yeah find the words they have to have value more than our query for you there's the fine and then we - the word there's the fine and then we - the word there's the fine and then we - the word line that will we will have our total work like let's say we find it here so index of 2 out of 4 the length of 4 and we find our index here so 4 minus 2 is 2 so we will have to in that case of see like we end up dating X here or if we end up the index here then that means it's 1 right but if we end up the index here then it means it's 0 like the length minus the total ink top the line - the for 0 1 2 3 4 so 4 is the line - the for 0 1 2 3 4 so 4 is the line - the for 0 1 2 3 4 so 4 is the same with the length so yeah you will have a 0 number of work in that case so let's look at the fine method so it's a binary search method with a low and high frequency so you get the mid value and make sure like the value of that word in the middle it's larger than bottom limit then that means our starting point is at least on the mid right but if that failure is less than or equals 2 which means that will be that will not be our starting point so we increase the low by mid plus 1 because the main itself is already not valid so we do make plus 1 so yeah the current case here is if the low is already equals to high it doesn't guarantee that we already from our starting point right so if low is our D equals to high and the fellow is still not valid which means it's not our last index probably so yeah we return the word lengths which will cause this - to become 0 or will cause this - to become 0 or will cause this - to become 0 or otherwise we return our low index right that's how you going to do this query there so yeah what else so yeah I think that's all of it so thank you for watching see you on the next weekly contest
|
Compare Strings by Frequency of the Smallest Character
|
shortest-common-supersequence
|
Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`.
Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** queries = \[ "cbd "\], words = \[ "zaaaz "\]
**Output:** \[1\]
**Explanation:** On the first query we have f( "cbd ") = 1, f( "zaaaz ") = 3 so f( "cbd ") < f( "zaaaz ").
**Example 2:**
**Input:** queries = \[ "bbb ", "cc "\], words = \[ "a ", "aa ", "aaa ", "aaaa "\]
**Output:** \[1,2\]
**Explanation:** On the first query only f( "bbb ") < f( "aaaa "). On the second query both f( "aaa ") and f( "aaaa ") are both > f( "cc ").
**Constraints:**
* `1 <= queries.length <= 2000`
* `1 <= words.length <= 2000`
* `1 <= queries[i].length, words[i].length <= 10`
* `queries[i][j]`, `words[i][j]` consist of lowercase English letters.
|
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.
|
String,Dynamic Programming
|
Hard
|
1250
|
1,099 |
when this is Fisher coder here today is Thanksgiving holiday of 2019 so happy Thanksgiving to everybody out there still watching lead code still practicing lead coding the muse happy holiday Happy Thanksgiving and also I really would encourage you to hit that like button on this video and also don't forget to subscribe to our channel as we continue to publish more YouTube content to walk you through legal preparation for interviews and also I really appreciate a Happy Thanksgiving appreciate for subscribing today we're going to go through a problem $10.99 going to go through a problem $10.99 going to go through a problem $10.99 it's called a twosome less than k it's labeled as easy which it's truly easy and very straightforward and we'll go through two solutions to walk through this problem the problem of this question is given an array of integers and another integer K return the maximum asked such that there were there exists I less than J with a ji plus n J equals to s and s is smaller than K if there is no such I and J exists satisfying this equation excuse me we're just going to return -1 the example here is given this return -1 the example here is given this return -1 the example here is given this array and K is equal to 60 and we can return 58 which is the largest son that we can find which is summed up by two elements in this given array that is still less than K well that is 34 and 24 which sums up to 58 which is still less than 60 we cannot find any other two animals which add up to a number that is still less than 60 Varis tree for second example is given this array which has three animals 10 20 and 30 we cannot find any two elements in this given a rate that could sum up to a number that is still smaller than the K which is 15 so in this case we're going to return -1 a very going to return -1 a very going to return -1 a very straightforward question and the there are two approaches to this problem of course there is a there pros and cons for each one of them since the very first one that people could think of inst you since this array is just it's uncertain and probably we don't even need to solve it but well we'll analyze that in there in a minute if we don't solve this array we'll just go through we'll have an Astrid for loop basically to check every single possible pair of this uncertain array to see if any of the two elements in this given array that would sum up to a number that's still that is still smaller than K which means we'll have one full loop which checks every single element one two three four until the very last second element because we all have another in the for loop which is going to starting from the second adamant after the first full until the very last element right we'll compare every possible combination pairs then we'll see which one is going to give us the largest son that is still smaller than okay the time complexity for that one for this one we don't need to solve it but the time complexity is actually going to be larger which is going to be n square right we can quickly put that into and do Co but before we put that into code I just want to quickly mention that there is another alternative approach compare in comparison to the first approach it actually saves us some time if the n is much larger it's going to be n log n if we just use a buting sorting algorithm for example quicksort in java is going to be a week so the idea the algorithm for the second approach is basically to solve this given array first so after sorting this array every animate in this array is sorted is going to be from small to larger and then we can use two pointers one pointer starting from the very left and the other point is standing from the very right hand then we keep moving these two pointers toward the middle of this array don't while we're moving these two pointers we keep calculating the sum of these two the two animals pointed by these two arrays then we know and which point we move on which pointer actually this algorithm is going to render as o n log n time so it's going to save us some time in the worst case so now I start writing the code well write code for both algorithms and then you'll compare you can see so now let's start writing code for the very first time which reads which is basically we don't start it we're just going to use two-masted for loop so say first we're two-masted for loop so say first we're two-masted for loop so say first we're going to use a max we'll call the result as maxim first we'll initialize it to be the max the main possible mid minimum value in java as an integer and then well you'll see that in the minute why we'll have the first for loop which starts from zero index zero goes all the way to the last second as I just said why because there will have another for loop which starts from the second one which is I plus one and then this one will go all the way to the very last element so we can always have a pair we have two indices to check the two elements in this given array now we'll have another variable called son new song is called Museum which is the son that we are calculating on the fly then based on the problem description if newsom is smaller than K and new son is greater than the current max son then we can just say we find a new son that's cool the maximum is going to be new son else if we find that this new sum is actually bigger than okay which means it's useless it's not something that we want to return in the result in that case we'll mm let's see okay I'm kind of next up for the two algorithm in okay that's what we got in this case in this otherwise we'll just continue moving forward until the very end we're going to check we can just return if we copy this if Maxim equals still equals to this that means we didn't find anything we'll just return minus one has the problem requires otherwise matter when you return max sum which means we find the best Max possible some that could add up to you a number that it's small and that still smaller than K let's double check and go through this problem again yeah looks good to me let's try to hit submit all right Lex it's accepted but you see the time the run time is two milliseconds which is faster than only a quarter of all of the Java online submissions which is not super ideal right we'll go through this problem and this is the one of that first one of the two algorithm two solutions which is giving us let's see which is time is o and square this is the time complexity which is not super ideal right you see we're beating only a little bit more than a quarter of all online Java submissions so let's try another one so I'm pretty sure there are some very long where and is very large and test cases for this problem so which gives me not very good performance for this algorithm so let's start writing code for the second algorithm which is going to give us let's see time complexity is going to be o n log n so first it would be just going to saut as we said what could you solve this algorithm that's given away first and then similarly we're going to keep that's this is the max time consumption for this entire algorithm it's the upper bound the worst case so it's the entire algorithm time complexity is just going to be overloaded and then we'll have another one here I mean this is very similar to the previous solution and now let's have two pointers it's not a master follow up is there's going to be one single wire loop two pointers left and right while left smaller than right io is a typo in new some equals any left Plus and you write look at the new Sun so we'll check if this logic is very soona this one if branch smaller than K and then use is greater than max in this case we're happy that we find a new one like a bigger one which one assigned to the max out else the other there are two other possible cases for in this case the New Sun calculation new Sun could be bigger than or equal to K in both of these cases either it's greater than K or equal to K this is not something that we're happy with which doesn't meet the problem description so we're just going to decrease the right pointer because you see after we saw this array all of these and all of the elements in the given array is insulting owners so all of the bigger elements are on the right end so in this case the new sum is bigger than K so will decrease the right index so that we can find it possibly smaller son the only other case is Newsome is smaller than K in that case we're just going to you increase the right index so then we can try to gradually find a smaller bigger new son so that is still less than K with all of that done we're happy and so say max would you the same track again if Maxim equals to u max integer that means we didn't find anything so we just return -1 otherwise we'll just return -1 otherwise we'll just return -1 otherwise we'll just return max all right that's it well just to give it a shot submit accept it so this time run time complexities one millisecond mmm and is faster than 100 percent of all online Java submissions which I'm super happy you can see the small trick it's not really that small actually it's it matters a lot from oh n square - OH square - OH square - OH n log n that's a big jump in terms of time comes in terms of time complexity especially when n is very huge which is usually the case in industry right I'd say how many items are nearing Amazon or how many search queries and they're performing being performed every single minute or every single second on Google search engine right so when you get asked for such a simple straightforward question make sure that you can walk through you can talk very clearly with your interviewer the pros and cons of each algorithm and why you pick any one of them well I hope you liked this video if you do please don't forget to hit the like button and don't forget to subscribe to our channel as we continue to publish new good YouTube leave code algorithms content almost on a single daily basis so don't forget to subscribe thank you very much I'll see you guys next time
|
Two Sum Less Than K
|
path-with-maximum-minimum-value
|
Given an array `nums` of integers and integer `k`, return the maximum `sum` such that there exists `i < j` with `nums[i] + nums[j] = sum` and `sum < k`. If no `i`, `j` exist satisfying this equation, return `-1`.
**Example 1:**
**Input:** nums = \[34,23,1,24,75,33,54,8\], k = 60
**Output:** 58
**Explanation:** We can use 34 and 24 to sum 58 which is less than 60.
**Example 2:**
**Input:** nums = \[10,20,30\], k = 15
**Output:** -1
**Explanation:** In this case it is not possible to get a pair sum less that 15.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 1000`
* `1 <= k <= 2000`
|
What if we sort each cell of the matrix by the value? Don't include small values in your path if you can only include large values. Let's keep adding a possible cell to use in the path incrementally with decreasing values. If the start and end cells are connected then we don't need to add more cells. Use union-find data structure to check connectivity and return as answer the value of the given cell that makes start and end cells connected.
|
Array,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix
|
Medium
|
1753
|
1,704 |
hi everyone welcome back to the channel and today we solve e code daily challenge problem number 174 determine if strings halves are alike so we'll check out the problem statement and then we'll uh check out the approach which we're going to use it's a really simple problem to solve and yeah let's check out the problem statement first so the given problem statement says uh you are given a string s of even length Okay you have to highlight this split the string into two halves of equal length let a be the first half and B be the second half okay true strings are alike if they have same number of vs and these are case insensitive okay uh return true if a and b are alike basically if both the halves have same number of vels otherwise return false so what we can do is we can just simply uh use the counter technique like in which you just count the vble so that's what exactly what we're going to do but I have tried to uh put an optimization layer on top of it so what we'll be doing is uh I will run a loop for in by two times only basically uh I don't want to uh run the loop end times for the complete list but we can do the same with running it at half as well so what we'll be doing we'll get the number of elements in the string given we'll get the middle of it and as soon as we get the middle we know that okay this is the partition now do uh so basically it's all about you know coming up with this formula it's a very simple formula so what we'll do for string a which is the left side which is the left string uh we will just simply follow index which we are getting from here basically we are running a loop from 0 to Mid minus one and we getting the index for left string but for right string what I have done I have just uh simply I'm just simply calculating this for example in this case the Nu is 4 okay my current index is let's say 0o so if you do the calculation 4 - 0 - 0o so if you do the calculation 4 - 0 - 0o so if you do the calculation 4 - 0 - one we will get the last element so uh we are checking the first and the last element at the same time okay if any of this is uh is the V we will uh keep two more variables let's say a count and uh a count and B count so as soon as we reach any Vel in any of the string we will keep on adding into it okay so on so this is the approach so and as you know like these are the vbls a e i o u and yeah that's it let's check out the solution now so coming to the solution uh this is exactly what we discussed uh while explaining the approach I took a uh a variable in which I'm storing the length of the string we are calculating the middle of it and we have initialized two variable a count B count to basically count the number of WBLS in each of the halves uh we are initializing with index zero and what I'm doing I'm running a while loop until I reached uh you know mid minus one basically and what we are doing over here I have uh you know written this in single line but this is a simple if statement where I'm checking if the current uh element is a Vel or not if it is a Vel I am adding one into it otherwise I'm adding zero into it same with B count uh the formula is a bit changed like as we discussed in the explanation so number of elements minus current index minus one okay if the element at this uh value is a Vel we will add one otherwise zero and at the end we are simply incrementing the value of index at last what we are doing we are checking if both the values are same if yes it will return true automatically otherwise it will return false so let's check out the test cases as you can see the test cases C clear let's submit it for further evaluation now and the solution got accepted and I say like we performed average we have performed 55.68 per of the submitted performed 55.68 per of the submitted performed 55.68 per of the submitted solution so yeah thanks guys for watching other the video stay tuned for the uping ones don't forget to like the video and subscribe to the channel thank you
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
1,802 |
hi guys welcome to algorithms Made Easy my name is khushboo and in this video we are going to see the question maximum value at a given index in a bounded array so let's go through the question you are given three positive integers in index and maximum and you want to construct an array nums which is 0 indexed which satisfies the following condition there are few conditions given to us that we need to satisfy and form an array what are we going to return is we are going to return nums of index of the constructed array so now what are the conditions that we have one of the things is n that we are given in the question is the length of the array secondly we are given a condition wherein we see what all numbers can be there in that array so the numbers that are present in an array can be positive integers less than n now one thing that I want to clarify over here is that the question States it will have 0 but according to the test cases that are given in the question 0 is not permissible so we are going to take into consideration that our numbers can range between 1 to n minus 1 I hope this is clear now let's move on to the third condition which is the difference between any two consecutive integers in the array is going to be either 0 or 1. which means you can have a maximum difference of 1 between 2 consecutive integers in the array fourth condition states that the sum of all the elements in the array should not exceed maximum which is the third parameter that is given to us in the question finally fifth condition States what we need to do with the index that is given to us we need to maximize the number that is present at the index and finally return that maximized number so let's go through the first example quickly over here we are given n equal to 4 which means our array is of length 4 index that we need to maximize is to the maximum sum that can be formed with that array is 6. now the output over here is 2 why we are given with an explanation as well so the numbers array will be 1 2 1 or it can also be 1 2 1 wherein the second index is maximized to 2 while satisfying the conditions which is the sum of the array should be less than or equal to 6 it also states that there is no array that satisfy all the condition and have nums of 2 equal to 3. if we try to put 3 over here then at least one of the condition is not met and so we cannot give that answer so the answer over here is 2. we will see the examples in more detail in our explanation so let's go and see how we can solve this particular question let's take the example one wherein we were given n equal to 4 index equal to 2 and maximum equal to 6 so what we are going to do is we are going to maximize the number present in this particular index while limiting the sum of all the elements to 6 and also that we are going to have elements from 1 to n so initially what we are doing over here is filling the area with once this is the least number that we can fill our array with now after filling this we'll get a sum of 4 so we still have a scope of improvement because maximum is greater so let's try and maximize this once we make it 2 our sum becomes 5 and it still satisfies the condition that the adjacent elements must have a absolute difference of 0 or 1 Let's again try to maximize this element that is to increase this particular value now when we increase this value we also need to increase the other elements as well that is we need to make this as 2 and we need to make this as 2 because we need the absolute difference as 1 or 0 but as soon as we do this the sum becomes 8. this is not satisfying the condition of Maxim that we had so that's the reason we need to go with the answer as 2 and that's the output that was shown in the first example given to us in the question itself so now how are we going to achieve this answer for that let's take a bigger example and let's see how we are increasing the number and how the rest of the array behaves so over here we are taking a array of length 6. and at the position 2 we are trying to increase the number that is maximizing the number now notice that when this is 2 all the other elements can be one when this is 3 the element just next to it also increases by one then this is 4 the element from this 0 to index 4 are getting changed and when we increase this to 5 all the elements are getting updated so what is happening over here is we are having the maximum number of elements in the left we can go maximum number of elements at right we can go and at a particular time when we are increasing this element the effect or the ripple effect also goes to some elements in left and some elements in right so when we were over here what we see is let's see here the left and right are zero and this is increased by one left and right also increases by 1 and this also gets increased by one in the next iteration this left and right index got spread by one more while I increased this element by 1. and similarly this happened over here as well now this was the boundary that is left was having a boundary so left couldn't go beyond this but we had a scope to stretch in the right in this case so as soon as we try to increase the index at which we are given we also need to increase the elements in the vicinity as well and that triple effect goes on till my absolute difference is greater than 1 so now we also need to code it in this way so let's see a dry run of how we can solve this using this particular scenario for that let's understand one of these things so over here there are different variables present this is the index this is the maximum we can go to left this is the maximum that we can go to right and while increasing our particular index value we are going to take into consideration some left and some right so firstly let's see what Max left and Max right is Max left is the number of elements in the left which is nothing but equivalent to the index Max write is n minus index minus 1 which is n is 6 minus this index 2 and -1 which is 3 elements in the 2 and -1 which is 3 elements in the 2 and -1 which is 3 elements in the right now let's solve the question we take n is 6 index is 1 and maximum that we can achieve is 10. so over here we have index 1 in the start we'll take the left and right that we are going to increment as 0. we are just going to increment this one first so what happens over here is initially the sum was 6 because we have filled the array once now we are trying to increment this by having left and right as 0 so what we are trying to do is we are not incrementing anything in the left anything in the right just the centerpiece so that gives us this particular array and now the current sum will become as 6 plus this 1. that we have incremented so that becomes 7. me let's go further now when we are trying to increase this we will also have the ripple effect to the elements in left and right so my left will increase by 1 and right will increase by 1 and this left and right will only go till my Max left and my Max right so now my current sum what is my current sum it is equivalent to the previous current sum plus number of elements I have incremented in left which is 1 and number of elements that I have incremented in right which is also equal to 1 and the one that I have increased for the center element or the index so that is equal to 7 plus 1 that is giving me an answer of 10. and this becomes my array now let's go forward and try to maximize this further as well once we try to do this our left and right also increases now my left cannot increase because it is the maximum lift right we can go till 4 but we haven't reached 4 so we can increment this so what happens over here is it takes the previous sum it takes the left it takes the right which is 2 and it increases the center index as well and the current sum with this becomes 14 which breaks the condition of Maximum and so this cannot happen and my array formed with this particular condition or this particular Center index is not valid which means we need to take the previous one as our answer so 3 is going to be the answer in this case so this is the basic approach or The Brute Force approach where we are trying to fill the array with once and trying to increase in a step manner what is the time complexity over here in the time complexity will go up to the steps that we are taking in order to fill this or optimize this particular index since my bounds of the questions are too high this particular approach will give me a time limit exceeded now how do we optimize this before that I highly recommend you to go ahead and try to code this Brute Force approach out and submit it so that you get a tle and then come back here to see how you can optimize it now let's see how we can optimize this particular approach for this we need to pay attention to how the working is for that let's consider this example further we increased our maximum to 30 and now let's continue this so over here the current sum is 14 and we can still go ahead so with this array we are going ahead so we are increasing our boundary of write and reaching its limit and we are getting the current sum as 25 we have the last term that was 19 plus this one in the Left 4 in the right and Center Index 1. this gives us 25 next iteration what will happen we are going to take this current sum and we are going to add the same number of values because my left and my right has the same number of elements that are getting added so what is happening over here is the increments that I am going to do in left and the right part is going to remain the same for all the iterations from now on because my right and left has reached its bounds so current sum plus equal to this portion remains same and so instead of looping over it I can break it down and I can use the division operation over here for the remaining Maxim that I want to fill in for example if this were 50 I would have done I would have stopped over here and I would have taken 25 by 5 which is 5 more iterations wherein I can increase this sum so in this case what we are effectively doing is till we have right and left Palms that is till n we are going to go in a step wise manner but as soon as we reach that particular point we are breaking it and we are applying a mathematical formula to reach the answer in one single step so we are effectively decreasing our time complexity to O of n rather than o of Step so let's go and code this particular approach out and see how that looks okay so let's start with initializing a few variables we'll take a result which is 1 and this result means that I have utilized my Maxim by filling the array with once so my maximum now becomes maximum minus n with this I have a left which is 0 and right which is also 0. and I also have a Max left which is equal to index as we saw in the example and my Max write which is equals to n minus index minus 1. after we are done with this we are going to take a while loop stating that while my maximum is greater than 0 I am going to perform some actions first action is maximizing my index value which is result plus next thing that I am going to do is calculate my left and right values that I am going to increment so left Val is minimum of left hand Max left with this in every iteration my left is going to increase and same is going to happen with right as well now that we are done with this we are going to update the maxim as well so Maxim is going to become maximum minus the elements that we have used which is 1 plus left 12 plus right well wherein 1 is for incrementing this left Val is incrementing the numbers in Left Right Val is incrementing the numbers in right with this I am also going to see whether I have reached my condition wherein I can optimize the solution that is I have reached the bounds of left and right if my left balance right well have reached my maximum lift and maximum right I can simply break from this Loop now once I am breaking from this Loop and if still my Maxim is not exhausted I need to add something in my results what I am going to add is result equal to result Plus maximum by n finally we are going to return so now while returning I'll check if my Maxim is gone below 0 which means I have taken one more element into my result so I need to reduce this while I am returning it else return the result as it is that's it's giving perfect result let's try and submit it and it got submitted so over here the time complexity is going to be the number of elements till which I am going in my left and right maximum which is going to be equal to n and my space complexity over here is over 1 because I am just using a few variables to keep my values in that now can we solve this question in a better way the answer is yes there is a better way to solve this question which is by applying binary search if you want to learn how to solve this question by binary search follow the link over here and it will lead you to the explanation to the binary search video for this particular problem I hope you like the solution and if you did please do like share and subscribe to our Channel and thank you for watching the video I'll see you in the binary search explanation till then keep learning keep calling
|
Maximum Value at a Given Index in a Bounded Array
|
number-of-students-unable-to-eat-lunch
|
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions:
* `nums.length == n`
* `nums[i]` is a **positive** integer where `0 <= i < n`.
* `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`.
* The sum of all the elements of `nums` does not exceed `maxSum`.
* `nums[index]` is **maximized**.
Return `nums[index]` _of the constructed array_.
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
**Example 1:**
**Input:** n = 4, index = 2, maxSum = 6
**Output:** 2
**Explanation:** nums = \[1,2,**2**,1\] is one array that satisfies all the conditions.
There are no arrays that satisfy all the conditions and have nums\[2\] == 3, so 2 is the maximum nums\[2\].
**Example 2:**
**Input:** n = 6, index = 1, maxSum = 10
**Output:** 3
**Constraints:**
* `1 <= n <= maxSum <= 109`
* `0 <= index < n`
|
Simulate the given in the statement Calculate those who will eat instead of those who will not.
|
Array,Stack,Queue,Simulation
|
Easy
|
2195
|
258 |
hey everyone today we are going to service a little question how to digits giving my integer named repeatedly at all its digits until the result has only one digit and return it so let's see the example so you are given 38 output is 2 because so we can separate 38 so numbers like three and eight so this calculation results in 11. and then we can separate again we can separate 11 like a one and one right two one right and the result between two so now uh we have only one digit so that's why output is 2 in this case and then let's see example two if we have a zero as an input number so we should return 0 because it's already one digit so we have a follow-up question so could so we have a follow-up question so could so we have a follow-up question so could you do it without any Loop or recursion in o1 runtime yeah so I'll show you how to solve this question two ways so one is a not a one and the other is a o1 plan time 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 the 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 38 so this is an input number and this is a return value result variable and that use of this question um first of all the main point is we divide the 38 and get to the model and all other all model O2 result variable so how can we get a model so it's simple um pass it so divide the percent 10. so in that case first of all we get uh eight as a matter of right so other eight to result variable and then after that we just divide the 10. so that we can get actually uh three right 38 divide 10 and get the 3. and then again we negative either with a percent 10 and I get the model in that case we get three so other three the result variable and 11. and uh just a device three divided 10 and I get a zero right so and then one Loop is finished but we still have like a 11 negative two digits so now um update a number with result variable so now number should be 11. and then we repeat it the same process and 11 divided pass and 10 and I get a module in the case one right so sorry default we iterate an iteration always a reset the result variable we still and then execute the division and passion 10 and get the one so other one plus two result variable and then after that 11 divided 10 just slash version and so that we can get just one and then uh divider with percent 10 so I get the one so other one to result variable in the case two and then one slash ten and then I get the zero so we finish iteration and so now number is zero and the result variable is 2. and then um update a number with result variable in that case two but uh this number is one digit so we finish iteration and then we should return two in this case yeah so that is a basic idea to solve a discussion so with that being said let's get into the code okay so let's write a code first of all if the input number is less than 10. in that case we just return the number it's simple and after that if not the case we use a two Loop so while number is greater than or equal 10 so we continue Loop and uh first of all um every time as I explained earlier so every time we start the iteration we reset the result variable with zero and then we need one more Loop y number is not equal um 10 not 10 0. in the case we continue um like a division so result plus equal number percent 10 and uh get the mother row and the other result variable other two result variable and then after that um num in Python we need a two thrush to get the integer so equal or equal 10. and then um if num is zero after that update a number variable with result variable for next iteration and then when we finish uh looping just return result variable yeah that's it so let me submit it yeah looks good and the time complexity of this solution should be order of log n so the outer while loop lands as long as num is greater than or equal to 10. so in each iteration of outer loop the inner loop calculates the sum of digits of num and updates num to be the sum so this process continue until num becomes less than 10 at which point the Outer Loop terminates the number of digits in Num determine the maximum number of iteration for in a while loop the maximum number of digits in a decimal number num is a base 10 logarithm of num which give us the upper bound on the time complexity so that's why time complexity of this code is on the over log n as the number of iteration in the inner while loop depends on the number of digits in Num and the outer while loop learns at most based on logarithm of num time and the space complexity is a 01 as it use constant amount of extra space to a result variable legal address of input size of num it does not depends on the size of num or any other input variable so space complexity is a constant so that's why o1 okay and then next I'll show you how to solve this question with a one long time okay so this is a one runtime case so look at this list so the numbers of left side is our input number and the numbers of right side is a result of calculation like a input number more model and nine so yeah I'm not sure you can use this idea in the earlier interview but if you notice this circle so we can solve this question with one runtime and uh there are two base cases and the one is a if input number is zero so we should return zero immediately and if input number we can divide the input num bar and get the zero in the case um we should return 9. so if input number is 9 if we get the 18 as an input number we should return 9 and 29 are 27 and 9. yeah so we have a two base cases so with that being said let's get into the code okay so let's write Circle and the program is very easy so if num equal zero in that case we return 0 and if num um divide 9 and get a model and uh the model is zero and then in the case we should return 9 and after that just return num divide 9 and I get the model yeah that's it so let me submit it yeah looks good but I don't know why it just six percent so yeah um time complexity of this solution should be all one and the space complexity is also one I don't use the extra data structure 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
|
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
|
746 |
going over the Java solution for lead code 746 Min cost climbing stairs you are given an integer array cost where cost I is the cost of the I'd step on a staircase once you pay the cost you can either jump one or two steps you can either start from the step with index 0 or the step with index 1 return the minimum cost to reach the top of the floor so in example one you're basically going to either start at 10 or index 0 or 15 or index 1 and then you're trying to reach this end of the array or beyond the last element so whenever you land on any one of these you're gonna have to pay the fine and then you can jump either one or two steps forward so in this case the optimal way to minimize cost is to start at index 15 and then jump to get out of there with example two instead of starting at index two which will get you closer it costs 100 so you would instead start at index one and then you would jump to jump two jump one and then jump two and then jump one or two to get out this way you avoided all the hundreds and basically optimized for the minimum cost so this problem is really is a really good introductory problem to dynamic programming and greedy algorithms so dynamic programming is basically breaking apart a large problem into smaller subsets and then figuring out the optimal solution for each and basically scaling your way up to the larger problem and with greedy algorithms it's basically taking into short-term gain the basically the choice short-term gain the basically the choice short-term gain the basically the choice that is the most beneficial in the short term without considering long-term without considering long-term without considering long-term implications so let's implement this um basically the idea here is that we're going to make a separate array that keeps track of how much it costs to reach each element so this sort of has a bit of dynamic programming into it so instead of saying okay what is the minimum cost for this entire array we can say what is the minimum cost to reach this element and in that case that would be basically the minimum cost between one or a hundred cents we had to start on either one of these then we could just jump to this one so in that case it would be this one and then we would jump to this one so we could put in a 2 here since one plus one would equal two then if we wanted to figure out what is the minimum cost to reach this index then we can say what is the minimum cost between 100 and this element which we updated to a two and in that case it would still be this two so we can change this into a three so basically the minimum cost to reach this index is three then if we want to reach this index it's basically what is the minimum cost between two and three and that we're gonna pick two so this will turn into a three and it's basically just keeping track of how much it costs to reach is each index and we're gonna use that information in the future to help educate our guesses so in terms of dynamic programming we're basically breaking it apart into smaller problems and in terms of greedy algorithms we're just choosing whichever one is the shortest between the last two so let's Implement that let's make a new array uh that will be cost dot length and basically this array will keep track of how much it costs to reach each index of cost so to re if a cost was only made up of one index and let's say we had to step on at least one you know the cost to reach index um zero would be the cost of that index and then the cost to reach index one would be the cost of that index and now we can actually start a loop so now the next index is going to be the math dot Min of basically cost I so how much it costs there plus array of I minus 1. so how much it costs to get basically for example in this element how much it costs to reach this it's basically the minimum cost between either 100 or 1. so we can say that cost I plus array I minus 2. so for example if we reached this index so this I think we said what would be cost two since you could go one and then this one so it would become two so now we're seeing what is less either one plus two or one plus a hundred whichever one it is that's what we're going to update this as so that's going to become the cost the minimum cost to reach this index so we can just do that and then at the very end we can just return the minimum between array.array.length minus one and array.array.length minus one and array.array.length minus one and array um array dot length minus two so since it's the whole idea that we don't need to reach the last element if we are one element behind it we could jump two to get out or if we are at the last element like in this one we can just jump one to get out we're just gonna pick the minimum between these two so that should be it let's see if it works okay great and let's submit it okay great so that was most
|
Min Cost Climbing Stairs
|
prefix-and-suffix-search
|
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999`
|
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
|
String,Design,Trie
|
Hard
|
211
|
916 |
hello everyone welcome to my channel it's all the problem whatsapp send sauvir awal distic of this letter no say davy in subscribe birthday is every letter in vehicles including multiplicity between slide all characters of world vs wave and for example you are subscribe w8 sexual behavior inner World This Week Busy Subscribe This Note Clearly world8115 That Boat Se Award S From A Universal Is For Every Living Being So Vs Universal 5V A Subset Of K Solve Video Player Words Are Involved In This Software Will Have Two Words Payroll Active Vivo y51l Secretary Idea Universe Which Way All The World In The First One To Give This World And No It Is The Universe subscribe to The Amazing This What Is This That And Similarly Second Ko Vinod And Again This Is Not Universal taxi123 This Dowry This Is The Worst Universal World In Response To A Writ Similarly Disawar Universal World And Universal Turn On This Is The Like Through All Wave In Every Word In Websphere Will Take A Universal Mother Was Not A Universal For Seervi Length Multiply Wealth Of Nations On Web A Big Time Complexity And Will Cross Sign In Power Or 900 Hens This Will Definitely Time And Morning To Look Pure Optimal Solution To Get Accepted How Will Solve This Month But Even So Fasval Cvr Looking Dear All Characters In Every Combine All The Character Maximum Frequency Same Office Character In All The Words Of Being So Hair Oil Creative World Are Special Frequency Of This One And No One In This To Just Check Out This Word Left For Every Word With Sacrifice Frequency Is Canteen 20 Characters More Than And Requested Acidification Ladi Tractor 1035 Vikram Universal Other Wise Notes Sonth 20 Frequency of Its Amazon Veto Ki Frequency Office Two Frequency of Amazon Frequency of G-20 One and Frequency of This Frequency of G-20 One and Frequency of This Frequency of G-20 One and Frequency of This One is Not Preferred Complete the Year and Nothing Is This Avoid Unwanted Arrangement Similarly Later This Google Hey Google Visit Two Time Over Two Time And Mail Is Vansh 151 We Can Use This Word From Which Is The Current Way Universal Into Another Example In The World Will Be Ide Degree Holder For Five One In This World Will Be Difficult To One Is This Quincy How Will They Take Maximum And Observe This Will Be Competitive World And See This Vansh Schezwan Finally Bigg Boss Safir Words Will Process In The Final Race For The Voice Of Birth subscribe and subscribe this Video Subscribe For We Need A Giver Subscribe 6 kal Swimming first generate second from all fierce minute word string vs ind vs waste oil new vpn ninth to find out the country of physiology of the country in the world witch your new of 69th urse character in we can see in chronic character in we can see in chronic character in we can see in chronic tomorrow morning Trolley Characters and Update Frequency of Return - A Plus Subsidy Frequency of Return - A Plus Subsidy Frequency of Return - A Plus Subsidy Frequency More The Small Works Latest Way Great Will Update Our Videos Most Strongly Do Subscribe The Value of the List of the Result is That Aap Turd Bhi Trait of These All the The World Lived A String In Na For The First B25 Difficulty Of Which Will Be Free From All Characters Page Straight Minus Plus Width Of First Company Universal Life Which Will Return Of Truth Will Withdraw The Universal And Definition Of The Universe Apni Villain Type And Will Accept d2h rape cases after and safety 200 hair vijay cigarette project from physical 202 left blank 8 plus novel check only i10 acid is luddi frequency between there frequency of veer is not possible to find all world subscribe will be late me no problem festival In this case Saudhar flashed this time and destroyed a resistance ear cutting also expected answer Sunavai can submit this code side of NCOS not accepted what is the time in sports complex and dissolution and you can be treating all the world in marriage and Also in the world which is the time complexity such a land of which word in verses Max MP Vijay Najoomi test questions for the time complexity video of A+B in video of A+B in video of A+B in vigilance officer subject and space agency bears in fuel specific ward-26 want bears in fuel specific ward-26 want bears in fuel specific ward-26 want two times which Consists of another woman to make which demon of vegetable and small method which can us this code on the user desired light swell radio frequency so they can return gift veer subscribe me hee return bhi frequency tarf vanshi return will hear his great Difficulty Are Enough To Call Me All 210 What We N B Kendra Use This Method Over The Years Will Also Be Just Qualification Pro Incident Give Me Three Lines Of Bj School And Subscribe To Hai Acid Yogesh And Time Complexity Same Just How You Can Right and Effective End User Apple Cider Using Code to Feel IT Solution and Different subscribe To My Channel thanks for watching
|
Word Subsets
|
decoded-string-at-index
|
You are given two string arrays `words1` and `words2`.
A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity.
* For example, `"wrr "` is a subset of `"warrior "` but is not a subset of `"world "`.
A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`.
Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**.
**Example 1:**
**Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "e ", "o "\]
**Output:** \[ "facebook ", "google ", "leetcode "\]
**Example 2:**
**Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "l ", "e "\]
**Output:** \[ "apple ", "google ", "leetcode "\]
**Constraints:**
* `1 <= words1.length, words2.length <= 104`
* `1 <= words1[i].length, words2[i].length <= 10`
* `words1[i]` and `words2[i]` consist only of lowercase English letters.
* All the strings of `words1` are **unique**.
| null |
String,Stack
|
Medium
| null |
713 |
Jhaal Hello Hi Guys Welcome to Questions Today's Question is the Weight Lose Bank's In This Question Beer Drinking Are Positive Integers Personality Account and Friends in Number of Morning Swift of All Elements in Directions Amazing's Intermediate Hindi Pimple Wear Dresses Only You All the subscribe this Video in this case the total number of morning 8052 1652 e jai hind survey research plant element so in the morning of this bank to find your servants and have you not one thing morning stand 52 acid 2012 cases will have to take care product considered against the product Be Considered Only 2 subscribe this Video not and not understand this question on and sunao bhi approach will also be using the sliding window approach in this is it is the are RKVY stand and appeal value peeth yovan happy represents the current product offer savere- Morning Start product offer savere- Morning Start product offer savere- Morning Start Arrangement 23.20 Will You Will Happen And You Will Arrangement 23.20 Will You Will Happen And You Will Arrangement 23.20 Will You Will Happen And You Will Be Amazed End Widows Main One Only Suno Today Encounter Will Move To Next Index Hair Products Start Head Post Office Amazon Starting End S2 Swapnil Vikram 2nd Number Thoughts Input Website End This A Total Number Female Dentist Savere 1000 The One How To That Under-12 Sunidhi President Start And Under-12 Sunidhi President Start And Under-12 Sunidhi President Start And Position And Will Mo Hain Next Step 9 People Earthquake Victim Northrop This Away From Studio Vikram Six Sudesh 16June If Survey 200 Account Number On WhatsApp Balance Between Acidity Are A Total Number Six batter torch band how two hands free I am one two combined and two three combined Sudeep subah savere four this is 32 16 two and one early morning 1234 is 2030 availability for daddy noida point rautahat so r product normal vikram a dot vikram aaj bhi product corrupt wall paint videos1 * * * aaj bhi product corrupt wall paint videos1 * * * aaj bhi product corrupt wall paint videos1 * * * 36 28 34 Birthday 2014 Switzerland's Sudesh Survey Will Not Be Included in an Answer Details of Variable Noida Pannu said that not beer 365 days the teach that from starting to ending what is this but the relationship between This Account Details Visit Three Little Baby Below This Account Which One At Every Step With Adding And Minus Plus One In An Account Variable Dare Devils And Is We A While And Advertising And Pr Who Is Equal To Pintu Number Of And Related Posts Which Hair Morning Us oy give this product is a practice which have been counted as president's 22nd over a key and drew the operational spirit welcomed sanm start anil aaron this algorithm on this are sunn the initial you is dynasty artist will contain deep roadways one nine and a large Number of Features Pain Number of Diabetes Patient 10 Ki Sudhir Shahi Look Note of Tennis Losing Which is Pain No Who Will Check and Next9news Pages of Losing and Not No Speed This Pages of Losing and Not No Speed This Pages of Losing and Not No Speed This Day Will Up and Minus Plus One in a Account It is Account Will Continue For This Language 0.1 Content And Minus Plus One 9 Language 0.1 Content And Minus Plus One 9 Language 0.1 Content And Minus Plus One 9 And 10 2010 Plus 13191 Law And Order Will Move Ahead That Nobody Will Happen Not In This Position Will Happen Will Multiply Divine Of Birth Norms And Not Be Leaf Number Pandit 5hp Stand Pure Soil But Will Result In fact I know what will happen will check the smile on one product is loot member loop inverter notification one that destination K Sudheesh condition will run rate this will increment account with and minus plus 1.1 August 2002 Superintendent account witch plus 1.1 August 2002 Superintendent account witch plus 1.1 August 2002 Superintendent account witch to total Vikram 3 Main Naagin Will Move And Hens No Similarly If Bump A P Vikram Android Show Man Or Peace Vikram Pious Bikramandal Sudesh Garlic Meat Bhi Transaction Ke Badhenge It Is Equal To K Sudesh Files Will Run Voice Of This Lesson Number Time And Pimple Took 10 Days But Will Do I Will Divide Rp That Married Per Device You Power System Tell Us Which Stands For PM Vikram 10th And Start Living In The District President Vice President Will Start From The Window In The Mid-1960s Android 2.2 99 Subscribe And Minus Android 2.2 99 Subscribe And Minus Android 2.2 99 Subscribe And Minus Plus 1.525 125 Mo the Plus 1.525 125 Mo the Plus 1.525 125 Mo the head and order and plus 9 vikram pimple problems and 6th 6066 mein knowledge can see but is deep is lagna ka person shalu will not run and effigy in k shivling reminder account plus 2 and craft with and western plus one and destroyed co tight is Vansh 2nd list 3 started 13012 plus one dead three five plus 3809 widow and plus app that noida and plus solid will not come back in this loot is condition has been st pauls sunao hindi and office look printout saudi value will be returning this eight this Was Deprived From This Question Commission District The Video Thank You
|
Subarray Product Less Than K
|
subarray-product-less-than-k
|
Given an array of integers `nums` and an integer `k`, return _the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than_ `k`.
**Example 1:**
**Input:** nums = \[10,5,2,6\], k = 100
**Output:** 8
**Explanation:** The 8 subarrays that have product less than 100 are:
\[10\], \[5\], \[2\], \[6\], \[10, 5\], \[5, 2\], \[2, 6\], \[5, 2, 6\]
Note that \[10, 5, 2\] is not included as the product of 100 is not strictly less than k.
**Example 2:**
**Input:** nums = \[1,2,3\], k = 0
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `1 <= nums[i] <= 1000`
* `0 <= k <= 106`
|
For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function.
|
Array,Sliding Window
|
Medium
|
152,325,560,1083,2233
|
448 |
hi everyone today we are going to solve the readable question find all numbers disappeared in Array so you are given already enough of any integers where NSI is in the range from 1 to n return array of all integers in the range one from 1 to n that do not appear in numbers so let's see the example so you are given 4 3 2 7 8 2 3 1 and in this case n is 8. so from 1 to 8 um so output is five six because five six do not appear in the range from 1 to 8 in this case so that's why output is five six and uh actually uh we have like a follow-up we have like a follow-up we have like a follow-up and could you do it without the extra space and in on runtime so you may assume that The Returned list do not count as an extra space okay so let me explain with this example uh to solve this question I use two loops and in the first loop I use each number to calculate the index number with the this formula so let's say we have an A4 and the index number is um I put 4 into bar so four minus 1 and index 3 and then um go to like a zero one two three and uh if index 3 is a positive then multiply minus 1 and change to negative number so in this case um so 7 is a positive so we change the 7 to minus 7. and then maybe next again we use three to calculate the index number so three minus one is 2 so 0 1 2 and if the number at index 2 is positive then change to negative uh by like a multiply minus one so in the case we change negative two and then move next so now um index 2 is a negative two so that's why uh we every time we get the absolute value uh because uh we need the index number but basically uh the index number is positive not negative so like this case uh the number already negative like this case so that's why we need to uh get the absolute value to calculate the index number so in this case the value already negative but uh if we get a solute value so that means 2 minus 1 is 1. so check uh index one so in the number at index one is now positive so multiply negative one and then minus C so move next again um index the one two three is already negative but uh we don't have to care about that because we always get the absolute value so -7 so i absolute value of minus value so -7 so i absolute value of minus value so -7 so i absolute value of minus seven is seven and the seven minus one is six so zero one two three four five six so six uh index six is positive numbers so multiply by negative one and then so minus three and then um next so 8 minus 1 is index 7 so 0 1 2 3 4 5 6 7 and then multiply negative one and minus one and then move next uh two minus one so index one so check the index one but uh the number is already negative so we don't do anything and then next so the number is already negative but uh obviously the value of negative three is three minus 1 and the index two so zero one two and then at index 2 the number is already negative so we don't do anything and then next minus one so I'm sorry the value is 1 minus one so in X 0 so check the index 0 and the four is a positive so multiply negative one so we get them negative four yeah and so this is a fast loop in the first Loop we change a lot of numbers to a negative number like a minus four minus three minus two minus seven and that means uh we could access the index number in the first Loop on the other hand there are a few positive values so index 0 1 2 3 4 index four and five so which means we couldn't access the index number so that this number uh must be a missing number in the range so we need to convert index number to real number so how can we do that so it's simple index plus one because uh index number usually starts from zero so let's say 0 1 2 3 4 so index four plus one is five so five is a one of a missing number in the range and index five so five plus one is six so six also one of our missing number in the range and uh um when do we need this calculation uh it's simple so current value is greater than zero so because uh um if we find the positive number that means we couldn't access the index number in the first Loop so that must be a missing number so yeah that's why we should return 5 and 6 in this case so that is a basic idea to solve this question without being said let's jump into the code okay so let's write some code as I explained earlier we use two loops and in the first loop I calculate the index number with each value and then the number at the index is greater than zero in that case we change the value to a negative number so for I in range and the length of input array and then calculate the index number so obvious and the current number -1 -1 -1 and then if the number at the index is greater than zero in the case um I change the number to negative number so index asterisk equal negative one so this is a first Loop and I create a result variable with empty array so this is a return variable so it is not counted as a like extra space so in the second Loop so in the first loop I convert real number to index number so in the second loop I convert index number to a real number if the value is greater than zero so for I in length and their legs of input array and then if current number is greater than zero in that case uh we don't have that index number so that should be one of the answers so less dot append oops plus Dot append and combat index number to their number so I Plus 1. yeah actually that's it so after that just return result variable yeah so let me submit it yeah looks good and the time complexity of this version should be order of n and the space complexity so follow-up description set this so follow-up description set this so follow-up description set this variable is not counted as a extra space so that's why we don't use our extra space yeah looks good so that means someone has a step-by-step so that means someone has a step-by-step so that means someone has a step-by-step algorithm this is a step-by-step algorithm of find this is a step-by-step algorithm of find this is a step-by-step algorithm of find all numbers disappeared in your array step one start the first Loop calculate index with each value and convert the number at the index to negative number step two start the second Loop if the value is greater than zero which means we don't have the index number so convert it to a real number with index Plus 1. yeah that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Find All Numbers Disappeared in an Array
|
find-all-numbers-disappeared-in-an-array
|
Given an array `nums` of `n` integers where `nums[i]` is in the range `[1, n]`, return _an array of all the integers in the range_ `[1, n]` _that do not appear in_ `nums`.
**Example 1:**
**Input:** nums = \[4,3,2,7,8,2,3,1\]
**Output:** \[5,6\]
**Example 2:**
**Input:** nums = \[1,1\]
**Output:** \[2\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `1 <= nums[i] <= n`
**Follow up:** Could you do it without extra space and in `O(n)` runtime? You may assume the returned list does not count as extra space.
|
This is a really easy problem if you decide to use additional memory. For those trying to write an initial solution using additional memory, think counters! However, the trick really is to not use any additional space than what is already available to use. Sometimes, multiple passes over the input array help find the solution. However, there's an interesting piece of information in this problem that makes it easy to re-use the input array itself for the solution. The problem specifies that the numbers in the array will be in the range [1, n] where n is the number of elements in the array. Can we use this information and modify the array in-place somehow to find what we need?
|
Array,Hash Table
|
Easy
|
41,442,2107,2305
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.