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,857 |
Hello everyone welcome tu d channel today chala ki ksi note01 connect hai zero tu se connect hai tu three se hai 347 and this gives us a string named colors what is its significance zero is the color of one note is zero index The color that is on the zero indicates the color of one note. The color that is that index of the first note. Force indicates the color of the note in which the number of notes in which the most of the D notes are in colors is from Okay, in the second example we have only one note life. That too and this graph is cyclic, if it is a cyclic graph then they have tu return minus one why did this let me explain this okay here is the graph 2 3 my tu and three both the notes have been colored blue so if I say 2 At 3:00, if I am caste, then tu ka color I say 2 At 3:00, if I am caste, then tu ka color I say 2 At 3:00, if I am caste, then tu ka color mera one hai, then a note was made whose colors is mine blue, the color of three is also blue, then I pressed one, I have the option, if I again say 2, then my Color is incremented again. Because it is color from, I am storing the same color value in the same variable because both of them are from color. If I had different colors, I would store it in a different way. I do OK now because there is a cycle here, my color is increasing so this thing will give us problem, we have the notes but I have the value of color 10 12 can go to infinity so if there is a cycle present in the graph S In D second test how then how is it not our valid test and give date how have they you return minus one OK this was the most important thing, the number one important thing was this question, if we see that the cycle is present then we have to check further. Don't have to do it if the cycle is not present, give them have, you can do it directly, what to do in that, I will go to all and check and store the maximum color in a variable, go to one and from that, all the people I want will be fast tomorrow. I will check all the parts present on you, I will go through all the possible parts of the fourth page and bring my answer. This will give us a lot of complexity. Second thing, what am I capable of doing? Its principle is this, it can be the first approach. Ok second approach, this is the suggestion, I came on the fourth, I am just ok, I am checking on this note, till now my color answer is only one note, comment, checked, my answer is done, its answer will be maximum one A, if I check this then I Let me check two notes, the answer to both of them is blue, so my answer is still blue and there are two notes with color blue, if I am checking this thing, but my answer is still you, if I check this thing. So right now I am checking the notes, my answer is three A's which is based on color, so one thing that I notice from here is that the bigger I take the lesson, first I set up small posters and checked five, the bigger one I checked five. I do this, either my answer will keep increasing or my answer will remain constant. When I was here, my answer was complete, you stayed here, he became free. Okay, so how will we get out? We are checking every note, what is his degree? Degree of zero Zero degree of one One because only R is the starting node Okay, I store zero in K I made the number of notes and these degrees and made my graph and now each one will traverse it on note whose Tomorrow, whose maximum color is OK, I am storing ours, we are storing those whose colors are the most, in our lesson whose colors are, OK, here we are traveling, we are taking out all the maximum colors, whatever we have and when Even the degree note will become zero, why will we push it in simple BF
|
Largest Color Value in a Directed Graph
|
largest-color-value-in-a-directed-graph
|
There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`.
You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the `ith` node in this graph (**0-indexed**). You are also given a 2D array `edges` where `edges[j] = [aj, bj]` indicates that there is a **directed edge** from node `aj` to node `bj`.
A valid **path** in the graph is a sequence of nodes `x1 -> x2 -> x3 -> ... -> xk` such that there is a directed edge from `xi` to `xi+1` for every `1 <= i < k`. The **color value** of the path is the number of nodes that are colored the **most frequently** occurring color along that path.
Return _the **largest color value** of any valid path in the given graph, or_ `-1` _if the graph contains a cycle_.
**Example 1:**
**Input:** colors = "abaca ", edges = \[\[0,1\],\[0,2\],\[2,3\],\[3,4\]\]
**Output:** 3
**Explanation:** The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored ` "a " (red in the above image)`.
**Example 2:**
**Input:** colors = "a ", edges = \[\[0,0\]\]
**Output:** -1
**Explanation:** There is a cycle from 0 to 0.
**Constraints:**
* `n == colors.length`
* `m == edges.length`
* `1 <= n <= 105`
* `0 <= m <= 105`
* `colors` consists of lowercase English letters.
* `0 <= aj, bj < n`
| null | null |
Hard
| null |
1,022 |
Allah universe hop ivygel Slime body Justice ribbon Challenge usamo frutteto fiber program cold mu de soda you talk to Adana old man Nuri's 4reasons arranged and normal bread Sena prot a How do you have a A7 Samsung Galaxy ziro One Zira the actor and the other of my father ziros oy lo lo o friend Nur from different places in the district big brother apricots shift ziro for This is a God for everything he creates my head casino ziro is there a chain ozerova Nokia cigarette alcohol rate no bear a b c this enaktar oo I'm fasting I was kissed Xero Van He us Smart Moving roasso game video NOS suddenly Because those dogs picture.and Then download Aysel There is nothing Windows is similar in all o
|
Sum of Root To Leaf Binary Numbers
|
unique-paths-iii
|
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_.
The test cases are generated so that the answer fits in a **32-bits** integer.
**Example 1:**
**Input:** root = \[1,0,1,0,1,0,1\]
**Output:** 22
**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
**Example 2:**
**Input:** root = \[0\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val` is `0` or `1`.
| null |
Array,Backtracking,Bit Manipulation,Matrix
|
Hard
|
37,63,212
|
334 |
Hello gas, so how are you guys about the question number 334 of welcome back, which is increasing triplet sequence, okay, yes, the question of midi is good, special like, it is good, honey is okay, you will get to learn either, the question will be fair easy, like in the beginning. It will seem complicated, then it will be done, then okay, let's see the integer items of a carenmi, I mean, you retain, true if, look at the true condition, when will it be? Basically, return tu means speaking, retaining, we are also getting to know from the function, now we need you retain. True if there exists triplet one any triplit exists with index jic science date i < j < k ok what does it mean date i < j < k ok what does it mean date i < j < k ok what does it mean if there is a triple plate then the value of the first triplet will be ok its index photo should be from the second one and the second one The index photo of the first one should be right from the third one, so this is something going on and the number of I <= these are the values of I <= these are the values of I <= these are the values from Let's X A S. Okay, so this is what is going on here and if there is no such word then What do we have to do, we have to retain simple false, then it is okay, now after reading the question, it seems okay and remember here it is written, not equal is not written, so if one people, then it is not our part of the answer, just give strictly less, check. If we look at the question then it seems that if we look at it from Han Bhai's point of view, then this is the first I which is fine and after he has fixed the first number, after that he has to find a prison which is bigger than I. He kept walking, he got this, okay, he got this one, now he will have to do another loop from back to find the one, brother, find one which is bigger than this, then let's keep going, did he see here, brother six? Pay ke got it right three for loop I got it for like these three conditions will be satisfied Han all three got the date mains apne ko tu return karna hai correct thing is absolutely right thing one this is the solution we are getting right and If we try it by court, then we will get it. It is okay, why will it be given, let's do something, this is completely fine, complexity is being created, right of N will be around when, which means when will the maximum of M go, it can be less than that, but it is okay because of the order. If it is going to be a resident, then this brother is giving a little problem, can we optimize it, let's focus on it a little, then if we look at the condition, its brother one, we want the smallest number, okay, brother, okay, so if I somehow After doing this, decide one minimum number of yours, it is okay here, decide one number here and just keep a bigger number than that on your friend, okay, after that, if I get another number which is going to be bigger, single, you can return. If you don't understand yet, do n't worry, don't worry, if we drive it a little more with a test case, it will be understood better, okay, just look here, what is happening in the test, Sapna 2150, okay, I took diesel, left name. Okay, I did it to the left, I initialized it with max infinity, I did the interior with max value, okay English list, after that I took a value from the middle variable, what to do with that too, I just gave it the maximum value possible, okay Maxwell Infinity. What are you talking about, let's start from here, okay, let's start editing from here to here, we came here and checked, we checked, sorry, it is doing a little bit wrong, I have to put this value inside the left, exactly. If this is correct then what will happen when I am here, what I have on the left will now become different from infinity, am I sorry, are these peppers small and equal, now will you say brother, it should be bigger than the left, if it is bigger than the left then it is okay. That's why in the else A is smaller than the left. If it is equal then this condition is fulfilled. Right, so we don't need to check this again. Okay, we have checked. If the Han way is smaller than the mid, then what do I have to do? Mid Storing the number in is the right thing, it is absolutely right and when the name of Mr. is cleared, then what will happen, see the index, I was here, I came from here and stored it without taking left, it is okay, in your place, the condition is still fulfilled, one and five. Now I just have to find the number that is bigger than the middle. All is well, so I go next to it, zero, is the zero smaller than the one on my left, is it smaller, is it van, is it zero, okay, exactly after that We check that. Index Next, what is four, which is okay, four is smaller than my mid, basically we have to check, okay, so what is my right now? Is it smaller than mid or not is not smaller than chilli so that means we are in the last cells condition and look at this when we are getting a value bigger than left and mid, something is ok which is six so it is like that so our trips should be Has gone zero four and six date mains returns true to us then what will we do here return you and if this condition ever comes and we will return false it is the right thing exactly like this there is a small question this will help now there is a doubt a Maybe you are right here and you index is here so your left becomes zero, this is the place of how did this happen and until the left is not ours then it will become the middle otherwise then the left can have any value if there is this one. Mid there is an mid existing which will definitely do so what is it in the case, what does the case mean that brother we have something smaller than this exists for the left whose index is less okay so that's why we are so worried about it. It will not happen because that condition is already being fulfilled. The update was done just so that if there is any other possible answer then it can be found because look, 156 but 046 is also the answer. Okay, so what did we do? We updated it to find the possible answer. If you go, then it is a simple code, once you go and code it quickly, then namshotland, first of all, I reduce these, make end equals tu length for length, it is correct, it is absolutely correct, is n't it the update which is there, it is updated only then. For every new value, we are not accessing the old value, so sometimes we do not need the index foreign type 0 i <. Now for the case of direct and not need the index foreign type 0 i <. Now for the case of direct and not need the index foreign type 0 i <. Now for the case of direct and goose fold, if instead of you, use the old method, basically There is no problem with the index, then it is fine, if you give equal, if you are left then what to do, I have to complete the left. If you have seen, if you have any doubt, then ask me in the comment. Medically, basically, what is the index? In the same way, the smallest is the middle and the one is bigger than that. And finally we got the biggest index so I what to do here return because I found an answer right if it is not there its time complexity will be write and space complexity we are taking two constants so space complexity will be your off van so I will also write it here by commenting at the end C Plus
|
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
|
151 |
hey everybody this is Larry this is day 12 of delete code daily challenge hit the like button oh no extra points hit the like button hit the Subscribe button join me on Discord let me know what you think about today's contest or today's problem matter um reverse words on it reverse words on a string um I'm gonna take a two second kind of to um you know celebrate victories if you are part of my Discord Channel you know one thing that I always try to Advocate is that you know you've worked hard maybe and you know sometimes it's okay to celebrate once in a while as long as you do it with you know you're with um you know but the joy and stuff like this right and that you know whatever right with the joy that you have for whatever that you're working on and today earlier today at least for me is earlier today depending on your time zone may be a little different I finished 11 but honestly a little bit sad there because I had a silly mistake that prevented me from being fourth but still um I feel like I haven't been this high in a couple of months so definitely um you know celebrating that anyway today's problem is reverse words on inner string so it seems like I would do another problem after this so definitely hit the Subscribe button and do that prompt with me as well if you feel like this poem is too silly to do um okay so let's kind of get started um I mean I don't know that there's anything cute about it you could do it in a number of ways I don't even know anymore uh I actually don't know how to attend those the double uh double duplicate like empty spaces so let's kind of see how it here that's what I'm doing here okay so it does actually um have all these things so yeah so we just have to um so I guess we have to do some trimming right is it called Trim in Python I don't know there is like a r strip maybe that's what I'm thinking of yeah I do mean script thanks that's actually a pretty good uh helpful ever message okay so the sky is blue well okay that looks what I expected okay so then now all we have to do is of course reverse this right so reversed and then we just return this join back in and I meant this as a space and yeah that's pretty much it I think assuming this is right oh it is not right oh I see hmm I want to do something like um but I don't know that this um I don't know if that um whoops but I don't know that once all the time so I've had to say I mean we can also just oh yeah so it only does two so it doesn't um keep going um is there let me see python regex does it owe you that's up okay fine um okay fine uh pattern replacement string okay so pattern is just um replacement string right something like that all right so that looks good let's give a submit okay cool uh yeah so this is going to be linear time linear space how did I did before hmm I don't get it why does this work did I change the problem did they change the problem or something like how did like this wouldn't work now right am I misunderstanding some parts that's why I did it some like crazy way huh what did I do wait why did I make it so complicated this time foreign that's interesting I did not know I didn't know that if you put a space was just a sprit it handles it differently I thought it just it's the same today I learned I guess but yeah but still nonetheless uh let's look back at this one nonetheless this is going to be linear time linear space um everything is linear this is linear um this is linear and the reversal is linear the split is linear the join is linear everything's linear so linear time linear space um if string data type is mutable and your language changes up in place of all one extra space um probably it's just way like hmm which I don't know I mean it's just very annoying to be careful about of like where everything goes I mean you know like it's just a lot of keeping track where like for example swiping the brew and the dirt you have to make sure that the dirt is here um so I put these two and then you kind of keep going left and right and stuff like that and it's a mess but durable I suppose um I don't know um that's all I have for today for this particular problem I'm going to do an extra problem after this so stay tuned um and hit the Subscribe button hit the Bell or whatever I'll see you soon stay good stay healthy to good mental health I'll see you later and take care bye
|
Reverse Words in a String
|
reverse-words-in-a-string
|
Given an input string `s`, reverse the order of the **words**.
A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space.
Return _a string of the words in reverse order concatenated by a single space._
**Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
**Example 1:**
**Input:** s = "the sky is blue "
**Output:** "blue is sky the "
**Example 2:**
**Input:** s = " hello world "
**Output:** "world hello "
**Explanation:** Your reversed string should not contain leading or trailing spaces.
**Example 3:**
**Input:** s = "a good example "
**Output:** "example good a "
**Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string.
**Constraints:**
* `1 <= s.length <= 104`
* `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`.
* There is **at least one** word in `s`.
**Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
| null |
Two Pointers,String
|
Medium
|
186
|
43 |
hello everyone today we are going to solve read code problem 43 which is multiply strings so in this problem here we have been given two integers uh number one and number two which in which both are strings and we need to convert them to we need to multiply them and we need to return them back as a string so and also in the note they have written that we should not be using any begin library to directly convert and number from integer to string so while i was solving this problem i uh i did uh did this problem with when i was working with integer i faced an issue with log with the variables which were uh which were having a precision of long so i tried it out with long and then i reached to a test case up to 1 118 out of 301 i guess so then when i converted it to big decimal since i did not have to use any of the inbuilt function i had to find out which how i can convert it and once i was able to convert it and then when i did the multiplication i was able to pass all the test case scenario so let me just go ahead and walk you through the implementation that i have written the implementation here is like i take the first number i get the big decimal in implementary uh equivalent the way that i do it is i pass the stream number uh as a string to the function okay i and i initialize the first uh the integer equivalent to be zero okay then i look through the entire string i pick one digit or one string character at a time or let's see if i pick this one let's say so like if the input is two over here so initially the integer equivalent would be in our case zero okay and then it will go digit will be number of 0.2 character array will be number of 0.2 character array will be number of 0.2 character array would have an character array of a single instance of two so we'll first do a integer equivalent which will be integer equivalent dot b into 10 so this will be 0 into 10 okay so it should be 0 then we will do integer equivalent so we'll add it so digit minus of 0 would give you the integer equivalent of that particular number so here it will be a string of two minus of direct special character 0 would give you nothing but 2 so if you do the math you will get 2 so that is what is the required output that we want and that is what will return it back to the following function same thing will happen with three and then we'll be then we it's basically like two multiplied by three which is six so we get the answer six and then we do 6.2 string we convert that 6 to 6.2 string we convert that 6 to 6.2 string we convert that 6 to string here they haven't mentioned anything about converting back to like not using any build function so i just use the big decimal dot 2 in our two string so that's how i get the answer over here so if i just comment it out i and when i run the code here so this was the last input that i was facing issues where i had started using a long and since this length was this uh argument length is greater than what the long precision is that's where i decided to use big decimal so because i knew that big decimal is a way in java to handle large inputs uh with more precision so that is why i started using big decimal in this particular problem so if we submit this particular code it will pass all the test cases and we will be able to serve we see all the test cases are passed and we solve this particular problem thank you very much have a wonderful days guys that's all for today
|
Multiply Strings
|
multiply-strings
|
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string.
**Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly.
**Example 1:**
**Input:** num1 = "2", num2 = "3"
**Output:** "6"
**Example 2:**
**Input:** num1 = "123", num2 = "456"
**Output:** "56088"
**Constraints:**
* `1 <= num1.length, num2.length <= 200`
* `num1` and `num2` consist of digits only.
* Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
| null |
Math,String,Simulation
|
Medium
|
2,66,67,415
|
378 |
um hello so today we are going to do this problem which is part of august theory challenge um so k smallest element in a sorted matrix the problem says we have an n by n matrix um and each of the rows and columns is sorted in ascending order right and we what we want is to return the kth smallest element in the matrix and by sorted order here it means um not the kth distinct so we may have equal numbers and we will want to return let's say for example even in this example here we have two 13s um and the eighth smallest including this 13 here is this value right we have 3 6 7 this one is the eighth okay so that's what the problem asks us to do um and here if k equal to one we want the first smallest number right um and so we are guaranteed that the rows separately and the columns separately are in sort of the order so you can see this row is in sorted order this one too and then if you take a look at the columns we have 1 first 10 12 so that's sorted and then we have as well 5 11 13 sorted and then 9 13 15 sorted as well right so the columns are sorted separately and the rows now how can we solve this um the easiest way to think about it is definitely there are like some really easy solutions you could just um create one list out of um this entire matrix so just concatenate each row so you'd have um 1 5 9 10 11 13 so you can cut any of these but they won't be in sorted order so you sort the array and then um just get the element at position k or k minus one right um a k minus 1 actually but um but that's o of n log n as where n is the size of the entire matrix so it's actually o of rc log of rc right so it's uh if the size of the row in the column is n so n squared then it's um oven squared log in uh actually oven squared lug n squared right and so that's not better than open square that we are asked to do here so that's not good the other solution um is just to take a heap right because the heap allows us to easily get the keith's smallest element and just put all of the elements in the heap right all of the elements of the matrix and then at the end just return the key smallest and so that would be something like this so i could just quickly go over it so it's something like this right where we go through the matrix each row each value in the row push it in the heap and then return the smallest right um so this is also oven squared at least right not counting even getting the smallest element um so that's not better than open square um yeah so that's those are the simplest solutions so how can we do a better one well it's sorted the rows are sorted and the columns are sorted so this hence to use binary search right we just need to do it in a clever way so let's see how we can apply binary search to solve it okay so let's see how we can solve it with binary search so what we need to find with binary search is a monotonically increasing or decreasing function what that would mean is basically we need to find um a function that has a pattern where once it's it starts out as for it we have one of two options so either it starts out as false and then once it becomes that function becomes true as the mid value increases um it will continue to be true so this is monotonically you can say um increasing or whatever the second option is it starts out as true and then once it becomes false it will continue to be false it won't change and with our binary search what we are looking for in this case is either the first true or the last false or the last true or the last false depending on the function that we want so we need to think about what function will give us this and here we are looking for the kth smallest element right what does it mean to be the kth smallest element well the kth smallest element means we have k minus 1 elements smaller than it right that's what it means by definition okay so what this would mean is that without function what we can do is actually just um find so what we can do here is actually just uh find the count for of the element smaller than some x that can be our function okay so we can start out with and check if that's um bigger or equal to k right because once you have an element let's say um let's say two let's say maybe i don't know seven has and our k is equal to three has three elements smaller than it in the matrix then if we increase it to eight by definition eight will have at least three elements smaller than it in the matrix it maybe have more but at least that because seven has three elements smaller than it if we increase to nine same thing right and so at least we know here it has this pattern once it becomes true it will keep being true the other aspect is let's say k is still equal to 3 and maybe 5 has two elements smaller than in the matrix then by definition element smaller than five plus a four has um at most two elements smaller than it can't have more because if that's the case then five has more than two elements smaller than it and same thing with 3 it has at most 12 smaller than so either 2 or 1 or 0 right and so this is smaller than our k right so that means this is false so we know also if it's false then for the elements smaller than the number for which is false it is it will keep as we go down it will keep being false so with the function count smaller bigger or equal to k here we will have this pattern in one here okay and so we could actually apply binary search with this now are we looking for the first false or the last true sorry for the last false or the first true so we are looking for the first one that has exactly k elements that has k elements smaller than it so we are actually looking for the first true okay um okay so we want the last true now we need an invariant with binary search to not make out of index out of boundary errors we need some invariance so with binary search we'll need to maintain low and high okay and in our uh this way of doing binary search we need to maintain an invariant that either low is always true and high is always false or the reverse low is always false and high is always true right and so since we are doing this a low it has to be smaller we will maintain that low is always false and high always true so we'll maintain this pattern so what this would mean is that at the end we need f to be low to be here and high to be here that way you can just return high as our solution okay and so with this would mean basically if f and true and this is low and this is high it means with our binary search high minus low needs to be bigger than one okay so that the gap is just one so that's just for the while loop condition and once it's equal to one that means we are at the end we reached this okay because remember our invariant is that low the function f so this is f of x is always false and for high it's always true okay so that's the first thing um so the other consideration is how do we know where to move low and high so let's grab this here and figure that out so let's say our um let's say our low was here so it's false and maybe our high heel is here um yeah this is these are the mid values by the way these are the mid values for these low and high and this is the f of x function okay which is the count smaller than x um so it's smaller or equal here i would say by the way because it may have equal values um and okay so now here um let's say we found that if f of x is false right which means basically smaller than k that means our low we are here our low is here that means sorry our mid is somewhere here in one of the false values so maybe let's add another false so what should we do should we move it to the should we move low or right and should we where should we move it so if mid is false um what we are looking for mid is the first true right so what this would mean is that we need to advance our low to have a chance of our mid being in a true value but we'll need to maintain that low is false right so if f of x is false what would we what this would mean is that we need to assign to uh low the value of mid because we know mid is false so maintain the invariant that low is always false and at the same time we advan we will advance mid because we advance it low so that we have a chance of reaching the first true right now what if f of x is true which is um the case we have which is the bigger or equal to k so that means our mid is somewhere here right so we want to get the first row so maybe our mid was is the first troop and we don't know right and so to maintain that we need to just make our high be at the volume mid we will maintain the invariant that high is always true and at the same time we'll have a chance because we will push high to mid to reach the first true right where the difference between low and high would be just one right so this would mean our high was be equal to mid okay and what's good in this pattern is that you don't need to think about okay should we do mid plus one should we do for low should we do for high mid plus one or the reverse should we do mid minus one this makes it really easy each of them would be equal to mid with this pattern and also with knowing the invariant that low is always false and high is always true that will help us pick the boundaries um basically what should be the initial low and what should be the initial high so let's think about that so we know low needs to always be false how do we make it false we want the kth smallest element so to ensure low is false regardless of k let's just make it not even in the matrix right that way we will guarantee it's false so we can just pick the smallest element in the array in the matrix which is the element at zero minus one that way we guarantee that so this is the initial values that way we guarantee that this invariant of always false is valid now what about our high we want height to be true so we want the smallest bigger or equal to k smaller number so we can guarantee that uh by just picking an element outside of the matrix because that would be the greater than all of them so it would have this condition valid and so because we want to keep this invariant and we want the such space to be in the matrix right and so we could pick this to be the last element which is the highest and just add one right so with this invariant this also helps us pick the initial values okay and now i think we have everything to do our binary sprint main binary search we know what would be our while loop condition we know the invariance we are going with we know when the function is true what should we do and when it's false what should we do right so the only remaining thing is how do we calculate the smaller than or equal x in an efficient way let's see that let's see how um okay so now how do we find the count for the elements smaller or equal than x the easiest way to do this is actually to utilize the fact that rows are sorted and columns are sorted so what we can do is we know the bigger element in the row is the last one right so we can start from the last one for the first row okay but say our x is equal uh is equal to eight we want to know if it has and k equal to three we want to know if it has we want to know how many elements are smaller than eight okay so we start with nine we check if 9 is so we check if the element at that row in column so we start with row equal to 0 and column equal to the last one which is 0 1 2 which is 2. so we check if that element is smaller or equal to um 2k 2x which is 8. is it smaller or equal to 8 no this is false so what should we do um so it's bigger that means if we go left we would have a chance of finding smaller elements right so if we move our pointer here we'll have a chance of finding elements smaller than or equal to eight so what does this mean basically is doing column minus one now five is small or equal to eight so how what can we deduct how many elements are smaller than eight in this case are smaller than x in this case well since this is the larger element the then all of those to the left of it we know that how many are to the left of five including five are smaller than um eight right so we can just increase the overall count of the elements smaller or equal to x by everything to the left including the element and this is column so and this here equal to one and we know it's two so it's column plus one right it's everything here is the value column and this is because we are starting an index from zero so we can just add column plus one to our count okay so all of these to the here if we have something like two three four five nine so the indices are zero one two three four five right so all those small it's everything here and this column four because the index is zero these are five elements right and so this is column so it's column plus one that's why you add column plus one okay so that's the first thing now what if it's so now once we find five we want to find how many other elements are smaller so we go to the next row right so we check 11. is 11 smaller equal to 8 no so we go to 10 it stands we go to column minus 1 is 10 smaller or equal to 8 no so we go to -1 right or equal to 8 no so we go to -1 right or equal to 8 no so we go to -1 right and now -1 is not a valid column anymore and now -1 is not a valid column anymore and now -1 is not a valid column anymore so our while loop that keeps doing this needs to have the condition that column bigger or equal to 0. the other thing is that once we are done with a row and counted it the element smaller than or equal to k you saw what i did here which is go to the next row right so basically what this would mean is if the element at row column is smaller equal to x what did we do we increased the count right so we increase the count but we also go to the next row because we already counted how many smaller are in this row so we go to the next row but if it's bigger right which is what i did here when we were at nine we saw that it's bigger and we know that to find elements smaller we need to go to the left so we decrease the column so otherwise we decrease column okay now one thing you would say okay if we decrease column and end up going 11 to the bottom is that right like could 13 be smaller than x it can't because by definition columns are sorted so 9 is if 9 is bigger than x then by definition 13 is bigger than x so going decreasing column minus 1 is the correct thing to do because we will never find an element smaller equal than x in this column right so that's the main idea here we can just do a while loop and decide to go left or right depending on the values we have okay um yeah i think that's pretty much it so now we know how to calculate the counts more than or equal and we know how to do our binary search so let's just code this solution um okay so let's write the function that we just saw in the overview so we know that we need to do binary search first right so we need um the values of the number of rows um i'll just make this m to make this easier to write and m of 0 right and now we need our low and high and as we said we want low to maintain the invariant to always be false so to ensure that we will pick the smallest element in the matrix and do minus one and no matter what's the k value this will make um our function on low be false which is how many elements smaller than or equal to x are the count of the numbers more or equal to uh to the value is bigger or equal to k and then for high we need to go outside the bound to guarantee that we have it true so we would go to take the higher element in the matrix so this can be r minus 1 c minus 1 which is just this in python plus 1 for high so we maintain the invariant low the function is always false for high it's always true and for our binary search our while loop we want to maintain as long as the gap is bigger than one which means we are not at what we said in the overview which is we are not at so we are done when low is here and high is here so the gap is just uh one okay so that's why we continue as long as the gap is bigger than one and now we calculate our mid and the way to calculate it to avoid overflow is just do low plus high divided by two so we can do that with this shift one um and now we check if our function which is count smaller or equal than for mid if that's bigger or equal to k right which means this is true so we are in some of the true values we need our mid to be just we need our height to be just equal to that because maybe we are here um and so we want height to be equal to mid and for the else which means that our function is false so we want to maintain that low is at false so we just but we want to get closer to the last false so you set to low to mid so we do that it's at low to mid okay and then at the end we want to return the first shoe which is high right because the gap is just one that means the first true is this high value here so return high okay and now we need to define this function and we just get a target value and as we said we will initialize row pointer and column pointers or always start with the first row and column with the end of the first row and so that would be column minus one the number of columns minus one right and we want a count that counts the overall number that we will return at the end and we will keep searching while row is not past the last one so we haven't explored all the rows so smaller than number of rows that we have here and column is positive right if we go past the first element in the row so the first column then we are done right and now we will check if error so this is r actually rc is small or equal to target right that means we found the first element in the row going from the right that is smaller than our x so let's actually call this x that is smaller or equal to our x so we need to count and it's everything to the left of that including the element and so we increment by column plus one because we are start the index from zero in the row and then we advance to the next row to check if we find anything smaller or equal to x otherwise it's bigger than x right so there is no chance to find anything smaller than it in the same column so we just decrease the column and we leave the row because we want to still see if we find something smaller or equal than x um and that's pretty much it so we can run this so this is actually c and this is r and this is c as well sorry okay and let's submit okay and that passes test cases now this is the function here is of n log n and that's just the um the overall uh matrix right um of like n sorry of like n squared that's the size of the matrix um and then since it's a square matrix and then here um this we will do um we will do at most i think um we'll do i think at most k right um so yeah it's definitely faster than oven squared um yeah so that i think that's pretty much it for this problem um please like and subscribe and see you on the next one bye
|
Kth Smallest Element in a Sorted Matrix
|
kth-smallest-element-in-a-sorted-matrix
|
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_.
Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element.
You must find a solution with a memory complexity better than `O(n2)`.
**Example 1:**
**Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8
**Output:** 13
**Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13
**Example 2:**
**Input:** matrix = \[\[-5\]\], k = 1
**Output:** -5
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**.
* `1 <= k <= n2`
**Follow up:**
* Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)?
* Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.
| null |
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Medium
|
373,668,719,802
|
415 |
okay let's talk about add string so you're given two string in nums one and nums two right and you're adding and you're going to return the sum of them so you're not allowed to convert to integer and let's talk about the idea so i'm going to start from the back and then to the front and when i you put a carry to the character from if there is and then we just don't care about it so let's just follow along so i will be the nums one index and j will be nums to index and i'm putting in stream builder so i equal to zero or j greater equal to zero and i say digit four num1 would become so i'm going to say if i check i could equal to 0 that means this is the value is character so i'm going to number one the choice i and minus the chart so that would become the integer right so that would be the integer value then i'm going to say else zero so that would be the digits one and they just two will become the same idea j equals equal to zero and then it's a valid string and i'm going to delete i mean subtract the zero because the ascii okay now i'm going to add it right so i'm saying 2 digit nums 1 plus digits num 2. so you have to be careful the carrier right so i'm going to put a carry to uh out of the loop and then plus i carry even though the carrier is zero right now and then carry will equal to sum divided by 10 and that will be it so i choose a pen well we'll show the pen i append the sum mod 10 right and then because this carrier will carry on the next following loop so what i did i subtract the i and subtract the tree and break out the loop so the only thing i have to check is if there's a carrier left because i and j will definitely less than zero when you break out right so if carry is greater than zero then sp dot pan our pin one and then i just have to return so imagine you know i open one so i open to the last one right but it's actually reversed because you think about three plus one is four right so the first character is four and then and the second character will be three and then two right so it's uh so uh wait so it's one sorry and then so you are going to reverse the string so that will give you the correct curve integer so when you rever and then reverse and then you are just type 2 string and you convert to string and talk about it let's talk about it okay it's pretty good cool okay let's talk about time and space so you definitely do through every single character right but you are doing at the same time so it's going to be all of that max so it's going to be the end of the then the file length of j right it is depending on which one is greater and the space is all the one you're not actually using so just don't forget you have to use a reverse function so you can try this example by your own but just make sure you reverse and that will be it peace
|
Add Strings
|
add-strings
|
Given two non-negative integers, `num1` and `num2` represented as string, return _the sum of_ `num1` _and_ `num2` _as a string_.
You must solve the problem without using any built-in library for handling large integers (such as `BigInteger`). You must also not convert the inputs to integers directly.
**Example 1:**
**Input:** num1 = "11 ", num2 = "123 "
**Output:** "134 "
**Example 2:**
**Input:** num1 = "456 ", num2 = "77 "
**Output:** "533 "
**Example 3:**
**Input:** num1 = "0 ", num2 = "0 "
**Output:** "0 "
**Constraints:**
* `1 <= num1.length, num2.length <= 104`
* `num1` and `num2` consist of only digits.
* `num1` and `num2` don't have any leading zeros except for the zero itself.
| null |
Math,String,Simulation
|
Easy
|
2,43,1031
|
1,963 |
hello everyone this is the lead code problem minimum number of swaps to make the string balanced you're given the strain of even length the string consists of exactly half opening brackets and half closing brackets a string is called balanced if and only if it is the empty string or it can be written as a b where both a and b are balanced strings or it can be written as c in a bracket where c is a balanced string you may swap the brackets at any two indices at any number of times return the minimum number of swaps to make the string balanced let's take a look at some examples example 1 we can make the string balanced by swiping index 0 with index 3. the answer is 1. example 2 we can swap index 0 and 5 then index 2 and 3 or swap index 0 and 5 then index 1 and 4. both resulting strings are balanced the answer is 2. in the example 3 the given string is already balanced no need to swap anything so the answer is zero so how to solve this problem suppose we're given these strains inside the string if some parts are balanced there's no need to swap ignore the balanced part everyone problem end up like this pattern the optimal swap is to balance two sets of brackets instead of one using one swap so for example one there are five sets of brackets we can make them balanced by three swaps for example two there are two sets of brackets we can make them balanced by one swap for example three there's one set of brackets we can make them balanced by one swap for the last example no need to swap at all the answer is zero let's take a look at the code go through the string character by character unbalanced represent the number of opening brackets that doesn't have a match yet if the current character is the opening bracket then unbalance the increment by 1. if the current character is the closing bracket and there are opening brackets waiting for the match then we find the balanced string increment the number of unbalanced by one this formula is the number of minimum swap thank you for watching you
|
Minimum Number of Swaps to Make the String Balanced
|
find-xor-sum-of-all-pairs-bitwise-and
|
You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** strings, or
* It can be written as `[C]`, where `C` is a **balanced** string.
You may swap the brackets at **any** two indices **any** number of times.
Return _the **minimum** number of swaps to make_ `s` _**balanced**_.
**Example 1:**
**Input:** s = "\]\[\]\[ "
**Output:** 1
**Explanation:** You can make the string balanced by swapping index 0 with index 3.
The resulting string is "\[\[\]\] ".
**Example 2:**
**Input:** s = "\]\]\]\[\[\[ "
**Output:** 2
**Explanation:** You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "\[\]\]\[\]\[ ".
- Swap index 1 with index 5. s = "\[\[\]\[\]\] ".
The resulting string is "\[\[\]\[\]\] ".
**Example 3:**
**Input:** s = "\[\] "
**Output:** 0
**Explanation:** The string is already balanced.
**Constraints:**
* `n == s.length`
* `2 <= n <= 106`
* `n` is even.
* `s[i]` is either `'['` or `']'`.
* The number of opening brackets `'['` equals `n / 2`, and the number of closing brackets `']'` equals `n / 2`.
|
Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum.
|
Array,Math,Bit Manipulation
|
Hard
| null |
368 |
today we're gonna be working on read code question number 368 largest divisible subset okay given a set of testing positive integers nums are written the largest and a subset answer such that every pair answer of i and answer of j of elements in this subset satisfies this condition where one module modulus of another is gonna be equal to zero so there are multiple solutions written in any one any of them so in one two three we're gonna be returning one and two because one divisible by two is equal to sorry two divisible by one it's gonna be uh modulus one is gonna be equal to zero one and three also satisfies and this one everything is gonna be in because two modulus one uh four modulus two eight modulus four and they all are like uh like potential solutions so in this case what we're going to be doing is basically we're going to be using the depth first search and the depth first search so in other words we're going to be doing the recurring and also the memoization so that we have and the kind of motivation is going to be like the for every index we're going to have some set of values and those values are gonna be basically that if we were at that index these are gonna be the solutions so we're gonna have a map for that so for every uh for every integer we're gonna have a list of integers let's call it mem for memorization and we're gonna have it as a new hash map okay then we're gonna have a helper function too which is gonna basically uh we're gonna be using that and in this one we're gonna be sorting the array because we wanna see them see in a sequence so it is dot sort nums and then we're gonna be calling our return function with we're gonna initialize it with a zeroth index so our helper function is basically gonna be returning the list of integers and it takes an end and it and like what it takes is the numbs let's just call it nums and then end i is gonna be the index so we know if we already have processed it we're going to be returning the result so if the mem dot contains k i we're going to be returning the value uh return mem dot get i okay otherwise if we haven't processed it before now we're gonna be creating a new list uh integer max length uh list so it's a maximum length less like what can be the multiples of that particular number uh which are already in the array so that is basically the gist of the logic here that we are actually checking the multiples of everything so if we have two we're gonna be checking for eight uh ten all of them um because inside the array and if we have already processed our duplication we're gonna be actually using the memoization in order to get the pre-processed results okay and the first time we're gonna be uh we're gonna be seeing is like the first time when the i is basically this index is equal to zero uh what we're going to be seeing the thing the multiples we're gonna be looking for is one so that every number can actually have at least like looking for itself to at the beginning so the div is going to be equal to 1 otherwise it's going to be equal to that nums of i minus 1. okay now our loop is gonna go through and uh k is gonna start from i right and then it's gonna go k is less than uh nums.length and then k plus okay so if we're gonna check our condition if that numbs of k modulus uh of that div is equal to zero we're gonna process it and in processing oh first of all we wanna see if we already have the uh first of all we don't want to take the same uh list we wanna make a copy of it right so for that we'll say list of integer uh list yeah and that is going to be equal to a new array list and we're going to make sure that if we have nums and the k plus 1. so we want to make use of memorization and we want to make a copy of it so that we can actually process on the new one and then we're going to add this current number list dot add nums of okay and then uh the last thing is that we have this max then we want to update it only if the size of that list we just created or got it from the helper function uh if their size has been greater than the this size then we're gonna uh do we're gonna update it let's start size is greater than max length less dot size in that case we're gonna say that the max length nest is just equal to this list okay once we come out of this for loop we're gonna update our uh memoization array memorization map and then we're gonna return that uh the result so mem dot part uh for this particular index i uh we're gonna say that this is gonna be the max length list and then we're gonna be returning max length list looking good yep and it works
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
78 |
in this problem we will see a very mathematical uh problem it's called finding the power set of a given set so what is meant by power set uh it means that if you are given a set of some numbers then you have to find all possible subsets that can be created from the elements of the given set and the set of all those subsets is called power set and the number of elements in the power set or number of subsets in the power set will be 2 raised to the power n if n is the number of elements in original set so we will see it recursively as well as iterative solution and then i will give another solution using bit masking so first let's understand what is a power set so we are given a set let's call it s and it has three elements so what are different possibilities either we pick first element or not so either we pick it or we don't pick it similarly for three so let's take one of the paths we don't pick this one so we get an empty set then we pick this one so pick true of this false of this so we get one so any possibility you can find let's say we want to form two three so here we took this path here we took false that is we did not pick one true so there can be two possibilities for one two possibilities for two and two possibilities for three so in total there are two cross two that is 2 raised to the power 3 possible combinations or 8 combinations so let's list them so when we don't pick anything this is empty set when we pick one of the elements then it can be one two or three then we pick two elements then we get one three one two and 2 3 when we pick all of the 3 we get 1 2 and 3. so these are all the possibilities and if you count it 1 2 3 4 5 6 7 8. so that comes out to be it as expected so this is the meaning of power set so the power set will be the set of all these subsets so you this see this extra bracket for set so it includes all the subsets of this is power set it's also denoted by p of s if s is the original set so uh we will solve it how we will solve it let's see so let's say first let's look at the recursive solution so we want to break this bigger problem into smaller problem so how can we solve it recursively let's say we know the solution for uh so we have to calculate the solution for one two and three so we break in into uh one we keep out and two three is the smaller problem so just take the first element out and solve for this again take the first element out and solve for this three now the solution for three is uh we know that the solution for three will be this empty set and 3 itself so this is returned back here so what we will do in the calling function so whatever is the solution for the original the smaller problem we will pick all the elements of that power set keep them as it is and add two to them all of them and append here so this remains as it is we are not removing them but what we are doing we are picking them one by one so first we pick this add 2 to it so it becomes 2 then we pick 3 and add 2 to it so it becomes 2 3 and this is the solution for this part 2 3 so this is returned back here so what it will do it will keep all of them as it is that is 3 2 3 and additionally it will take all of them and add one to it the first element so we will have one if one is added here it will become one three if one is added here it will become one two and if one is added here it will become one two 3 and this solution is returned up that is this solution and this was the original solution so there is it will return this value and it includes all the possibilities so what we are doing is we are solving for s 1 to n or if you are starting from 0 index it may be 0 to n minus 1 so the solution for this is a solution for that is f 2 to n solve for f 2 to n and in that solution take the union of the same thing f2 to n but append to it s 1 the first element so whatever is the solution keep it as it is and append to it uh the first element so that is a recursive way of solving it as the idea of iterative solution is very similar to this and the same concept in fact so what we will do here we will initialize our result to consisting of an empty set so this is initialized and what we will do we will iterate for all the elements of this given set this may appear to be easier to you so for n in s so we are looking for all elements of n s so what we do whatever is the existing result we append this end to that so result is empty so what it will do it will append to it so result equal to result union n plus the elements of result so what it will become so initially n is so first n is 1 so what it will do result is empty so take the result and append to it append to all the elements of this number n which is one so just one element so just this is appended when n becomes 2 that is we take the next value of n so this is for all the elements of this set what we do we take this result this is result we don't delete the existing ones we have to just keep appending values so what we will append take this one add 2 to it and this is the result when we have processed n equal to 2 finally the last number is 3 so n equal to 3 so keep it as it is we will not be copying we will be using a common result we will be just appending to that here i am writing it again and again for keeping it clean so this is the result now what is our job to iterate from first element till the last element of result and before iterating keep the size here because you will be inserting to that result only so it size will keep increasing so take the size beforehand so we have four elements so we will take first four elements of the result and add three to it and push it back so in this if we add three we get three in this we add three we get 1 3 in this we add 3 we get 2 3 and in this we add 3 we get 1 to 3 and now we have i traded for all the value of n in this set and this is the final result so you see it looks much more cleaner and much simpler but if you are able to solve this recursively then it would be a good practice for understanding the recursive concept finally let's see the third method which is using bit patterns so here we have three elements and we know that if we use three bits that is b 2 b 1 b 0 let's say these are 3 bits then using 3 bits we can form 8 numbers and what are those possibilities 0 1 and 1 0 and 1 two three four five six seven eight exactly same concept each bit can be either zero or one so there are total eight possibilities so these are the possible uh values for each of the bits this is exactly same thing we had seen these branches it can be true or false and that is 0 or 1 so 8 possibilities are there so you convert this you list down all the bits represented by this three digit number that is this is number one this is zero this is one two three till seven so if you have three elements then you know that it can represent eight possibilities are there so you iterate from zero to seven and whatever is the bit representation of this which will be this iterate through this characters so all of them are zeros so don't include anything then i will be one and in one you see that this character is one so what you will do you will pick this element at this index third one so it will be 3 then in this i equal to 2 we see that second bit is 1 so just second number then when i equal to 3 then these two are one so take these two that is two and three in this case this one is one so take this one here first and last are one so take first and last that is one and three in this element in this set then here these two are one so take one and two here all three are one so take all three one two three and you see this is also the power set so try solving it in c plus at least i know you can use bit set and you pass this number from 0 to 2 raised to the power n minus 1 and convert it to a string two string and then check which character r1 then pick those indices from this so let's let me solve the recursive and nitrative solution method one and two in c plus and later we will just continue with iterative solution in java and python so this is the problem i had taken the same example so if nums not size or num nums is empty then return this empty set should be there this null set should always be a subset so you cannot simply return this it should be this there would be one element otherwise we will create a vector for result this is the return type so first i am writing the recursive solution so let's call the recursive solution recursive function subsets rec and we will pass this nums and one index so initially it will be zero to last element and then recursively it will call from two to last index three to last index and so on so here we will pass in zero and let's pass result so result will be populated and finally we will return result and now we will define this function so if this is the last index that is there is only one element then we know the solution for this result dot push back this empty set and also there is just one element so push that element these are the two possibilities else we will call it recursively so this will recursively uh call smaller and smaller problem ultimately it reaches the end and then it will start returning and it's it will be inserting into this common result which we are passing by reference so now we will take the size so this recursive call has done it for all the smaller values then we iterate through all the values all the elements of this result and then append it to it the current element that is idx and then also insert it into the result and this matches the expected solution this ordering is not important in sets these can be in any order so let's submit and this solution is accepted now we will see the iterative solution so what is the time complexity here we will compare the times for recursive as well as iterative solutions so let's understand the time complexity first so what we are doing uh we are taking an empty list and appending to it one element then this size becomes 2 then in the next step what we are doing we have 2 and we are adding 2 to each of them so its size now becomes 4 then we are taking third element and adding 3 to all of these and pushing to the result so this is done four times this is done two times this is done one time so 1 times 2 raised to the power 0 plus or 2 times 2 raised to the power 1 plus 3 times 2 raised to the power 2 all the way up to n minus 1 times 2 raised to the power or n times 2 raised to the power n minus 1 so what is this sum let's call it s then this is let's write it 2s then what will be 2s uh if we multiply 2 to it will become 1 times 2 raised to the power 1 so let's write it here then if we multiply this by 2 it becomes 2 times 2 raised to the power 2 and so on and here it will be n minus 1 times 2 raised to the power n minus 1 so we have we are writing this same thing we are multiplying each term by 2 and we are writing one place to the right so this multiplied by 2 comes here and so on and this will go here so if we multiply 2 here it will be 2 n times 2 raised to the power n and now subtract this from this so it will be minus s this will be 2 raised to the power 0 this here powers are common and constants are a difference of 1 so this is 1 times 2 raised to the power 1 similarly here it will be 1 times 2 raised to the power 2. plus 2 raised to the power 3 and all the way up to 2 raised to the power n minus 1 and this is minus n times 2 raised to the power n so this is a geometric progression till here so let's take the opposite sign so s becomes n times 2 raised to the power n this term it becomes positive this becomes negative so what is the sum of this here first term is 1 it's 1 plus 2 plus 4 plus and there are in total n terms so a multiplied by a is 1 so 1 multiplied by common differ ratio is r which is 2 each is increasing in the factor of 2 so 2 raised to the power n minus 1 divided by 2 minus 1 that is 1 so what is this term n 2 n minus 2 n plus 1 so take 2 n common so n minus 1 2 n plus 1 so you can ignore this in time complexity analysis and this n minus 1 you can think of it as n so it's of the order of n times 2 raised to the power n so this is the time complexity and similarly the space complexity since uh we are storing 2 raised to the power n subsets are there so there is no way to get out of that you have to return a set of all those subsets and in between we are copying elements in a temporary variable and then copying to the original result so it's also of the same order now let's write the iterative solution so let's comment it out and let us initialize it to empty solution so just what we saw here we initialize with empty set then for all the elements of s we append to them this element it's very similar to in fact this logic and the solution also matches so let's submit and this solution is accepted and here it's much faster you can try a few times it can be zero millisecond as well now we will write it in java and python so and the java solution is also accepted finally we will do it in python and the python solution is also accepted
|
Subsets
|
subsets
|
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
* All the numbers of `nums` are **unique**.
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
90,320,800,2109,2170
|
264 |
Hello Everyone and Welcome Back to my Channel Algorithm Hq Today I am going to write the code and also explain to you all the algorithm to solve this next number two problem which is there in lead code it is a medium level problem and can be solved using A Priority Why and a Greedy Algorithm We are going to solve it using a Greedy Algorithm because it is a better approach and we can reduce the time. So let's start it by taking the name of Shri Krishna and we have to enter only one integer in it. Will be given n in input and we have to return th next number and what is the next number here whose prime factors will be only th or f, non prime factors can be any number, can be any but the prime factors are only th and There will be 5 that means 7 or 13 or 11 these should not be all the factors ok they have also listed an example here in which n = 10 so we have to return the 10th next number in which n = 10 so we have to return the 10th next number in which n = 10 so we have to return the 10th next number which is 12 ok so this is the whole series It has been told that what were the next numbers, before that there is no one, because the prime factor of one is none, nor is two, neither is three, nor is five, so there is none, in this it is okay, then two. The prime factor of Ka is only two. Three is only three. Four is two. It is three, it is 10, it is two, it is five but it is not going above five, it is the same for 12, so basically we are getting to know that the series which is being made was somewhere and 5. It is being formed by multiplying something by two, it will become four. Multiplying something by three, it will become six. By multiplying something by five, it will become 10. Basically, th is being formed by multiplication of 5, except for the first element. That is one, so we should not do this by simply taking th and 5 and then multiplying it with the numbers in this series, like if we did 2 in 2, we made 4, but by doing 2 * 7, we made 4, but by doing 2 * 7, we made 4, but by doing 2 * 7, we cannot make 14. Because the prime factor of 14 will be Sen and we cannot take Sen, so basically whatever number we have in this series, we are getting the next series only by multiplying it with th and 5. If we notice, then We do it simply by considering one as the first element and rest of the series we make it using Th and F. Okay, now they will make it, let them understand how, okay from this example, so basically first of all. We have th and 5 okay so we have to make the series in ascending order of course so the first element is one which is not a multiple of th and 5 but after that if we have th and f which is the first element. This is one, if we multiply it and we take the minimum from it, then we will get the second element, this is okay, then again, now we have the next element of the series, two, so again we have 2, 3 and 5. And basically the element that we have picked up, we will only multiply it by the next element. We are not coming here yet, okay, we are here now, basically the remaining elements are what are left, okay. And to put the element in the series, we have moved it forward and multiplied it with the next element, so first we multiplied it with one, all three are fine, then after that because we have picked two from here. So the next element we have is two, we have multiplied two by that, okay, so now we have considered these three elements, 2 * now we have considered these three elements, 2 * now we have considered these three elements, 2 * 2, 4, 3 and 5, which one among 4, 3 and 5 will we pick, three, okay now. Picked three. Now if we pick three, then by what will we multiply three, which is the second element of our series. Okay, why are we doing it from the second element only because by multiplying 235 from each element, we will see that we will fit it in the series. Can we do it or not? So we multiplied 3 by t. Now which elements do we have? In consideration, 2 * 2 In consideration, 2 * 2 In consideration, 2 * 2 is 4, 2 * 3 is 6 and 1 * 5 is 5. Okay, is 4, 2 * 3 is 6 and 1 * 5 is 5. Okay, is 4, 2 * 3 is 6 and 1 * 5 is 5. Okay, which of these three is the smallest? is 4, so we have taken four here, okay and moved it forward again. Now what will we multiply it by? We have already done two by two, so we will do it with the next element which is 3. Okay, now when this If we do 3 or 2, it will become 6. Okay, if we look here, there is six. Here too, there is six, okay, and here, F. Which is the smallest among these three? Okay, so here, F. Note down. And because till now this one was only multiplied by n, so we will multiply it by two, making 2 into 5. Okay, so now what elements do we have, one has come, 3 * 26, one has come, 2. * 36 and one has come, 3 * 26, one has come, 2. * 36 and one has come, 3 * 26, one has come, 2. * 36 and one more has come 2 * 5 one more has come 2 * 5 one more has come 2 * 5 Which is the minimum among all these? It is six again. Okay, if it is six, then six is available from here too. And if we are getting it from here also, then what will we do in this case? Okay, we will multiply two by four, because it was done by three earlier, and we will multiply three by three, because we did it by two, okay, we will take both of them forward and take one element from it. Which is six, okay now we have 4 * 2 8 then six, okay now we have 4 * 2 8 then six, okay now we have 4 * 2 8 then 3 * 3 9 and 2 * 5 10 So again from here we will 3 * 3 9 and 2 * 5 10 So again from here we will 3 * 3 9 and 2 * 5 10 So again from here we will consider 4 2 8 Okay 4 * 2 8 we will consider 4 2 8 Okay 4 * 2 8 we will consider 4 2 8 Okay 4 * 2 8 we will consider and take it forward and here We will write 5 * here We will write 5 * here We will write 5 * 2 ok which will be 10. On Aventura we will write 8 ok and now what are the elements we have 5 * 2 10 ok 3 * 3 9 and 2 5 again 10 so consider 3 10 ok 3 * 3 9 and 2 5 again 10 so consider 3 10 ok 3 * 3 9 and 2 5 again 10 so consider 3 9. And from here we will take it further and multiply it by four, okay by 3, now we have again 10, 5 in 2 is 10, 4 in 3 is 12 and then 2 in 5 is 10, so again here we will take down 10 notes. Because the smallest among these three is 10 and we will increase it further i.e. 6 in i.e. 6 in i.e. 6 in 2, we will make it 6 * 2, okay 4 * 3 will remain like this okay 4 * 3 will remain like this okay 4 * 3 will remain like this and we will bring 2 * 5 to 3 * 5 that and we will bring 2 * 5 to 3 * 5 that and we will bring 2 * 5 to 3 * 5 that is 5 by 3. We will multiply, now we have three elements 6 * 2 that is we have three elements 6 * 2 that is we have three elements 6 * 2 that is 12 then 4 * 3 that is again 12 and 3 * 5 12 then 4 * 3 that is again 12 and 3 * 5 12 then 4 * 3 that is again 12 and 3 * 5 that is 15 so from this we will take 12 which is minimum and again we will multiply these two 4 * 3 and 6 * 2 are fine, 4 * 3 and 6 * 2 are fine, 4 * 3 and 6 * 2 are fine, after that we do not need it because we have reached 10 and after doing this we return this 12 that is the 10th element which is present at the ninth index in the array. Okay, so by doing this we will make this complete series and the code will also be very simple and we will just code it, then we will quickly create an array with the next name, whose length will be A, okay and first on its zero element. From here we will put one, okay, because one is the first element, then we will take one, after that, we have to multiply the 3rd and 5th, only one i5, so basically these indexes will remain okay, which element of the array we have to multiply by. Those are indexes, okay then int f1 e 2 f2 sorry f2 = f2 sorry f2 = f2 sorry f2 = 2 f3 e 3 and then f5 = 5 ya aa means f3 e 3 and then f5 = 5 ya aa means f3 e 3 and then f5 = 5 ya aa means index so what does f mean f means factor okay factor 2 can be 3 or 5 also. That's why f2 f3 f5 has been taken so that it is more readable. A will always be smaller than n and will start from one because the first element which is at zeroth index is one, then we will find its minimum from these three. Math Dot Man Off again math dot mind off A2 and A3 and compare that to A5 okay then here if av e is equal to what we just found out the minimum next i tov will be carried forward av e 2 into next off plus i 2 okay. Why have we done this because we are maintaining different indexes for all three with the same index, first of all we multiplied it by one, then 2 came 35, then again which will be the second element two. What do we do to multiply it by that? We will first move i2 forward, so if plus is written then it will go to the first index. Okay, the first index will be present to two. And after that we will multiply it. f1 will not come. Sorry, here f2 will come and then f3 if it is equal to the next i. We will repeat this also as f3 it 3 into next i 3 i man plus aa3 and then the same for i5 and for f5 also we have to do the same, the array will become, by the time we come till a, n will be at the second position which The element is that which is the index. We will return that element. Let's run it and see. Here, sample test cases are being run. Let's submit. Expected here is 25 but the output is 27. Here is the code. Let's check what is the mistake and then put 'Thr', what is the mistake and then put 'Thr', what is the mistake and then put 'Thr', here five should come but by mistake I made it 'Three', now let's made it 'Three', now let's made it 'Three', now let's first run this test case and check that it is running and successfully submitted. Gaya Butt Jaane Se Vivek Please Don't Forget To Like The Video And Subscribe To My Channel If You Haven't Already Also Tell Me My Improvement Points In The Comment Section That's It For The Video Radhe
|
Ugly Number II
|
ugly-number-ii
|
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.
Given an integer `n`, return _the_ `nth` _**ugly number**_.
**Example 1:**
**Input:** n = 10
**Output:** 12
**Explanation:** \[1, 2, 3, 4, 5, 6, 8, 9, 10, 12\] is the sequence of the first 10 ugly numbers.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
**Constraints:**
* `1 <= n <= 1690`
|
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
|
Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
|
Medium
|
23,204,263,279,313,1307
|
31 |
hey everyone welcome back to the channel I hope you guys are doing extremely well so this is another video from the stripers A to Z DSA course just in case here for the first time here this is world's most in-depth course when it world's most in-depth course when it world's most in-depth course when it comes to DSL though why do I say that because this course has 456 modules by the end of the course you would have sold more than 400 plus problems when it comes to DS I'll go you can go across the entire internet you can buy any of the paid courses in the market none of them will be teaching you DSL go in such step one thing that I can give you as Assurance is if you complete this particular course you can hear any of the DS algorithms in any of the companies in any part of the world so till now we have covered till this particular problem and this video I'll be covering the next permutation problem so what does the problem next permutation stay it states that you'll be given an array of integers it can be repetitive integers as well now you have to find the next permutation of this particular array but in order to understand next permutation what you need to First understand is what is permutation now you're given an array and the array is containing integers over here there are three integers these three integers can be rearranged in themselves now imagine if I rearrange three one two can I write them as one two three I can if I bring the one to the first place if I bring the 2 to the second place if I bring the 3 to the third place I can write them as one two three I can also rearrange three one two and write it as three to one I can also rearrange three one two and write it as two one three so I've asked you how many possible rearrangements are possible it'll be like for three one two since there are three numbers three factorial many basic maths six possible ways I can rearrange them in six possible ways now all of these ways are called permutation now the question is asking you to find the next permutation now what does next permutation means when I say permutation all the possible ways have to be written in the sorted order so if you see one two three is before one three two now what do you mean by sorted order if you go to the dictionary can I say one two three will always be smaller than one three two will always be smaller than two one three dictionary order because one two three like one two three smaller than one three two so we have to write them in dictionary order in the sorted order ascending way now you have to find where is three one two can I see three one two appears here it does in the sorted permutation now you have to find the next permutation after three one two and the next permutation is three to one so the answer to this that you have to return will be three to one yes this is what you have to return as an answer now you might be thinking of a possible Edge case what if the array was given as three to one so can I say put three to one these will be the possible permutations but if I have to write the next permutation three to one Lies over here and if I carefully observe there is no one after three to one so what will be the next because there is no one in such cases you will fall back to the first possible rearrangement in the sorted order hence the answer will be one two three if there is no one after this particular Arrangement it'll fall back to the first and the answer will be one two three if this question comes up in an interview the first solution that will tell the interviewer will be of Brute Force solution now what is a brutusation it is generically doing what the problem States the problem was stating uh to generate like if you normally think it's basically generating all the permutations science generate all the possible permutations once you have done that can I say you'll get all of them you will then you'll be like where does three one two lie and make sure you generate all of them in the sorted order then it is like why does tree want to lie so probably I can do a linear search I can I trade I can find that three one two lies over here so do a linear search in order to find where does three want to lie once you've figured out where it lies can I say the next index permutation like this one the next permutation this one will be your answer yes that will be my answer if there doesn't exist next then the first one will be my answer can I say the brute force will be comprising of these three particular steps yes but now you'll be thinking but how do I generate all the possible permutations in order to generate all the possible permutations you will be using recursion and I've already made couple of videos on it so there are two approaches if you see the lecture 12 and lecture 13 from the recursion playlist you'll get to know how to generate all the possible permutations now in an interview you just have to mention these steps usually in an interview you don't have to because if you start coding the code for generating all the permutations and recursion that will eat up a lot of time that is why in an interview you generally we have to just say that this is what I'm thinking generator or do a linear search and that's it and that is when the interviewer will ask you okay what do you think will be the time complexity I'm not diving deep into the time complexity I'll find that in lecture 12 and lecture 13 of the recursion playlist let's just hypothetically analyze the time complexity I know one thing there are three numbers and there were three factorial which is six possible permutations so can I say if there are n numbers there will be at minimum of n factorial at a minimum of n factorial permutations generated and every permutation is of n length so can I say at the minimum um I do not know the algorithm at the minimum if I go across to generate all I'll end up taking n factorial to generate all and each one of them is of length n so this is what I'll at minimum Take N factorial into n and if I say if I give you an array of length 5 n factorial is 120 if I give you an array of length 15 n factorial is near about 10 to the power 12 near above imagine the time it will take 10 to the power 12 iterations this is why this complexities of extremely high order and that is when you'll see that we will not be using it because it will end up taking a lot of time so remember one thing whenever you are in an interview never ever Deep dive into a group 4 solution always tell it from a very high level like generate all linear search the next will be man so because that is what the interviewer wants uh to listen you should not start writing the board because that will end up wasting your time once you've told the steps on a very high level just tell him that this is going to take a Time complexity of a very high order that is why I'll try to optimize it now does there exist a better solution it doesn't like there doesn't exist in a better solution but still for C plus user you can say that I can use the SQL Library so if you use the STL there is an stls next underscore permutation over which if you pass the list it will automatically change the array to the next permuted array got it and then you can return that as an answer but this is an STL which is an inbuilt function now the interview might ask you can you please Implement that inbuilt STL like I know there is an inbuilt next underscore permutation but can you please implement it and that is when you'll jump to the most optimal solution if your job or a python user what you can do is you can skip this part if you are a C plus user I highly recommend you to see this STL so that the interview gets an idea that you have a knowledge about STL as well okay so time to understand the most optimal solution and knowing what happens when that next underscore permutation in C plus STL so the flow of the lecture will be first some observation using this particular example and then we build our intuition once you've done that we move on to the algorithm and then we move on to the dry run once you have done all the three steps we move on to writing the code so at any moment you feel like jumping over you'll find the timestamps in the video and you can jump over so before taking this example and doing some observations for a moment let's go into the English dictionary and imagine I've given it three words Raj racks RBX now we know one thing in English dictionary Raj will appear before racks and racks will appear before RBX now why does that happen now the pretty obvious answer is R A and R A matches so there is a very long prefix that match and then there is a difference of jnx that is the reason Rax tends to appear but it appears after RHA and RBX appears after RX node before RX because over here just one character is Magic and that is the reason it doesn't appears in between so something we have seen in dictionary is the next elements or next elements tends to have a longer prefix match so this is the first thing on which I'll start observing on the example that we have taken so longer prefix match is what I'm looking for longer prefix match because I know the next elements tends to have a very longer prefix match now over here we know something we don't have all like all the possible combos like if you go to an English dictionary you'll find all the possible words but over here we are very restricted to these seven integers so we cannot exactly say that what will be the next because we are restricted we do not have everything in the world so we know one thing in order to get the longer prefix match we have to kind of keep a very long prefix match that's something we know from the English dictionary so the first thing if I try to match everything what will we get we will get the same array so this is definitely not something which will do but if I try to just match this much what will happen two one five four three zero there's only one number left that I can rearrange and mix something I'll again get the same so not pursue if I try to match all of them maybe like two one five four three so I have two numbers if I had something other like nine eight I could have written 98 but we just have 0 which we have to rearrange so if I try to rearrange this will stay constant because prefix match if you try to rearrange 0 it cannot at match be zero so the number like the array still stays the C perfect so we'll try to match four maybe four as possible two one five four if I match four I will have three numbers three zero which I can rearrange I can probably put zero here and then three zero but this will be smaller so that's not possible maybe I can put zero three that small whatever you try to do with these three numbers you will not get anything that's bigger than that so that is not possible maybe I can try to match three two one five three prefixes much and then I have four three double zero you can try out all combos like you can take three four double zero smaller you can take four three double zero same you can take zero four three smaller you can take zero four three zero smaller no one is greater than this so three prefix match is not possible okay I'll try to make two fix match two one and now we have this if I write the same that will give me the C not possible Right four five three double zero not possible if I write three four five double zero not possible so you can again try rearranging all the five numbers will not get anything greater and why is that happening because you have a five you need someone greater than five hear me out properly again you have five in order to get Greater by keeping two prefixes same you need probably a six or seven over here in order to get greater that's not possible because among all the five numbers you have no one is greater than five sorry whatever you rearrange will always be small two prefix matches not possible can I just do one prefix match let's do this now I have one five four three double zero can I put something like five four three one double zero I can and can I say this is definitely after this but is it right after this is my question I can also have two four five three one double zero and this is also after this but this one is before this so I have to kind of find what is right after this so I know one thing I'll have one prefix match I will have one prefix match now there can be five over here and then four one three double zero there can be five one four three double zero there can be five three four one double zero there can be a lot of arrangements that you can make but can you write something like this zero four five three one you cannot because this 0 is smaller than this so this is not possible so what is the thing that you have to take care your matching till here this is where you're changing from so your target will be to get someone who is greater than one get someone who's greater than one that is for sure so who will be that Creator guy you want the next you don't want the very next because if you take two five it's way ahead because we can also take to four we can also take two three which one will you prefer taking two five two four two three two zero is out of question two one is out of question because 0 is smaller one is smaller which one will you take it'll be like someone who's greater than one but the smallest sort of three four five were greater than one was the smallest three so you'll end up taking three got it so this is the observation that I'm forming so before going to the next set of observations let's try to conclude on this first observation and try to build that algorithm that gives me that okay that's just one element of probably gives me something out of this observation so why was this not possible the simple answer is we have four and we need someone greater than four and no one out of these elements were greater than four and no one are of these elements were greater than four thereby it was not possible so I knew this why was to one not possible because we need someone greater than 5 and there was no one greater than 5 but y was 2 possible because we had so many greater than one something Did You observe zero so we're trying to draw the graph 0 3 4 and then five so do you see a graph forming and then there's one here so there is a certain breakpoint and that's what you have to figure out the break point you have to figure out the breakpoint why because if you everything is increasing so you have nothing on the right that smaller the moment you find the breakpoint you're sure on that on the right of one everything is smaller so you have to figure out the breakpoint so what you do is you'll try to run a loop and you'll try to figure out the pre so this will be your I and this will be your I plus one and I can say the break point will be whenever a of I tends to be smaller than a or five plus one very simple observation we need to figure out the breakpoint so the conclusion from the first set of observation is find the breakpoint once you have done that then let's move on to the next set of observation what was the next set of observation we say two will stay but instead of one whom did we take five did we take four did we take three whom do Tweety we did take three why so if you look at the right of one now these two elements are smaller than one and these three elements are greater than one can I say this and if you take five it's far if you take four it's close if you take three it's further closed so what did you try to take you will try to take someone who is slightly greater than one so that's three so what you'll do is since you know this is increasing you know this is an increasing order you'll start iterating zero are you greater than one three oh three are you are greater so I will take this 3 here I will take this three year that's what my observation is second one will be find someone greater than one but the smallest one because you have to find greater than one so three four five was greater but you have to find the small list so that you stay close so the observation is so that you stay close got it so the second step is kind of clear so I'll take three and what I'll do certainly is I've taken three Okay so first two places are filled a what are we left we are left with can I say five four one and double zero these are the numbers that we are left with five four zero one how would you like to place it on these places just think and tell me now can I say 2 3 is now greater than 2 1 so than 2 1. 2 3 is now greater than 2 1 so what should be a third priority to keep this thing as small as possible and how can you do this you'll be like now since 2 3 is greater than 2 1 how you place them doesn't matter but you need to keep it small so will you prefer placing it like this 10 Me 0 1 4 5 yes because that will keep the number small it's already greater here so I'll try to place in a sorted order so try to place remaining in sorted order so this three observation these three observation will build the indication for the algorithm that I'm going to write I hope you've got the indication very simple try to get as long prefix match as possible so I cut the longest prefix match by finding the break next Once you figure out the break point after the longest prefix try to put someone who is slightly greater than this perfect this guy and this was three in this support once you've made this greater fill this out as small so that it's right next got the three intuitions or observations now it's time to think of the algorithm so it is now time to design the algorithm on the basis of the three observations we did and you know the intentions Behind These observations so coming to the first observation find the longest prefix match I know the smudge matched and this was the breaking point where we increased 0 3 4 5 and there was a dip over here can I say there was a dip over here because after five there was a smaller number one so let's take an array like one two three four five can I see if I've been given an array of one two three four five in this case this is the smallest permutation and the largest like the last permutation will be this can I say and over here if you see there's an upward curve like the numbers increase one two three four five and there's no dip why is there no D because this is the last so no prefix cap you can match but over here if you see right here there's a dip yes because 5 is increasing like five is the starting and there's a so I'm going to do four so the dip is here why because then you can say one two three will match and the five and four you can just take someone greater than four so you have taken that's why but in a way you cannot thereby there was no tip so there was a dip here so which is the last index where you can have a dip so it's like n minus 2 is the last index where you can have a dip I can say that so what you will say is first step is very short find out this particular index so you can see that 4 I is equal to n minus 2 I greater than 0 I minus if at any moment array of I comes down to be a dip value then you can see index can you store the value of I and can you break down and what you can do is you can keep the initial index as maybe minus one and if it is minus one if it is minus 1 then you don't need to do anything you can say that this particular array is your answer you can just reverse this particular array and that will be your answer if you see if there is no dip then this is the like next geographically the biggest one so you just reverse it you'll get your answer so that is a very simple algorithm if there is no dip which means index is minus one then you just reverse the array and that will be your answer so this is The Edge case that you have to take care whenever the given array is the last one okay so we have our index pointed here what so I can say I've done the first observation what is the second find out someone greater than 1 but the smallest of that like someone greater than 1 5 is greater 4 is greater 3 is great but you need someone who's the smallest what greater than one smaller spread greater than one so you'll be like zero three four five so there's a increasing curve so you can start from the back zero are you greater 3 are you greater he says M yes and greater so I'll be like cool do that so what you'll do is you'll find this greater and you'll swap it you will swap it why swap I'll tell you just swap it swap done so I'll go across and say I it is equal to n minus 1 and I can go until the index the breakpoint and I can go on like this and if array of I is greater than array of the break point which is index you will see can you please swap array of I and array of index once you have done that can you please break and this will be under the if and the for Loop ends right now I've swapped it so after swapping one will come here three will go here why did I swap I'll tell you so the second point is also done so I can say 2 3 got placed in the correct order what about the next previous leaders to one so now we have two three is greater than two one what do we have five four one double zero I know I'm already greater so I need small so what is my thing 0 1 4 5 how can you get this either you sort this but you knew one thing it was always in the increasing order and if you snap three and one it will still stay in the increasing order so if it's an increasing order you need the reverse now you need the reverse Now isn't it so can I see I will reverse can I sell reverse from here to here if I reverse what will happen zero one four five because I need as small because 2 3 is already greater than 2 1 so I can just make it as small as possible so what I'll say is can you please reverse the array from the index like the break point plus one till the last Index this is what you'll see please reverse it and this will complete the third observation part can I say once you've done this you actually have your next permutation yes you do have and this will be your algorithm I have also done the dry run with the algorithm let's quickly code it up make sure you cry out the problem from the problem Link in the description so coming back to the code enter we are given the list what was the first thing we did we figured out yes let's try from the back so probably we can just store the size and that's a DOT size and we know we will be starting off from this and we can go on let's go ahead and I know one thing if array of I is smaller than array of I plus 1 that means it's a break so I go ahead and say hey this is my break index and you can pick but if there was no break index the given one was the last so I'll say reverse so in C plus we have this function again the Java code will be in the description make sure you check it out and away you can just write a letter quite simple you end it over here if it is not what do you do from the back you find out which is the first grader or the least greater end so let's start from the back again so I'll say let's start from the back and probably I can just go on till the index and I can go on like this and if I know a of I is greater than a of index that means we got someone who's greater I was the first guy I will swap and if I'll swap it I will just go off that's the step two so what I can say is uh the second step is also done what is the third step you have to reverse why because see you have five four one double zero but two three is greater now you want this to be as small so the simple job is you say reverse again in C plus STL is there java Port is in the description so you reverse from this particular index till the end and once you've done this you can return the array now we will quickly go and run this and see if this is running fine should be running fine so as we can see that this particular Port is accepted now if we talk about the time complexity we go of n plus we go of N and plus b go of n at the worst case so the time complexity at the worst case may be near about big of three and will be near about big of three and yes you are modifying the array so if the interviewer says that is considered in the time a space complexity will be big open otherwise it is bigger fund because I am not using any extra space in order to solve this problem yes I'm modifying the array but I'm not using anything from myself so coming back to the sheet I can mark this as done I hope you have understood the observation the intuition because see algorithm every one everyone can just write the algorithm and do the trial but the thought process the observation the intuition the designing of the algorithm that is the key and I hope I've understood it and it took me like two hours to record this lecture and it's like three nine am in the morning so in case you watching this video till here please do consider giving that like and if you're new to our Channel please do consider giving us a subscribe because 45 of the users who watch our videos do not subscribe and I understand it's an education channel so most of the people do not press it but please do consider pressing that subscribe because it does highly motivate me to make subscribe of content and yes to continue our tradition make sure you comment understood as well and if you haven't followed me on Instagram Twitter LinkedIn the links will be in the description with this I'll be wrapping up this video that's been in some other videos whenever your heart is broken don't ever forget your golden I will find a light in
|
Next Permutation
|
next-permutation
|
A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order.
* For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`.
The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
* For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`.
* Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`.
* While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement.
Given an array of integers `nums`, _find the next permutation of_ `nums`.
The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,3,2\]
**Example 2:**
**Input:** nums = \[3,2,1\]
**Output:** \[1,2,3\]
**Example 3:**
**Input:** nums = \[1,1,5\]
**Output:** \[1,5,1\]
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 100`
| null |
Array,Two Pointers
|
Medium
|
46,47,60,267,1978
|
215 |
what's up everybody although here and welcome back to yet another youtube video in today's video we'll be solving another medium level lead code problem number 215 also called as eighth largest elements in an array now we'll be solving this with the help of two methods one is with the brute force that is sorting and other one is with the maxim so without the further ado let's get started now the problem states that we are given an integer array nums and an integer k and we need to return the kth largest element in that array now here the largest element is in the sorted order okay so not the key distinct element now if we look at the examples we have the first example as the array including three two one five six and four and we need to return the second largest that is if we see here we have the six as the largest element so the second largest would be five that is why we return five similarly in the second example we have the following given array and we need to return the fourth largest so the maximum is six then we have two fives so we are done with three and the fourth element is four so we return four the constraints that we are given here is that let me just clear my screen the constraints that we are given here is k is from 1 to 10 to the power 4 and nums of i that is every element of the vector is from minus 10 to the power 4 to 10 to the power 4. now let us look at how we can approach the solution of the problem now the simplest approach or the most naive or brute force approach that you can say is that we take the vector and we just sort it because we need kth largest so after sorting we will have them from uh lowest to the highest that is the largest element and then we can take the kth largest that is from the back side we take the kth element and we return that so that is what we are basically doing here in the most native approach that is we sort the element now here the sort is the std sort that we have and then we just return the kth element from the last of the vector so that's the first approach now for the previous approach that we saw uh with the help of sorting uh it takes basically time for sorting which is the maximum time that is n log n and after that we just return the kth largest element okay so basically the time complexity would be off and login now to optimize that we can use the data structure called as max heap and in c plus we implement maxi with priority queues now if you do not know what max heaps are what heaps are basically they store the elements in uh in a particular manner if it is on max heap then we always get uh whenever we want to get an element from the maxi we always get the largest element and similarly in the min heap we get the smallest element okay so if we uh keep on pushing the elements for from this vector that we are given into the maxi then firstly whenever we pop any element from that we will get the largest element that is six similarly we if we keep on popping we can get the second largest that is five and if we keep on doing that we'll get uh in the decreasing order okay so that is what the max heap is for so how we implement that solution is basically we take a priority queue and we uh push all the elements of the priority of the vector into that priority queue now in the priority queue it basically uh saves it in the tree format so if you want to learn more you can check it on google you can get how that is uh internally implemented so basically the first element the top element of that tree would be six that is the largest and if we pop we can get the second largest element okay so that is what we are doing we are running a for loop and then till k because we need the kth largest element and if uh we are at the kth element that is k minus one because it is a zero based indexing we return the top of the element okay otherwise what we do is we just basically uh pop the element until we reach that keith element and if uh we have the kth element and we do not do any bounce error then we should be returning at this point itself we will not be reaching this point but this is just to make sure that we do not get error while submitting our port okay so that's the solution let's quickly run it i've ran it already and it was giving me 10 okay now it gave me three millisecond which is faster than 92.32 percent and which is faster than 92.32 percent and which is faster than 92.32 percent and memory uses as 10.5 less than 9.65 memory uses as 10.5 less than 9.65 memory uses as 10.5 less than 9.65 percent solution so that's all for this video and i'll see you in the next one you
|
Kth Largest Element in an Array
|
kth-largest-element-in-an-array
|
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_.
Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
You must solve it in `O(n)` time complexity.
**Example 1:**
**Input:** nums = \[3,2,1,5,6,4\], k = 2
**Output:** 5
**Example 2:**
**Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4
**Output:** 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
|
Medium
|
324,347,414,789,1014,2113,2204,2250
|
1 |
this is Leap code question one the two sum problem now this is a classic problem and there's a reason why this is the first uh in the leak code list and that's because we can solve this intuitively firstly but then we'll come across a core approach which might not be obvious at first so given an array of integers nums and an integer Target return indices of the two numbers such that they add up to Target so you may assume that each input would have exactly one solution and you may not use the same element twice you can return the answer in any order so let's have a look at an example here example one we want the target of nine so we look at the elements in nums and we can see well the zeroth element two and the first element seven if you sum those together you get nine as the answer so we can return the index of those numbers so the array 0 1 . if we look at example two . if we look at example two . if we look at example two we can see that we want the target of six so three won't add anything but 2 and 4 can add together and then the first and second element can thus be returned and it's good to note that there's exactly one solution so as soon as we find that uh we can return that another thing is only one valid answer exists and is this really good follow-up question really good follow-up question really good follow-up question can you come up with an algorithm that is less than all n Square time complexity so we'll see that in the second part of this video but firstly let's solve this the intuitive way so the intuitive approach is to create a for Loop and we want to Loop through each number in the array starting from the start so we'll let I equal zero and while I is less than the length of the array we can increment I and then what we want to do is for that particular number we're on we want to Loop through the remaining numbers or the other numbers so what we can do is we can have this nested for Loop and then we'll just rewrite the variable I as J to represent it being a different number and since we've got this double for Loop we know this is going to be o of N squared um there's only really one thing we need to do in the for Loop so there's no of endings in the nested for Loop so basically we want to ignore the case that um you don't want to repeat the same element and since you may not use the same element twice we need to check if our number that our outer iteration is on is equal to the index of the inner number so we're comparing the indexes of the outer to the inner loop if they're the same well you can just continue but if we find that the first number plus the second number so the outer number the number from the outer loop plus the number from the particular inner loop that we're on in this inner iteration if that if those two numbers together add up to the Target value then that means we've got the result so we can just go ahead and return the indexes of that because that's what the question wants so we can just return I and J and we're guaranteed a solution but for typescript we want to return just the empty array so it matches the return type because it doesn't necessarily know so let's run this okay so it's accepted the solution and if we look at the space complexity it's all of One the reason it's all of One is because we're not needing to um all we're doing is an addition there um there's no we're not assigning that we use for every iteration or anything like that we're just looking through the numbers um so the time complexity is N squared because the memory lookup is a nested for Loop um but the old one space complexity is okay but we can do better as the follow-up question suggests follow-up question suggests follow-up question suggests how can we do better so let's consider the fact that we don't want to have two for loops we will need to have at least one for Loop because we need to Loop through the numbers to be able to determine what they are and you know that's obvious because we need to go through the numbers to find the sum of them if they equal the target how can we be doing better than old N squared well we better than all of N squared is basically well for this case we should be aiming for o of N and the reason we know we're aiming for all of n is because there's the follow-up question because there's the follow-up question because there's the follow-up question can you do better than all N squared which we can um but we need to Loop through everything so it only makes sense that things are going to be o of n so and it doesn't need to be o n log of n so we'll discuss the logs in another video but um you know we're not doing any sorting here um so let's just copy this out of for Loop here so we can Loop through our numbers and the trick to this question is rather than having two for Loops that are nested and we do that because we needed one element in the numbers array added to another element in the numbers array but we weren't sure which one it was and add those two numbers to equal the target the trick is to think of it as well to find the other number you can take the target number and you can subtract the particular number you're on and they will find you the complement so let's create this variable here we'll call it complement and essentially that's just going to equal the target minus the particular number that you're on and the reason we do that is so we don't have to if we keep track of all of these complements um in like a object or a map they'll have all of One lookup so we can just quickly look that up by a number and if it exists then we can say well you know that complement plus the number we're all and that's going to equal our Target so let's just add uh the number we're on the index I so let's create a variable to keep track of all of our complements and let's just adjust some settings here make it two spaces even though I'm sort of halfway through already um so let's create our complements variable and this is essentially going to be an object where the key is the particular number and then this value is the num the index of the number um that are in the nums array so we can have this map type this is um built into JavaScript uh and then we can put in this generic type here where the keys number and the value is number and I'll just put this note here to say that the index is the number so that means essentially what we can do is well we have the complement so we can just go ahead and we can set the complement so on a map we can use the set method and we can pass in the number which is num's I and then the index I so every time we've looped through a number um we've added the complement of the number that we're looking for into the complements map which means that if we can find that um or if we do a lookup when we go to the next iteration and that number exists well that means those two numbers together will be the target so that's why we keep track of the index because this question wants us to return the index so all we have to do is just check for that so we can have an if condition and basically if our complements and since we're using a map we need to use the has method so we pass in our complement so the number that we're looking for and if that's in our list or our map we can go ahead and we can return the index so to get the index of the complement you can say complements.get complement you can say complements.get complement you can say complements.get complement and I'll return the index and then we also need the index of the value that we're on so we can pass that in as a second element and then we can just go ahead and we can return that and if we're thinking about the space and time complexity uh we've got this for Loop so that's going to be o of n and the space complexity that's also going to be old and because we need to Loop through our numbers and then we need to assign a variable to each of the numbers and it could be the case that we don't find the complement all the way to the end so we need to consider the worst case scenario where the space is O of n and the time complexity is old and because we're doing a lookup for each element in the array um when you get the element from the map that's the old one lookup so you can get that almost instantaneously um so it all then will be the dominant term so let's go ahead and submit that and we can see it beats 86 percent which is pretty good so this was a really good algorithm to solve shows you how you need to know some of these approaches because the um you know the intuitive approach isn't always the best approach and if you haven't studied this before it's sort of you know unlikely that you'll stumble across these Solutions um the good news is that you know the topics I'm covering this video will give you the fundamentals of all these sort of techniques and in the next video we're going to see the two sum part two
|
Two Sum
|
two-sum
|
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
You can return the answer in any order.
**Example 1:**
**Input:** nums = \[2,7,11,15\], target = 9
**Output:** \[0,1\]
**Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\].
**Example 2:**
**Input:** nums = \[3,2,4\], target = 6
**Output:** \[1,2\]
**Example 3:**
**Input:** nums = \[3,3\], target = 6
**Output:** \[0,1\]
**Constraints:**
* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**
**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
|
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
|
Array,Hash Table
|
Easy
|
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
|
1,094 |
Jhaal Hello Hi Guys Welcome To Dad Today's Question Is Car Pulling In This Question Or Driving Michael Phelps Easily Available For Passengers Divide Kar Lu Drives Us Towards East Subscribe And Content Information if you liked The Video then subscribe to the Video then subscribe to subscribe our Of all passenger is all the giver by question 20001 first representatives in numbers are cent in the first place to start position is vansh and position spinach and total capacity of sarkar is 400 but so in this case pick up two passengers from first position and they will Drop Back To Phone Position And In Between The Pickup Three Passengers From Third Position And Drop 227 Position So I Will Not Carefully Date End Position From 4 To 5 Tags Page 6 And Three Position Lower Also Already Have Two Passengers So E Third Position Capacity Hindi Ka Ras 235 Butter Total Capacity of Percentage Sarkar K 400 Return for Example Give two changes to wake up from his position and drop back to fifth position and three passengers pay third position and drop 227 Position and Capacity of Sarkar Is 50 Case Will return to rule because when will sit at third position which is strong strips total number of people in president subscribe button to the question paper of class eleventh class 10 questions subscribe the time of start and id have that sports is posed and this is trip to make Timestamp that is not in position and miss position but will you give me time at ace2three passengers pendant position 0530 like for example position to earth passengers subscribe The Channel Please subscribe and position the fifth passengers is next9 position field drop husband passengers midnight position will drop dsp Passenger Subah Maker Tweet on Twitter Story Start Position and Difficult to Opposition and Corresponding Events to Reduce the Beneficial for B.Com Events to Reduce the Beneficial for B.Com Events to Reduce the Beneficial for B.Com First Vighn Subscribe to - The Video First Vighn Subscribe to - The Video First Vighn Subscribe to - The Video then subscribe to the Page A proposition which welcome first will be sorted like it will be sold on The basis of the position day to day three lines based din sevat ki sudarshan jha websites in the website did not meet you will read through if twitter on Thursday attached one position which position third position will check the change in the middle of the windows and Do n't forget to subscribe third position 232 and subscribe 11112 position Well now the second passenger that is - body Well now the second passenger that is - body Well now the second passenger that is - body website Calcium Vikram 11:00 - 4800 will be doing with checking during sleep on website Calcium Vikram 11:00 - 4800 will be doing with checking during sleep on dark timestamp representative one side address vector peer vote this time Its Time Is Used For Traveling And Went There At Every Position This Current President Vice City Plus Karo Time But Second This 381 Shown So Another Current President Movement Will Be Greater Than Ther Capacity Is The World Will Return Forms And Incarnations From Time To wake up sid and subscribe today am only with opposition will check every position birds impacts owner current capacity is the current president capacity return forms and edit will be done through listen deshwasi whole approach timestamp in log in which is the Means of 512 Co Maximum Value of Pending Position Starting Position Will Be of Thousand Sudhir Vo 101 And Would Also Withdraw Cash Like Subscribe Button For Every Position To Position And E Channel Do Not Subscribe And Subscribe Button Appointed This And Subscribe To The Position Of these two 7 index two of these are representatives second position and 10 representatives and information so in this case automatically are in short position only this will help in same time complexity as white only online in a soft manner so that the world you will update the index And Second Position With Changing Number Passenger Update Position Text Message Setting On The Person's Top Subscribe Like Subscribe 27 2012 Second Position With Three Members In The Same Position To The Amazing Three Position Two Three Position Subscribe Similarly In Next Subscribe Similarly In This 222 838 Passengers Ninth Position Medicine Index Of But There Will Be A Surprise Visit Passengers 102 Uttar Pradesh Loop British Pass Bihar Me Director Of Times Time Of 510 Scion Trilok Noble Truth Paved Reps Added Every Day Trip Will The One Billion Passengers Dot Position Dentist Towards 1000 Percent Forth Disposition and tree to represent assistant position sowe lead will 8000 that is number passengers endowed app the seventh position due to position will surprise the number send your setting of the big wedding of the Michael so after this over will agree position will have if they Delhi Passenger Decoration of Increasing and Passenger Updates Time to Time The Video then subscribe to the Page if you liked The Video then Ki End After 10 Loop Attended Divya Neighboring Country Known for Its Ability to Enter 1363 Possible Apart Again Will Explain Jyoti Approach English Medium Size 102 Shot Are Not Agree With U The Index And Other Mirch Se Number Passenger Update Position But As They Sardar Picked Up And Dandruff Like This Example Its Position At Third Position Passenger Subscribe To I Will Rdc Passengers And In Battery Only At Second Position Dashrath Passengers and Drop Date Position Due to Will Spread Number Five Senses and Three Times a Response Will Win That and Merger Day Velvet Every Intact and Current Capacity and He is the Current President Capacity Will Return Forms Will Attain True After Elections and Sudesh and Buddhi Approach 15.2 Over and Over Again and Buddhi Approach 15.2 Over and Over Again and Buddhi Approach 15.2 Over and Over Again Time Because Yeh To Shot Di Aur Timestamp Button Second App Launch Blood Already Made In Areas Size 101 With All Its Opted Sudhir Par Also Drafted And Complexity Have Committed To End In This Case Such Sacrifices And Dinner First Step Every Morning Directly from First Time Champion 1000 Times a Day for Relief Fund or Pickup Location Where Were Number of Members Later in Bluetooth Settings for More Benefits Number of The Number of Members Were Targeting of the Michaels Should Look Bill Is This Loop Will Update And beyond time suman sa before time this updated but will do will trade tower before time and every value in time se per equal will editing and current capacity in senior resident current capacity value effect of building directly city wise city for over three do It Means The Sun Can See In The Morning That's Getting Accepted Gas Lighter Video Thank You To
|
Car Pooling
|
matrix-cells-in-distance-order
|
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_.
**Example 1:**
**Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4
**Output:** false
**Example 2:**
**Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5
**Output:** true
**Constraints:**
* `1 <= trips.length <= 1000`
* `trips[i].length == 3`
* `1 <= numPassengersi <= 100`
* `0 <= fromi < toi <= 1000`
* `1 <= capacity <= 105`
| null |
Array,Math,Geometry,Sorting,Matrix
|
Easy
|
2304
|
105 |
hey what's up guys uh this is chum here so this time today's daily challenge problem uh number 105 construct binary tree from pre-order 105 construct binary tree from pre-order 105 construct binary tree from pre-order a new other traversal very classic tree problem right i think everyone knows what is the pre-order and the other traversal pre-order and the other traversal pre-order and the other traversal right so pre-order traversal is like we right so pre-order traversal is like we right so pre-order traversal is like we visit root note first and then left and then right and for you know order we reach the left first and then right uh then root and then right okay and given pre-order and the other traversal we pre-order and the other traversal we pre-order and the other traversal we need to reconstruct the original tree right so for this kind of for this problem you know so to me i think the pre-order is the most think the pre-order is the most think the pre-order is the most important one because the because you know if we follow the pre-order follow the pre-order follow the pre-order sequence here you know that's exactly the sequence we are going to use to build our tree right for example this one you know the first one is three which means three is the root note okay and then the left one the next one is nine the nine is the one that we want to attach to three which is in the left child okay and then 20 is isn't is the next one because 20 is the right child we're going to uh append because you know there's nothing under 9 that's why you know the next one is 20 right and then 15 okay 15 is exactly the next uh tree node we're going to create which is this one which is the parent the sorry which is the uh the child node of 20 and then seven in the end right that's why you know this pre-order to me is more important this pre-order to me is more important this pre-order to me is more important but only given this pre-order will not but only given this pre-order will not but only given this pre-order will not be enough for us to reconstruct the tree right because you know the trick would also be like this could be 3 9 20 15 and then 7 right so this can also be a tree and the pre-order for this tree is also and the pre-order for this tree is also and the pre-order for this tree is also this sequence okay so that's when this you know other list comes to rescue right basically we need this in other uh traversal to help us determine if given the current node we want to know if this current node has any child that's when we need to use the second one and the reason being is because you know let's say for example you know we have three here right so three is this so we have a 9 3 15 20 and seven right so three is the first one that we're going to process and three this index for three right so we know by looking at three you know every time basically we split uh this in other traversal lists into two parts where the left part is a is that it's everything on the left side of the current route and this part is the right side on the current route right that's why you know the next one it's nigh because you know we know they're like a child on the left side of three right and then come when it comes to nine we want to know okay so nine doesn't have a child so how can we know that because you know because when we process nine we're in the range of this part right and this part we have a range where it's from zero two to one i think assuming there's a range right and then we want to see that you know between knight and the left do we have any other like numbers if we do right if we do on if there's anything between the range between the left border and the knight if there's like any numbers here no then we know okay knight has some other uh has a left child right and if there's anything on the right side of knight between nine and three then we know this part will be the right child out of nine right that's why you know every time when we have when we're processing a number here you know we'll be using we'll find we'll try to find the index in the in order and then we'll use the left and right boundary right to check if the card node has any left or right child and that's basic the idea here you know so in order to check since for each of the node we have a boundaries for that right between the left and right that's why when we write the dfs here you know we need uh two more index here right our parameters here that can tell us the boundaries of the current node and then since we're going to process the pre-order in sequence you know we can pre-order in sequence you know we can pre-order in sequence you know we can simply do this so every time when we are at a dfs we can simply do a pre-order you know dot pop simply do a pre-order you know dot pop simply do a pre-order you know dot pop zero yeah i'm not i'm assuming this one is like oh off one but in reality it's not but i'm just using this one just to for this simplicity purpose and then every time we have a node we simply uh it's going to be a root right it's going to be a tree node of value right and then we need to find the index of the current value in the you know the traversal right you know in other dot index of value right and then you know we're going to have like a node left equal to dfs left dot i minus 1 right and then node dot right equals to dfs of i plus 1 dot right and then in the end i return the root so here like i said you know given like a current values we need to know if the current one if this value has any left uh tree or right tree right so we do so by passing in this kind of uh the boundaries for the left half or the right half right because here we already have i here that's why the boundaries will be i minus one right and i plus one here and obviously if there's no left or right subtree we need to return we need to set a nine here right otherwise we recursively calling this dfs to process the subtree right so the base case will be if the l is greater than r right we return none right for example if we have knight here right if the current value doesn't have any uh doesn't have any children you know basically this i'll if this one doesn't have any children it means that you know l is equal to r because it's the node it's by itself right so which means you know every time we do a either do a uh i minor l to i minus one or i minus one to r will all will both lead to this number here right so yeah and that's it so we have this um we can simply return here so it's going to be n dot length of pre-order minus one of pre-order minus one of pre-order minus one okay yeah that's it if i run the code right submit yeah there you go right i mean it's very classic you know a dfs uh tree problem but this time it's in the reverse way right basically you're given like a pre-order and another pre-order and another pre-order and another uh traversal list and then you need to reconstruct the arduino tree so basically you know that we use the pre-order uh traversal that we use the pre-order uh traversal that we use the pre-order uh traversal as a main source because that this will be the sequence we're constructing the tree node and then in order to reconstruct the tree we need to know if the current one has any child or not right how can we check we simply use the uh the range for the current subtree plus the uh yeah just use the current range of the tree and then to check if the current one has any trout because you know in other you know if we find the index for the current values you know we will we can know how many uh notes we have on the left on the card notes left or on the card notes right and we can use that to determine if the current one has a left subtree or not and that's it's not that difficult but i believe this is quite interesting and the better to understand the concept behind it cool thank you for watching this video guys and stay tuned see you guys soon bye
|
Construct Binary Tree from Preorder and Inorder Traversal
|
construct-binary-tree-from-preorder-and-inorder-traversal
|
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** preorder = \[-1\], inorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= preorder.length <= 3000`
* `inorder.length == preorder.length`
* `-3000 <= preorder[i], inorder[i] <= 3000`
* `preorder` and `inorder` consist of **unique** values.
* Each value of `inorder` also appears in `preorder`.
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
106
|
1,287 |
Hello friends welcome to a new video in this video I am going to discuss a array based problem okay it is a lead code problem okay so what is problem is saying to you let's see so we have to find out the element appearing more than 25 percent assorted array means a Aries given to us and the array is in sorted order okay and the array is sorted in non-descending order I mean increasing non-descending order I mean increasing non-descending order I mean increasing order okay and you have to find out the element that is uh that is occurs more than 25 percent okay so 25 percent means what 25 percent divided by uh divided by 100 right yes one by four right so you only need to find a um the element as is occurs 25 percent more than 25 percent or equals to okay more than 25 percent so I will do this code using hazmap okay show them more than 25 percent okay more than 25 based on what based on the total number of the elements total number of elements is equals to array size means length of the atom right means what I am trying to show you right n equals to let's take an integer variable n and then KR are 12 length divided by a form okay because total number of the elements is equals to add a length right and um the 25 total number of the elements right so that's why I have write test um that's why I have just write ARR plus length means the length of the array means a total number of elements divided by four divided by 4 means 25 percent right 25 percent means one by four Tesla is just multiply array size initial length of the array into one by four I think it's clear to you now okay and now drivers are added I will use uh I visa for each Loop okay and okay this is the key and this is the value right so I will use key I will use the number of the elements as key and the occurrences as the value okay who is key as the number means the element minister right one I will take one as a key okay two as a key six answer key for 7 as a key ten as a key and the number of the occurrences I'll take as a value number of the occurrency I will take as a value means one is number of the occurrences is 1 means a value will be one for two the number of occurrences two so I will take the value as 2 Okay so either you I will now I will write h a hm thought put I then it's in so okay for P4 plus 1 okay so here I will just put all the uh elements of array into the this is a method if in a particular key there if they don't have any value then it will return 0 and we'll just add that one we will just add plus one okay if they are already have the value then it will be written that value and we'll just add plus 1 with that value if they don't have any value means this value is 0 means then it will be written 0 because get or D for me if I don't have any value then it will result 0 and then we will just add plus one if we already have a value then we'll just take that value and we'll just add plus 1 with that value adding Square in that word we can easily calculate the occurrences of any particular number okay so now we'll just Traverse this hash map okay if he Dot get value okay hello because here is right here what is written here the written uh what is written here more than 25 percent right more than 25 percent mean greater than n okay not equals to note we cannot we can write greater than equals to we have to write Kera then become more than 25 percent not equals to not more than equals to write so then we will just return that key value okay e dot get Keith okay otherwise I return this zero okay I think is clear to you okay so I will repeat all the things again at first here I just calculate the 25 percent of the um 25 of the atom means all the basically all the element Basin in the array which is point of the 25 percent of the array um okay and then here I take a hash map and here I just have her sorry and I will add all the elements in the Hazmat the key is the valve key is the elements means the elements that are present okay and value is the occurrences of any particular element okay that I will take as a value map okay and here I just check if the occurrency means the value means occurrences right if the value is scarier than N means this N means is 25 percent mean more than 25 percent means more than n then I will just return that key value okay otherwise I will return in I will send this groom okay I think it's clear to you if you have any question then you can ask me in the comment section and yeah that's all for this video I used it videos helpful for you thanks for watching
|
Element Appearing More Than 25% In Sorted Array
|
distance-between-bus-stops
|
Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
**Example 1:**
**Input:** arr = \[1,2,2,6,6,6,6,7,10\]
**Output:** 6
**Example 2:**
**Input:** arr = \[1,1\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 105`
|
Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions.
|
Array
|
Easy
| null |
116 |
okay hi everyone welcome to the solution of another lead code problem so today we are going to solve a problem related to binary trees the problem name is populating next right pointers in each node so let's go through the problem once so you are given a perfect binary tree where all the leaves are on the same level and every parent has two children the binary tree has the following definition struck node so value of the node is given the left and right pointers are also given and apart from these three things one node next pointer is also given so populate each next pointer to point to its next right node if there is no next right node the next pointer should be set to null okay and initially all next pointers are set to null so here we are given one example so the next point of node one will be pointing to null because it doesn't have a node present to its right the next pointer of node 2 is pointing to 3 which is present on its right the next pointer of 4 is pointing to 5 next pointer is pointing to 6 next pointer is pointing to 7 okay so basically the next pointer of a particular node will be pointing to the node present on its right side so this is a classic example of level order traversal like basically if this is level 1 level 2 level 3 so the nodes present at a particular level will be pointing to each other basically so the next pointer of node two will be pointing to the another node present at the same level similarly we if you are at level three so four to five to six to seven we have to kind of make this connection so how to go about this level of traversal so level order traversal can be implemented using the concept of queues so let's uh quickly go through the algorithm that can be used here so if we just write the algo so we will first have to create one queue and in this queue we have to initialize with pushing back the first node and basically one more node which contains null as the value so why are you populating null here so null basically it shows that we have reached the end of a particular level so we are at level one the level one has only one node which is one only and we just populated none to mark that level one is complete right so we are at this level and now we will start with the iteration of this cube basically we will iterate from the front of the queue that's how the queue works so we take the element one from the queue so before going into depth of this algorithm so basically whenever we are iterating over this q we have to perform three operations first is we have to check if it has left child second operation is check if it has right child and the third operation we have to do is populate the next pointer of the current node right so this is how our queue looks like right now and we start with the front of the cube so the front of the queue value element is one so we check if it is a left side yes it has so we populate two here if we go to the second step we check if it is the right child yes it has we populate three here push back basically three to the q now we populate the next pointer so the next pointer of one that is the next pointer of the element in the front of the queue will be nothing but the element present after that element in the queue so the next pointer of one will be nothing but null right so we will mark the next pointer one to be null and all the three operations has been completed for node one so we will pop front node one from the queue so now we encountered null to the queue from the queue which means we have completed just a level right now so which means that all its children of that particular level would have been already been pushed back to the queue which means we need to mark that end of the level with the lesson right and we don't need to do any further processing with null so we can directly opt friend null from the queue now coming to 2 we check if 2 has a left side yes it has we push back four it has a right hand yes it has then what we have to do is we have to do this third step which means we have to populate the next pointer of node two so the next point of node 2 will be nothing but the next element of the present in the queue itself so the next element present in the queue after this element is nothing but 3 so the next point of 2 will be pointing to so all the operations for this node two are completed we pop front two from the queue now coming to three uh three left child is six its right side is seven and now to populate the next pointer of node 3 which will be null itself right because the next element present after 3 is none now all the operations of node three are completed we pop front three from the queue now we have encountered null in the queue which means we currently have completed uh all the elements of a particular level and all its children have been already pushed back to the queue right so we push back another null into the queue to mark it as end of the level and nothing more has to be done with this null node so we directly pop front null from the queue right so we are at node four doesn't have left or right child so these two steps are basically useless to us now coming back to the third step for node four so the next pointer of node four will be the next value present in the queue which is five so we will mark next point of node four as five we pop friend four from the queue similar operations for five as well so five next pointer will be pointing to six next pointer will be pointing to seven next pointer will be pointing to null so uh now the queue contains just null and we just pop this null element as well and the queue is empty and till this point all the next pointers of the nodes in the tree would have been correctly assigned right so in this approach uh like we are going through all the elements just once at max so the time complexity would be of n only but the space complexity for this problem by going by this approach would be uh would also be of n because it would be the maximum size of the cube that is possible and the maximum size of q in this case would be the maximum number of elements present at a particular level right because that's how we are populating the queue so the maximum number of present uh nodes present at a particular level in this case because it's a perfect binary tree so that would be at the last level only that is where all the leaves are present and that would be n by 2 actually because in a perfect binary tree the number of leaves present is n by 2 where n is the total number of nodes in the tree so the space complexity is off and on only and the time is off and as well yeah so this is one of the approaches uh going for this solution and this is also an acceptable solution right it's a bfs approach that we have taken so let's think of an another solution in which we don't have to use the implementation of the queue so if you know our observed carefully in this problem some of the things can be uh directly uh deducted so suppose so let's take a note for example so suppose we are at node 2 and we have to check whether the current node that we are at whether it is a left child of its parent or right side of its parent so here 2 is a left side of its parent right so next pointer of two will be pointing to the right child of its parent right side of its parent which is three and another case can be if the node is a right child of its parent so let's take an example of 5 so 5 is a right child of its parent 2 right so the next pointer of five we have to point it to six so how can we go from five to six we have to take this path five two three six so we go to the parent of five we go to the parent right so we come at 2 we see what is the next pointer of 2 which is 3 and after coming to 3 we take its left child which is 6. so let's uh write the logic for this once and uh things would be much clearer after that so this is the base case if root itself is not we directly return and we have to check if the node that we are at which is the left child right so it's next point that will be pointing to suppose this is the rule uh this is the root left is plane which means it is not null so 2 is there so we have to populate next pointer of 2 so root left is 2 next pointer would be 2 right root here is 1 root left is two root right is three so root left next would be three similarly if roots right pointer is present right node is present in that case we have to we can mark the next pointer as we would so suppose let's take an example of 5 here so root is two root right is five right so root ride is not none so we go inside this if condition so we have to mark the next node of this file root right next would be equal to root next now we come to three from this root next three and then its left side that's it and going for the recursion we will recursively call the left subtree and the right subtree and ultimately we have to return the root cause that's it let's try to run it right time error okay root ride is present would write next is equal to root left next okay so we have taken example of five here uh yeah let's take an example of seven so if the root is three root right is seven so we go inside this if condition so we have to populate next pointer for this seven root right next would be equal to root next the root is three root next would be null okay so we are doing nulls next pointer so we are kind of doing a null uh pointer if we're basically trying to access nothing which is wrong so we have to add one extra condition here basically next thing has to be present just move it down that's it try to run it yeah let me just try to submit it yeah so for this as we can see the runtime and memory usage both are very high memory usage is perfectly fine because it's greater than 84 percent but if we would have gone by a q approach then this memory usage would have been you know much lesser uh like memory switch would have been greater but here the value would have been much lesser correct because we are using extra space there here as well if we kind of think like uh we someone may argue that we are using the extra space in the form of recursion but uh i guess lead code doesn't consider that space while extracting these statistics so this looks a perfectly fine solution and uh yeah so this is it like this pretty much the solution and if you guys have any queries or any improvements are needed in this solution so please feel free to comment in the comment section and i will see you next time with another problem of report so take care thank you
|
Populating Next Right Pointers in Each Node
|
populating-next-right-pointers-in-each-node
|
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[1,#,2,3,#,4,5,6,7,#\]
**Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 212 - 1]`.
* `-1000 <= Node.val <= 1000`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
117,199
|
1,630 |
lead code 1630 arithmetic subarrays a sequence of numbers is called arithmetic if it consists of at least two elements and the difference between every two consecutive elements is the same or formul a sequence is arithmetic if and only if s i + 1 - s i = s of 1 - if and only if s i + 1 - s i = s of 1 - if and only if s i + 1 - s i = s of 1 - s of 0 for all I got it uh you're given an array and two arrays of M integers each two arrays of M integers oh I see yes representing the M range queries and the E query is the range L of I through R of I inclusive all the arrays are zero indexed return a list of Boolean elements answer where answer of I is true if the subarray can be rearranged to form an arithmetic sequ sequence and faults otherwise okay that's easy enough um can be uh left right so ARR equals um nums Left Right AR r. sort um so uh if length of ARR is less than two return fults difference equals excuse me AR r of 1 minus a r of zero for I in range 2 to length ARR if D does not equal a RR of I minus a r of IUS one then return false all other cases return true and then um for uh L comma R in zip L comma R oh crap left right um if not can be l r then return false else return true false is not a valid value for the expected return type list of Boolean whoopsie got to pay attention to what I'm doing that was just sloppy all right have a great day
|
Arithmetic Subarrays
|
count-odd-numbers-in-an-interval-range
|
A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`.
For example, these are **arithmetic** sequences:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not **arithmetic**:
1, 1, 2, 5, 7
You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**.
Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._
**Example 1:**
**Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]`
**Output:** `[true,false,true]`
**Explanation:**
In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence.
In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence.
In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence.
**Example 2:**
**Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\]
**Output:** \[false,true,false,false,true,true\]
**Constraints:**
* `n == nums.length`
* `m == l.length`
* `m == r.length`
* `2 <= n <= 500`
* `1 <= m <= 500`
* `0 <= l[i] < r[i] < n`
* `-105 <= nums[i] <= 105`
|
If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low.
|
Math
|
Easy
| null |
1,823 |
Hello Everyone Today By Solving Dil Weekly Contest Problem With This Cross Very Interesting Places Is For The Sharing Solution This Question Of Death Is The Winner Of Circular Game Play Revolving Chair And Subscribe 12345 Every Element Will Be Eliminated Waste Oil Filter Element Subscribe Don't forget the under-14 hydration favorite song on the under-14 hydration favorite song on the under-14 hydration favorite song on the freezer winner after all directions and don't touch screen 200 without match schedule and definition of windows 10 and unlimited slide show of divisional magistrate 4 find winner utsav killer game list 1234 so let's train visualize The Problem With Another Example subscribe Video One Two Three Idiot 123 Jai Hind Leave Hydration A Pot With The Limit 123 That Hindustan Ko Side Reaction To Will Be Eliminated 123 That In Race Then Titration I Will Be Eliminated 123 Half Minute Winner Of The Hey A Combination Is One Different How Can We Do This Problem Solving Problems Approach To Subscribe To 108 All Elements In Mrityu Hind Splash And What Women Want To Be F Loot Criminal Elements And Developments In The Country Point Mix Elements From The Co Via Am Doing This Bigg Boss Ki - Via Am Doing This Bigg Boss Ki - Via Am Doing This Bigg Boss Ki - Elements of Wave Today After 10 Minutes Electronic Salute Oo Element Subscribe Now To Receive New Updates Salute Ki A Trisha From The Kyun Unwanted Quality Ashtami Eliminated Ki Assam And Continue This Process Will Be Time Mrityu Synonymous To Be One 200 Guddu Element Cube And Development Will Be Removed Video Subscribe Doing With Us The Various Fields Eliminated Completed And Bone Density Election Committee Has 125 Salute Tube E Want Earrings And Long Give Someone Comes Into A K Under-14 Element Which Is This One Is Under-14 Element Which Is This One Is Under-14 Element Which Is This One Is Eliminated Member John And Underwear Importers on Anna Viewers 512 Value 12512 That Aunty Next Vihar How to Addison Itna Tak Years Element Oil Simply Remove It's Not Interested Next Week Left Witch Five Walk Soil of This Element Death Again Oil Filter Element Lucky Ring Road Map Hai Andhra Favorite Bun Gone City A Blind Limit 125g Fennel Oil Simply Leaves Remove 5a 25 Minutes Eliminated The Spiders Eliminated And What Is The Scientific You Know One Saw Damage Subscribe To A Report In Atm Songs Define Why Daily Tide In The River Ganges Near Me And Unlock Me 10 of elements in the few pointers highway-21 amazon is equal to and half pointers highway-21 amazon is equal to and half pointers highway-21 amazon is equal to and half inch plus to do subscribe the present one notification 212 e will do the operation continuously what do me loot criminal elements and us thumb back into a 200m writing To follow for ujjwal se zinc k plus apk data ki offer apq wle want next and governor remove the k development from active in the middle class element don't forget to subscribe also subscribe to remove the looks meter Sammit Hain Akshar Updated On Hai I Hope You Like This Video IF YOU LIKE PLEASE DON'T FORGET TO HIT LIKE BUTTON COMMENT AND SHARE WITH YOUR FRIENDS TO SUBSCRIBE TO R CHANNEL
|
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 |
997 |
hey guys welcome to a new video in today's video we're going to look at a leite code problem and the problem's name is find the town judge so in this question we are given n which represents the number of people and these people are labed from 1 through n and there is a rumor that one of these people is secretly the town judge if the town judge exists then these three rules must be satisfied for the town judge does not trust anyone everybody trusts the town judge and there is exact one person that satisfies these properties one and two so out of these n people given to us there is exactly one town judge if he's present if he is not present we have to return minus one so in the question we are also given a trust array which is a 2d array where every element represents a and b a ofi represents that a ofi trusts the person who is labeled as B ofi There is a trust between A ofi and B ofi it means a ofi trust B ofi and only the trust represented in the trust are given to us are the only trust relationship ship present there are no more trust relationships present and our task is to return the label of the Town judge if the town judge exists and can be identified else we have to return minus one so label of the Town judge is the label 1 through n if he's present that should be the label if he's not present we have to represent it as minus one now let's take the first example there are two persons and their labels are starting from one to n these are the two people and there is a trust between one and two so if this is one and this is two it says that a of I trust B of I a of I is 1 and B of I is 2 so a of I trust B of I and that is the only trust relationship present now we have to check if there is a town judge now let's take a look at the rules the town judge does not trust anyone so two does not trust anyone everybody trust the town judge everybody is the sense apart from the town judge everyone else so one trusts two so everyone is one so this condition is also satisfying and there is exactly one person and that one person is two so in this case two is your output which is the expected output here now let's take the second example there are three people they are 1 2 and three One Trust Three so there is a trust relationship between 1 and three two Trust Three there is a trust relationship between two and three now let's take a look at the rules the town judge trust nobody so there is a relationship between one and three and two and three does not trust one or two so three is our probable answer for the first rule everybody else trust the town judge everybody else is 1 and two and they both trust the town judge here so the second rule is also satisfying for three and there is exactly one person that satisfies the property three satisfies the property 1 and two so three is our answer which is matching our output here now let's take a look at these examples given to us so there are five people let's draw the five people there is a link between 1 and three there is a link between two and three there's a link between four and 1 there's a link between 5 and 3 there's a link between 5 and 1 and there's a link between five and four the five people are labeled from 1 to 5 now let's check the rules the town jet does not trust anybody so we have to check for the people those who don't have outgoing relationships because that person does not trust anybody there shouldn't be outgoing relationship you can see that three does not have any outgoing relationship so three satisfies rule one everybody trust the town judge so everybody in the sense apart from three 1 2 4 and 5 we have to check if 1 2 4 and 5 have outgoing relation ships to three you see one Trust Three here two Trust Three here four Trust Three here and five Trust Three here so the second rule is also satisfying for three and there is exactly one person that satisfies rule one and that is three so three is your town judge for this example now let's take the second example there are five people again so 1 to 4 2 to 4 3 to 2 3 to 4 to 2 and 5 to 4 now let's check for the three Roots the town judge does not trust anyone so we have to check for which note there is no out outgoing node one has a outgoing node here two has a outgoing node here three has a outgoing node here four has a outgoing node here five has outgoing node here so all of them have outgoing node so this condition is not satisfied by anyone so we return minus one as the output but the second rule is satisfy for person four because there's a relationship between 1 to 4 2 trust 4 3 TR 4 and 5 TR 4 this condition is satisfying but four trusts 22 so this condition shouldn't be satisfied for four because the town judge does not trust anyone there shouldn't be any outgoing node for the town judge but there is outgoing node for Town judge here so this is a wrong answer so none of the people are the town judge so we return minus one as the output as expected yeld so for every input given to us as n we have to check if for every n there is incoming and outgoing nodes and let's formulate the conditions using these the town judge trust nobody that means the town judge should have zero outgoing nodes and the second condition states that everybody trusts the town judge except from the town judge itself so the town judge should have exactly n minus one incoming nodes the person that satisfies these two condition will be the town judge now let's take a look at the court and see how we are forming the outgoing connections and incoming connections for every person so first we are doing a base check that if the length of the input rust given to us is less than n minus 1 then we return minus one because it means there is no Town judge so trust the relationships between two persons right if the number of relationship between two persons given inside the trust array is less than n minus one that is the total number of people minus one then it means there are not many relationships which are needed to form an output because the town judge should be trusted by everyone except for himself but if there are not enough trust we return minus one as the output now we create two arrays in degrees and out degrees which are having the size n + 1 we are taking n + having the size n + 1 we are taking n + having the size n + 1 we are taking n + 1 because n starts from 1 through n so these represent the labels of the people and there is no label as person zero so this will always be ignored now we iterate through the input array from left to right we take the first index so out degrees is at the zeroth index so if we take this particular trust so it is 1A 3 right and this has the index 0 and 1 so out degrees will be incremented for one because 1 plus three right so there is a relationship between 1 and 3 so it means one has a out degree so Inside Out degree array we take the zeroth element inside the current ARR is 1A 3 and for that we increment the index so this will become one and in degree means three is receiving One Trust relationship so inside ingree of error of one which is three we increment the count to one and now in the next iteration we take the second element is 2A 3 which is having 0er and one here so there is person two and there is person three two Trust Three so two has outgoing request so for two increment the count and three has a incoming request so increment the count of three so this becomes two and now we reach the end of the array and now like I said the town judge should have zero outgoing for rule one and for rule two the town judge should have nus one incoming connections and for this question n is equal to 3 so we iterate through the input from 1 to n which are the labels so we iterate for this part of the array for both the arrays using a single for Loop and we are checking if the in degrees of that I is equal to nus1 the second rule and the out degrees for I is equal to zero that is the first rule so we start our iterations from left to right for both the arrays we check for index one and whatever is empty will be filled with zero for index one incoming is equal to0 and outgoing is equal to 1 this condition is failing so we move forward the next iteration we consider index 2 so I is at two we check incoming is equal to Zer and outgoing is equal to 1 again the condition fails now we go to the next element I is equal to 3 now I is equal to 3 incoming is equal to 2 and outgoing is equal to 0 2 is equal to N - outgoing is equal to 0 2 is equal to N - outgoing is equal to 0 2 is equal to N - 1 right n is equal to 3 so 3 - 1 is 1 right n is equal to 3 so 3 - 1 is 1 right n is equal to 3 so 3 - 1 is equal 2 so this condition is satisfying and outgoing is equal to zero so this condition is also satisfying so we return I and what is the value of I is equal to 3 so 3 will be returned as output which is the expected output here for example two and if this condition is not satisfying it will come out and it will return minus one as our output because there is no Town judge so the time complexity of this approach is O of e where e is the length of the trust array that is the number of connections between the persons because here we are iterating through the input array trust and we also iterating through n so the time complexity may be bigger of e+ n time complexity may be bigger of e+ n time complexity may be bigger of e+ n but here we see e is less than n minus1 then we return minus1 which is constant time and in this part of the array it means that e is greater than or equal to n minus 1 so in the worst case e should be greater than n so in this case e is greater than n right so we can drop n so we can denote the ver time complexity as Big O of e so that is the time complexity Big O of e and the space complexity is Big O of n where n is the number of people given to us as input because we're using two 1D arrays to calculate the in degrees and out degrees that's it guys thank you for watching and I'll see you in the next video Lady
|
Find the Town Judge
|
find-the-town-judge
|
In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties **1** and **2**.
You are given an array `trust` where `trust[i] = [ai, bi]` representing that the person labeled `ai` trusts the person labeled `bi`. If a trust relationship does not exist in `trust` array, then such a trust relationship does not exist.
Return _the label of the town judge if the town judge exists and can be identified, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** n = 2, trust = \[\[1,2\]\]
**Output:** 2
**Example 2:**
**Input:** n = 3, trust = \[\[1,3\],\[2,3\]\]
**Output:** 3
**Example 3:**
**Input:** n = 3, trust = \[\[1,3\],\[2,3\],\[3,1\]\]
**Output:** -1
**Constraints:**
* `1 <= n <= 1000`
* `0 <= trust.length <= 104`
* `trust[i].length == 2`
* All the pairs of `trust` are **unique**.
* `ai != bi`
* `1 <= ai, bi <= n`
| null | null |
Easy
| null |
114 |
hello friends welcome to tech grants today's problem is flattened binary tree to linked list so here we are given a binary tree and we need to flatten it to a linked list in space so we don't need to create a linked list here only thing we need to do is we need to put everything towards the right pointer of the tree so if you see this so this tree will become something like this where you have one dot right is two dot right is three dot right is four not right is five dot right is six so it goes like uh your from one whatever was left it went towards right from two whatever was left it went to the right of the two so let us solve this problem if you see this particular problem what we need here is we need to move whatever is on the left hand side so if i have something on my left so and here if it is like this 3 so i need to move the left pointer to the right so what i need is i need to make one dot write is equals to 2 then i need to make one dot left equals to null and i need to go down and i need to make 2 dot right is equals to whatever right was there initially so whatever one dot right was there so i need to make one dot right i need to make one dot write as the value two dot uh one dot left will be null and one dot uh two dot right will be one dot right whatever previous one dot right was there so this will be one i can say previous so if i follow this logic then i will end up with one and on my right hand side of one will be two one dot left is null now then again two dot right will be equal to whatever previous one dot write was there which is equals to 3 and 2 dot left was already null or we can also make it as 2 dot left is equals to we can handle like this so this should be our output so we will take this same approach to solve this problem and we can recursively call for each of the subsequent node so what we will do here is that and since here it is previous node so we need to maybe keep a pointer for this so that we can store it somewhere so let us solve it we'll say if root is equal to null then you return from here since this is void i don't want to return anything i will take tree node if it is not equal to null then i need to keep track of the right side so this will be root dot right okay and whatever is on the left hand side i need to flatten that and i need to add it i need to make it as the right side of root so if there are multiple or it is like this true has multiple subtree so i need to flatten this again flatten the left side so i will flatten root dot left till i reach a place where we have only a simple subtree so that i can move two towards this side so once it is flattened then what i need to do is i need to make whatever my root dot right like here i said two dot right is equals to uh one dot right is equals to two so my root dot right is equals to uh my root dot left whatever my left side was there i will make it i will attach it to the right side of the root and i will make my root dot left as null root dot left is equals to null so i reached here i did this part now the next thing is i need to make two dot write is equals to one dot previous right now how do i know how many roots are there on the right hand side previously so for that what i can do is i can keep on going towards the right hand side till i find that the root is equals to null so while root dot right i will keep on going while root dot right is not equal to null i will make it as root is equals to root dot right i will keep on going towards right hand side till i find that root dot right is not equal to null once i reach at that particular point where the right hand side is null then what i will do is i will flatten the right hand side i can simply use the right variable here with whatever i have used here whatever i have stored here and i can say once these are flattened so i can say that the root dot write is equals to root dot right is equals to my right so this is nothing but this part so two dot right now my two dot right how i will be just two dot right uh once we have one and i have two here so my root is still at one so i need to go towards right so that i reach here at 2 so that is why i said 2 dot right is not null i will go towards the right of this after attaching the left subtree to the right hand side so once i have reached here then i will flatten the left hand side because three might also have some subtree of its own so if i see here rather than three it is five so five has another sub tree like six so i will flatten that and i will add towards the right hand side so root dot right which is at 2 now so 2 dot write will be equal to whatever the previous right hand side which i kept here so this will be 2 dot write is equals to 1 dot previous of right so this is how we will solve this problem finally the root that is left with us will be a flattened tree like this it will be a flat entry like this one two three so let us execute it and it is accepted and that's it so i hope the logic was clear the only trick in this problem is that you keep track of your right and then once you have flattened your left hand side you move the pointer towards the extreme right because you have attached the left side of the tree to your root and you need to move that root towards the or the current pointer towards the extreme right hand side so this one is the only trick in this particular problem and after that it was pretty straightforward so i hope you like the explanation do like share and subscribe to the channel this that's it for this video see you in the next one
|
Flatten Binary Tree to Linked List
|
flatten-binary-tree-to-linked-list
|
Given the `root` of a binary tree, flatten the tree into a "linked list ":
* The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
* The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.
**Example 1:**
**Input:** root = \[1,2,5,3,4,null,6\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
|
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
|
Linked List,Stack,Tree,Depth-First Search,Binary Tree
|
Medium
|
766,1796
|
94 |
before starting this video i'd love to thank releval for sponsoring this entire tree series did you know that companies like google apple starbucks are now hiring people without any degree or experience why because they believe that skills are more important than anything else the top companies in india like the top startups have also started following this trend by hiring through a platform which is relevant which is backed up by an academy all you have to do is to give the relevant test and based on your score this flat send your candidate profiles to 50 plus companies which includes cred upgrade vedanta and you can get selected for a job role within a week another amazing thing about relevel is it's absolutely free so please make sure you check out the links in the description hey everyone welcome back to the channel i hope you guys are doing extremely well so the previous video we did learn about how to find an inorder traversal of any given binary tree but that method did use recursion right what if in an interview the interviewer says uh tells you that you cannot use recursion then how will you solve this problem we're going to use an iterative uh technique in order to get the in-order traversal so let's to get the in-order traversal so let's to get the in-order traversal so let's just quickly write the inorder traversal for this particular tree or the inorder traversal you know what is in order is basically left and since it is in so the node or the root will be at the middle and after that something like the right will appear so over here this is where you start you go to the left 4 is the first node then you go to its root that's 2 then you go to the right so this is the right subtree and this right subtree again left root right so six five seven so the left portion is completed so you come back to root that's one then you go to the right that's three that is how you generally do left root right so this is going to be the in order traversal of this particular binary tree so you know recursive way right so if you remember in the recursion what we did was we moved to the left we printed and then we moved to right so basically what happened was we went to the left again we came to the left and the moment the left was complete then we printed that note basically i went to one then i went to two then i went to four and then i printed four and this one like at first the call was made for one it went to the left then two then it went to four and at the end the four was printed so these two and one were stored in the auxiliary stack space of recursion right auxiliary stack space of recursion over here in order to convert this into an iterative solution can i not use a stack which is created by me yes i can and i same this i store the similar thing like one two and i can just reuse them i think that makes absolute sense so let's do that so in order to have an iterative traversal just make sure you have a stack data structure okay so what's the stack data structure it's a lasting first out data structure that is what you will have and also have a node which is initialized to the root initially so currently you add the node one let's start the iteration now remember at every step of iteration you take whatever is at the node remember this if this is not null you take this and you put it into your stack okay once you have put it into your stack if there exists a left like even if that doesn't you just take the left of one so you'll take the left of one so in every iteration if the node is not null you'll take this and you'll put it into your stack and you'll move to the left similar to recursion where you move to the left now in the next iteration you come to two again same thing take it and put it into your stack and now it's time to move to the left similar to recursion i'll move to the left and the next iteration you come back again and you have a four again just store it and move to the next so move to the left so when you move to the left you will get null so in the next iteration when you come you see that there is a null remember if there is a null there is no need to move to the left any further so similar to recursion what you will do is you will just take out this element and you will print it so the first element for is indeed printed that is the inorder traversal right after that you know you have to move to the right if you remember a question left print right so you have to move to the right so who is force right do you have anything no so this guy again gets converted to null because force right is null and that is what you will make the node as iteration over again come back to the next iteration now when you come back to the next iteration you again have a null if you again have a null it's the same thing come back so you'll take this too and you'll print it so coming back right if it's a null if you remember the recursion code if it's a null you have to come back right so came back you have printed two right now since you've taken two and printed if you remember it was left root right so it's time to move to two's right what's two's right five so this is what i will do i'll take out the top of the stack i'll print it and now it's time to move to the right so i'll move to the right perfect in the next iteration when i come across i will take this five and i'll put this into the stack okay and at the same time i will move to the left of five because this five will wait and i'll move to the left that is six let's move to the six then the next iteration when i come back again i'll take this six and make it wait and i'll move to the left so when i move to the left it's a null again perfect if it's a null again in the next iteration what will happen it will say i'm a null so i will take the top of the stack and what is the top of the stack six so i'll print the six and what i will do is left print right so six is right is null again so i'll just reassign that to null so i've reassigned that to null perfect in the next iteration when i come across i again get a null so what i will do is i will take back the last guy 5 and i'll print it once i have printed it you're getting a pattern right first it was six then it was five so it is coming back it is backtracking for six then five is backtracking so since you've printed five so left root is printed time to go to the right so five's right is seven so this guy will change to seven so i'll come to the right now i'll come to seven perfect and the next iteration when i come back i see i have a seven so i'll take that and put into the stack and i will move to the left of 7 so i'll move to null and the next iteration when i come back i see a null if it's a null what i'll do is i'll take this 7 and i'll print it and since it is printed now it's time to move to the right seventh writer is null so i'll move to null perfect now the next iteration when i come across i again see a null now this moment when i see a null what happens very simple i take the topmost element again and that is what is printed once that is printed i will reassign this to the right of one because one is printed it's time to go to the right of one left print right so the right of one is nothing but three sub went to three and the next iteration when i come back i have a three so i go to the left of three yes in the next right so in the next iteration when i come back i have a three so just take it and put it into your stack and that's time that you change this to the left so the left is null in the next iteration when you come back you see there is a null so whatever is over here you just take it out and you print and you move to the right of three that's null perfect now the next iteration when you come back there is a null yes there is null and whenever you look at the stack it's empty so if it's empty you can break out saying there is no further notes to travel and at the end i can say i have actually printed my inorder traversal so if you draw the recursion tree you'll actually see the same stack trace being created so as usual the c plus code is on the left and the java code is on the right so what are we given we're given the root of the tree right and we take a stack empty stack i create a node which is our current or whatever you can call i can just assign it to root and i've declared a vector which stores my in order now if you remember what we did if the node is not null we took that node we put that into the stack and we moved to the left basically this creates my stack auxiliary stack trace and i move to the left perfect and at the same iteration if i end up getting to the else what does else means it's null right if it is null if you remember what did we do we just we will just make sure the stack is empty then it's over that means there are no nodes to travel or else whatever is at the top of the stack we take it okay and that will be my in order and after that since it is print and after that it's right i move to the right and the iteration goes over whenever the stack becomes empty i'll break out once i break out i'm going to return the inorder traversal what will be the time complexity guys it's very simple it's a big go of end traversal because i'm traversing all the notes what is the space complexity it's a big of n because i am using an auxiliary stack space now why the auxiliary space is b go off and imagine you're given a tree which just has left children so you'll push this then you'll push this they will push this and you'll go to the left every time you go to the left and you're going on to push on so if there is a skew tree which is just the left children you will end up taking b go off n space or if i just summarize this i can say it's a big go of height of the binary tree is the space complexity for storing the inorder traversal so i hope you've understood the entire explanation as well as the code just in case you did please make sure you like this video because it took a lot of efforts to make this entire tree series also if you wish you can definitely drop in a comment that will keep motivating me to make such further series also if you're new to this channel please do consider subscribing because i'm going to bring in such more series in the upcoming future as well with this let's wrap up this video let's speed in the next lecture bye
|
Binary Tree Inorder Traversal
|
binary-tree-inorder-traversal
|
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,3,2\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
98,144,145,173,230,272,285,758,799
|
336 |
thank you hey everybody this is Larry this is day 17 of the Lego day challenge hit the like button hit the Subscribe button drop me on Discord no extra coins really uh let me know what you think about today's form pattern drum appears hope you liked the intro I'm still in Dublin for maybe a day or two can't do the math so yeah I hope you enjoy it and yeah um let me know what you think uh okay today's problem is 336 palindrome pairs given a list of unique words return all the pairs of distinct indexes in the givenesso chat can count okay basically I press J or what's up I plus word sub J is apparently okay um okay so the 5 000 words and squares probably not going to cut it right um so I guess that my first instinct is just trying to figure out how to prune it in a good way right and of course you have stuff like uh s l s where you know uh one of the things my um my uh one of the things might be um you know more than half of the word is what I was trying to say sorry I'm thinking I think I'm talking but my mind is kind of thinking ahead a little bit uh and I don't know this one off my head just to be clear so it's not like I'm trying to rehearse it or whatever I'm just trying to think about the possibilities the other one you know this these kind of problems sometimes is just uh an exercise on reading the constraints and looking how to do them right so 300 to me seems a little bit maybe we can do something uh let's see because if 300 we check that means that for each word there are only 300 possibilities but then it's going to be 300 Square lookup so maybe that's not time it's not an improvement at all uh okay I think one thing that I'm tempted to do is some sort of you know prefix tree or something like this is the easy way to do prefix tree though like okay let's say we in the first case right let's say we have LLS how do we so you know there are two at least two uh pattern drums maybe I was wrong about the 300 Square maybe I take that back I was just thinking of like you know let's just say we have something like this my initial thought was just oh okay then now we have f e d c p a that's one but then maybe my DOT doesn't make sense okay maybe that is the way to do it but then the idea is okay how do you minimize it right like okay so here we know that we want to look for at least this but it could be other stuff as well right it could be like a g or something like that uh or and this would still work um like as in this could be the other thing though in this case you can maybe argue that it'll be just part of this which is that if you have this then now you reflect it the other way as we said and then you have g f b d c p a um and then but then the other thing is that we have to say AAA then now it could be like you know now this is the 300 Square case right where you have AAA you have to look for this and also this and this right so maybe that's not good enough um and I guess stuff like this as well um I still think the word less than 300 maybe is allow us to do something but this feels so familiar but I don't even know um it's five thousand square times 300 or 600 as it may be uh it's gonna be too slow am I spring silly am I doing too much uh let's see right um yeah because of this case I don't know how uh I don't know how I would do it per se foreign one two three four five I worry that I don't know if this is one of those problems where lead code is just silly with the test cases and they're not very strict or the opposite where they're very strict and I think that's um and some of it is because you know as an earlier problem so they might have done something like that uh and this becomes a guessing game um because then I need more sleep um okay let's first of all let's do a index lookup is equal to for index uh word and enumerate words lookup of word is Index right okay then now what well we do it again but now we want to look up things we've seen right can it can cut itself no it's this thing okay so then now it tries to see um what would the brute force be like I guess let's just do this thing even though I'm very worried about this um I guess if they're unique words they're only um I mean in the worst case each word can have 300 matches right so I guess that's 300 times 5000. I don't know all right let's see so basically we want okay so let's say we have this ABCD of G then now we just do basically um let's just say the first character right uh let's just say Alpha link um I'm just spending a lot of time trying to think how to do it but uh okay so we do something like this can L be zero no right it should be his yeah maybe hmm and then now we look at the first whatever and then we reverse it yeah maybe there's a better way of writing this uh okay and then now okay well we could do filtering in a couple of ways but if now uh is in lookup meaning if it's not then we don't even bother uh if now not in lookup contain your otherwise so we know that now exists in the lookup so then now we can do something like uh the word plus now uh base Oak I would just say a new word as you go to this if new word this is reversed basically if this is a palindrome then uh answer dot append um was it no uh look up off now and oh get away I think all the matters in this one index I know it will come up now right and then we just return answer did I just sort or anything no um is this good enough I guess you have to look up the other way too uh oh whoops foreign Okay so or look up of now is to go to index there's another one right another bug so okay so this works because the text a it goes A B C D and then it goes uh ABCD in the last one and then okay so LLS our next is a take from the back and then put in the front I guess okay fine uh then we just do now is you go to word um we want the last is that right we take that and then we put it in the front so but first we do the swing again well I guess I could just copy this foot foreign so what I'm banking on even though the complexity looks bad is that python strings are generally fast-ish because at least for compared to other python uh things but uh what is that one uh well in this case it would be one because I have to do uh just return the set but then it's still not why tell me why do so now it's taking the first thing right huh okay so that's good why is it not using LLS uh okay well let's see oh because I do continue here it's skipping this part okay I am not very smart uh well then I guess I just have to invest this I was hoping I don't need to Joker in the wrong answer for the last one wait empty string is possible okay so I guess I can change this I this is so silly I actually didn't see that example but okay let's give a quick submit I don't know if this is right or maybe it's probably right I don't know if it's fast enough okay well 900 days I actually missed a screenshot uh whoops um I mean what did I do I guess this is mostly the same or this one foreign but except for that now it is much uh more expensive why is it so slow what is the slow part of this I mean um there are a lot of slow Parts in this I just don't know which particular one that you know is not good oh well I know what to say but uh that's what I have for today I am very tired friends so let's stay with that let's go for the complexion really quickly um you know uh this first part is going to be all of let's just say and oops where n is the number of words it will say Elvis um time and space but this point is going to be off n again uh times o of L for this one uh and then each one of these is also o of L this is O of L this is uh this stuff is all uh this stuff so oh everything is all about so this is n times L Square um what did I say maybe I set that weird I meant n times L Square um is the time and the space is going to be just lookup I think and look up it's all L right yeah so wait I think Elvis number per word so this is actually because uh depending how you want to say it uh because the n words but each of those vertex out uh space as well so um the value I know it that's uh the space uh I guess that's also actually answer and answer can be at most um as we said it's going to be L Square n times L times output space no way now what we check their L Square possible answer for each one uh and each of the maybe that's not quite technically possible but I think that's actual space this is terrible I don't know how this works uh I don't know anyway that's all I have for today sorry for a little bit uh sketch uh hopefully I think tomorrow I'm back in New York or the day afterwards hopefully once brings solo back to regular uh we'll have regular uh her videos anyway uh stay good stay healthy took good mental health if y'all join the contest coming soon or whenever good luck and I'll see y'all later bye
|
Palindrome Pairs
|
palindrome-pairs
|
You are given a **0-indexed** array of **unique** strings `words`.
A **palindrome pair** is a pair of integers `(i, j)` such that:
* `0 <= i, j < words.length`,
* `i != j`, and
* `words[i] + words[j]` (the concatenation of the two strings) is a palindrome.
Return _an array of all the **palindrome pairs** of_ `words`.
**Example 1:**
**Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\]
**Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\]
**Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\]
**Example 2:**
**Input:** words = \[ "bat ", "tab ", "cat "\]
**Output:** \[\[0,1\],\[1,0\]\]
**Explanation:** The palindromes are \[ "battab ", "tabbat "\]
**Example 3:**
**Input:** words = \[ "a ", " "\]
**Output:** \[\[0,1\],\[1,0\]\]
**Explanation:** The palindromes are \[ "a ", "a "\]
**Constraints:**
* `1 <= words.length <= 5000`
* `0 <= words[i].length <= 300`
* `words[i]` consists of lowercase English letters.
| null |
Array,Hash Table,String,Trie
|
Hard
|
5,214,2237
|
143 |
hello welcome to my channel i'm here to do my 100 lego challenge today we have leeco 143 reorder list let's take a look at that uh question giving a singly language else l zero one two all the way n minus one and l n so we order this to l zero and one n minus one two n minus 2 and go on you may not modify the value by only changing the order only so the example in this single linked list is will be 1 2 3 4 but we get the beginning one ending one and then later beginning one later ending one by going left and right until they met each other so this is the right order one four two three and here will be one five two four and three this is the order by solving this problem you can have actually three pointers it look it sounds really hard but you can imagine a now we have had pointed to one and we can store the head.next which is this one and we can have another pointer go all the way to the end and the last one so we captured the last second one node and have one pointer in here so you see since we have one pointer in here one point in here and the beginning pointer here we can route that one dot next is equal to last right and dot next is equal to one dot next and also three dot next will be empty so now after that thing translated become one four and then two i will become one four two three so we have this freak beginning one and ending one uh in sort already in this right order now we have everything between unsorted so what we can do is now we have this one sorted and we just do a recursive uh order for this node starting after that and then that will be this solution you can see if we have one point two five point into two right it will looks like one five and an anything between two three four this is unsorted so you just recursive this for this list and then you will get the answer so in this list 1 5 and you have 2 4 3. so this is our order yeah this is a basic idea and now we can take a look at the code first we always start with the base case by checking hat not equal to no i mean equal to no then we don't do anything also hat dot next equal to no and um dot next this three case well don't need to do anything and now we have a few nodes we have a list no call last to capture the last no right here starting from hand let's know second last also equal to head and the note that capture temporary head dot next first we need to uh go through the whole entire list to find the last where is it in the same time moving the second life so now we want to look at where is three and four put them in place so while last dot next is not equal to no and we have to keep looping um second law it's always equal to last and then last equal to last dot next so last jump one step and second last is the previous last so now just keep looping until you see the end so after this while loop last and second last will be in place now what we can what can we do now is having had dot next equal to last like hat dot next equal to last that's what we want and last dot next equal to temp you can imaginate that the second last dot next should be no so we connect one to four to two in this one 1 4 and then connected 2 and also 3 connected to no now it's in right place in the right place what we can do we have 10 pointed to 2 right at the beginning so we just need to traver i mean keep recursive for this note which is we order the same no tem and then until the end of the right order so that's it for this question yeah it solved the problem cool and that's it for this question please let me know if you have any question comment below and i will get back to you as soon as possible otherwise i will see you in the next video bye
|
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
|
171 |
in this problem we have to convert a given excel column to a column number so here let's say if we are given a then we have to convert to 1 z then we have to convert to 26 then a comes so if a is given we will return 27 and so on so there was one another problem where we had done the reverse of this so we were given an integer value and we were converting it to the column number here it's the reverse thing and it's much more easier than the earlier problem and it has been asked a few times in microsoft interviews and also in a few other interviews so let's see how we can solve this so if you have converted let's say hexadecimal to a decimal then it should be very easy for you let's say you want to convert uh a9 so this is a hexadecimal we write it as 0xa9 but let's forget this part so how do we convert it we know that a is mapped to 10 and 9 is mapped to 9 so 9 multiplied by 16 raised to power 0 plus a multiplied by 16 raised to the power 1 and if we had more digits we would have multiplied that by 16 square and then 16 cube and so on so a is mapped to 10 so instead of a we can write 10 here so it's 160 plus 16 raised to the power 0 is 1 9 so it's 169 so in this case we will again be given a column number for example uh column numbers are a is mapped to 1 b is mapped to 2 all the way up to z which is mapped to 26. so here there is no zero it is starting from one so there is a offset of one then after z we have a so a till a z it will be again 26 characters so this is 27 and this is 52 then we will have ba to bz and again we will have 26 and all the way up to z8 to z so these are two digits so in two digits we will have 26 multiplied by 26 combinations first place can be any 26 characters again also so if we have let's say three digits then straight away we will know that at least we have 26 cross 26 plus 26 so this is the count of up to two digits then three digits start so conversion should be very similar to this you should remember this so let's say we want to convert column number bcd to a number so what will be this so just like this remember this picture even in decimal if we have let's say 123 what do we write 3 multiplied by 10 raised to the power 0 plus 2 multiplied by 10 raised to the power 1 plus this 1 multiplied by 10 square so here also d multiplied by 26 raised to the power 0 so whatever is the base here we have in hexadecimal we had 16 different digits in decimal we had 10 different digits in our case excel seed we have 26 different characters so whatever is the base so d multiplied by 26 s to the power 0 plus c multiplied by 26 raised to the power 1 plus b multiplied by 26 square so 26 square is 676 and b means 2 plus 26 multiplied by 3 plus this is 1 so just 4. so if you multiply this we have 2 and 14 plus 1 5 then 12 plus 1 13. so 1352 plus 78 plus 4 so this is 10 plus 4 14 carry 1 12 plus 1 13 carry 1 14. so you can verify that bcd the value the column number is 1434 so it's very simple let's write the code for this you can go through this problem a few more examples are there so first let's calculate the offset which is this character so we subtract the sky value of a so for a it will be 0 b will be 1 so we need to add 1 and then whatever was the result we multiply by 26 plus add the new digit and this is how we doing any conversion whether it is hexadecimal decimal binary or anything and return result so it works for this case let's try bcd what we saw in the example then we know that z is 26 then a is 27 a b so this would be good enough so our answer here is wrong let's see why realty 0 or d is equal to c minus a plus 1 sorry it's c that's why we calculated d here and now it matches so let's submit and the solution is accepted and we are here but if you run a few times you will get to 0 millisecond so what is the time complexity here we are doing one scan of this string so number of characters in the string so o of m the same thing you can write in java and python i don't think it's necessary here you can easily convert and the java solution is also accepted and here also we are right here in the top the same way you can write in python 3. so here we cannot directly add or subtract characters we have to first take the sky value of that so we will take over d or d will take the sky value and the python solution is also accepted
|
Excel Sheet Column Number
|
excel-sheet-column-number
|
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnTitle = "A "
**Output:** 1
**Example 2:**
**Input:** columnTitle = "AB "
**Output:** 28
**Example 3:**
**Input:** columnTitle = "ZY "
**Output:** 701
**Constraints:**
* `1 <= columnTitle.length <= 7`
* `columnTitle` consists only of uppercase English letters.
* `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
| null |
Math,String
|
Easy
|
168,2304
|
380 |
welcome to in this video the problem insert random so let's look into the problem so we need to design a data structure that supports all following operations in or one time so we need to insert a value in one time we need to remove a value involve one time and there is also a method called get random and we need to generate the random value in off one in constant time the probability of choosing the number should be same should be the same for all the given numbers so the example here is they will do set of operations like they will initialize the set and they will insert a value remove a value and when trying to remove the values insert two is not present we should be returning false in here and while inserting two it should be to true and if there is already one exists and if they are trying to insert again two already exist so we need to return false so basically we need to insert a value if the value is not present and written true the value is present don't insert the value and just return false similarly when removing the value if there is a value we need to remove the value and return true if there is no value present into written false and similarly to get random we need to return null if there are no numbers at all and if we need to just return a random number so how we do it so there are a couple of things we need to consider here because we need to do it in constant time so let's assume you will take an array and insert the elements Z 1 2 3 4 whatever number of elements they have processed but how do you find duplicator let's say they're trying to insert again one which is already exist how do you find it if you are using an array it would take often time to find if a value is present or not then we are missing the condition where the time should be of one constant time to insert or to remove so we won't be using an array have about using a set you can use a set and find out if the value is present or not raising set data contains method you can return false but so the caveat of using a set is when we are trying to get the random number let's say if us it has one two and three four we can't get a number by index so when you are using a set so ideally what we need to do is so we will use a hash map actually to hash maps where we will store the value in one map and the index in other map so we will have like B map and I map let's go ahead and initialize the required Maps the first operation would be the new randomized set so I will go ahead and initialize those hash maps which will hold the value and the index i map will initialize them here we know we initializes the maps what we need to do let's perform the insert operation all we need to do is we need to check if the value is present if it is present we are returning false if it's not present we will go ahead and add it to the map so if value map naught contains of Val I would just return rudin false else what would I would do is if it doesn't contain we need to add it to the map Oh valid comma the size of the map basically we are storing the index okay so sighs and now once you stored it so this becomes the index of the value remember when the map is empty the size would be zero when we are trying to insert one what the map would have like 1 comma 0 the value is 1 and the index is 0 now we need to refer this index in the index map and add it to their 0 and the value so that when we are trying to randomize it we know the index and we will get it from the index map instead of the value map i map dot could offer a map dot size alright map it doesn't matter we would return true so now the insert operation is done we will go ahead and perform the remove operation is almost the same if the value equal to null we would just return false now if we map brought contain key of Val we need to remove it and return true else we are returning false so how do we remove it so we know we need to remove the value both from the V map and the index map so what we will do is we will get the index first int index map dot get off value this will give us the index now we will go ahead and we map daughter to new off Val which removes it from the map I am AB dot remove off index which will remove it from the index map so here what happens is here we have in setter two values 1 into 1 index 0 to index 1 the I map will also have the same things we have 0 1 and 1 2 now let's say we are trying to remove one what happens is it goes here V map contains the value so it gets that index now index is equal to 0 we try to remove it from the V map and we try to remove it from the index map so we remove both the values now what we need to do is we need to replace this if there is only one element left in the map you need to replace this 0 with index with that particular last element because when we're trying to randomize and it gives us a value and if the index is not present in the index map it will throw an error so what we will do is we will get the tail element which is basically the size of thing let's say int tail element is equal to get our I map dot I am AB dot size which will get us the last element and after size is 1 at this point and it will get us to if this is not null we will go ahead and keep it in the index map as 2 and 0 and similarly we will keep it as it will be to 0 and we will replace this with 0 and 2 that's how we do it let's go ahead and do that and last element a map dot get of a map size if there is the last element to null then we will keep this index last element in this so that's how we will remove now coming to the random part it's pretty straightforward all we need to do is if the size is 0 let's say if there are no elements size to 0 we would just return minus 1 since we are returning an integer and not boolean value we will just figure it if B map dot size equal to 1 we would just return hi map dot 0 it index because there is only one element now if the size is bigger we will initialize a random or is continued random we will generate the index random index inte R and index next in of the size of T V map now we got the random integer holding today's return I'll not get off and that's it so let's go ahead and run it out there is a type of here okay contains key note contains actually I don't H an integer I don't have to check for no value okay sorry when I'm trying to get its immunity chair if you look into the operation so then sessions take off one time all we are doing is if it contains we are written in false or we are adding it to the value we are not reversing anything similarly they remove if it doesn't contains we are just returning the false if it contains what we are doing is we are just removing it from both the V map and I map and we are so this whole operation will be one unit of operation and we are not looping through the map or anything so this will take one and similarly the random will also take just a one time complexity I hope it's clear please do like and subscribe
|
Insert Delete GetRandom O(1)
|
insert-delete-getrandom-o1
|
Implement the `RandomizedSet` class:
* `RandomizedSet()` Initializes the `RandomizedSet` object.
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
* `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned.
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
**Example 1:**
**Input**
\[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\]
\[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\]
**Output**
\[null, true, false, true, 2, true, false, 2\]
**Explanation**
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
**Constraints:**
* `-231 <= val <= 231 - 1`
* At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`.
* There will be **at least one** element in the data structure when `getRandom` is called.
| null |
Array,Hash Table,Math,Design,Randomized
|
Medium
|
381
|
459 |
hello everyone welcome back here is vanamsen with another live coding session so if you are into go and you love a good challenge stick around because today we are diving uh into enchanting string manipulation problem from Lady code repeated substring pattern and if you are new to the channel hit the Subscribe button and join our coding Adventure so our mission today is quite a classic but always intriguing we are given a string and we got to figure out if it's formed by repeating a certain substring multiple times so sound simple right but their devil state in their details so for instance think about the string a b so we are given a b and it's clear and in daylight that it just a b repeated so a b uh twice so uh twice will be a b and this is a substance but what about uh a b a so no repeated substring there and if we try for example a or a B so it will not form our a b a uh yeah and you can see it and so we output here fourth and here we output uh true yeah true so now when we understand the problem let's dive into implementation we are going to solve it using two approaches one straightforward and one more elegant so all right let's jump into first solution a straightforward approach could be looping through possible substring and checking for repetition so we'll start by getting the length of our string and then a trick here is to iterate only up to half of the string length and anything beyond that and it's impossible for any such string to form the original string so let's implement it and will be Len s and 4i 1. less than n divided by 2 increment and if modulo I zero substring will be S to I and Builder string Builder 4 J 0 J less and divided by i j increment and Builder right string substring and if Builder string is s return true and if we iterate to the half return Force as simple as this for each length if our main string length is divisible by it we create our substring and instead of usual concatenation we are going to use go string builder for more efficiency so let's run our code for test cases yeah all good so now we can submit to verify it's also working for unsynthesis cases and as you can see our implementation it's not very fast so we beat just 70 with respect to memory and also 24 with respect to run them and the core idea behind this approach is to find the smallest a piece of our string and check if repeating it can recreate our original string a bit like finding the smallest building block and think if it makes up the whole structure and now let's dive into approach two so now hold your has we are about to explore a slicky method so imagine solving this in just a couple of lines of code exactly two so the trick double up the string and look for the original string within it and if I found we got our repeating substring and yeah so this will be the elegant and efficient implementation so double S Plus s and return string contains tablet 1 length WS minus 1 and compare it with s and let's run it just two lines of code and will it work yeah it's working for our given test case so now let's run it for unsynthesis cases to compare with approach one so as you can see our implementation now is much faster so we beat 77 with respect to the runtime and also 67 with respect to memory so as you can see it's quite significant improvement over the first approach so I'm running it one more time so as you can see it's quite uh yeah constant so five six milliseconds I think I have even a better score before but uh yeah we can rerun so yeah it's probably a different set or something now it's two milliseconds so really fast and faster than approach one and approach is a bit magical so isn't it by doubling the string and searching inside we are cleverly checking all potential repeating combination without re sorting to uh complex Loops So It's Tricky idea but a quite efficient and elegant and now if go isn't your uh only love I got you covered so head up to the description below for implementation in Python Ross C plus and more and dive deep compare contrast and elevate your coding game and let's wrap up for today's session if you had any aha moment or just enjoyed coding along don't forget to hit the like button share your thoughts question or your own solution in the comments and let's keep this community buzzing with ideas and Innovation and until next time keep practicing and happy coding
|
Repeated Substring Pattern
|
repeated-substring-pattern
|
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
**Example 1:**
**Input:** s = "abab "
**Output:** true
**Explanation:** It is the substring "ab " twice.
**Example 2:**
**Input:** s = "aba "
**Output:** false
**Example 3:**
**Input:** s = "abcabcabcabc "
**Output:** true
**Explanation:** It is the substring "abc " four times or the substring "abcabc " twice.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
| null |
String,String Matching
|
Easy
|
28,686
|
225 |
hey guys welcome back to helper function in this video we will discuss another popular interview question implement stack using queues so the problem statement says that we need to implement the following operations of a stack using queues push x that will push element x onto the stack pop that removes the element from top of the stack top that will get the top element of the stack and empty that will return whether the stack is empty or not now we need to do all of these using queues not stack let's say we are given with these set of instructions so we have to make a stack first we will push 1 then we will push 2 now for pop operation as for stack the top element should be deleted so we will delete 2 from this stack and now for the top as the top element of the stack is one we will return one so let's see how we will solve this using queues stack works on lifo model that is last in first out if i need to push a element into the stack it will be pushed at the top of the stack and also if i need to pop the element from the stack it will be popped from the top of the stack that is whichever element has been pushed into this stack lastly will be popped first but q works on fifo model that is first in first out if i need to push the element it will be pushed here but if i need to pop the element it will be popped from the front that is whichever element has been pushed first will be popped first let's say i have this stack with elements 1 2 3 4 and 5. now if i need to pop the elements from this stack my order will be 5 4 3 2 and 1. so here what we have to do is we have to make a stack using a queue so let's say if i need to achieve this fob sequence in a queue my queue should look like 5 4 3 2 and 1. so now if i perform pop operation in this queue the sequence will be 5 4 3 2 1. so thus we can see that if i need to achieve the same pop sequence the elements in my queue should be reverse of the elements in my stack let's say again if my stack has elements 1 2 3 the pop sequence should be 3 2 and 1. so i need to push elements in q in such a way that the q element should look like 3 2 1. and if i have achieved this then i can simply call q dot pop in order to pop the elements from the stack so let's see how we will do that let's say i have a stack and i want to push one into my stack so in queue what we will do is we will push 1 because the reverse of 1 is only 1. now let's say i need to push 2 in this stack this time if i push 2 in the queue this will not be the reverse of what we have in the stack that is what we want in q is 2 comma 1 not 1 comma 2. so how can we reverse that simple whenever we are pushing the element into the queue all the elements that are behind that we will pop those and will push again in the same queue so let's say at first we will have one and two i am pushing 2 so what i will do is we will pop the elements from this queue so at first one will be popped and we will push this element in the same queue thus one will come here and we will have 2 and 1. so let's say 2 and 1 is achieved and now i need to push 3 in this stack so again what we will do is i have 2 and 1 so i will push 3 and now i will pop all the elements before 3 and again will push in the same queue so first 2 will be popped and we will push 2 here and then 1 will be popped and we will push 1 here thus it will become 3 to 1. again let's say i need to push 4 so again this time we will have same kinds of operation we have 3 2 1 and now we will push 4 and now we will delete all these elements and again we'll push in the same queue so first 3 will get here then 2 will get here and at last 1 will be here so what we have in our queue will be 4 3 2 1. now let's say if i want to pop the elements from the stack so we can simply use q dot pop and the sequence will be same as this step that is 4 3 2 1. so in this way we can achieve a stack using a queue now the push operations here requires order of end time because every time we will be pushing element in the queue we have to remove all the previous elements and insert it into the queue again so this will require order of n time the pop operations requires of one time because we need to simply call q dot pop now let's quickly look at the code we are given with four functions push pop top and empty and we need to write the code in that for that first we declared a queue now for the push operation as explained in the solution we will first push this element x into the queue and after that for all the remaining rest element that is whatever will be the size of the queue we will take it minus 1 and we will pop all this element from the front that is let's say my queue has elements as one two and three and now i am pushing element four so my for loop will work from one to three and every time i will push the front element of the queue that is at first one will be pushed into this queue and one gets popped out again two will be pushed in this queue and two gets popped out and at last three will be pushed into this queue and three will be popped out thus my q elements will be 4 1 2 3. now for the pop operation we need to also return the element that we have popped so q dot front will represent the element that we have popped so we will take that in a variable and simply perform q dot pop operation and at last we will return k for the top element we will simply return q dot front and for empty if my queue is empty then the stack will also be empty so we will simply return q dot empty so this was all about this problem the overall complexity of this problem would be o of n because for the push operation we required order of n time i put the problem link in the description so you can go and solve it if any doubts or suggestion please write in the comment and if not subscribed to the channel yet then please do that thank you so much for watching
|
Implement Stack using Queues
|
implement-stack-using-queues
|
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`).
Implement the `MyStack` class:
* `void push(int x)` Pushes element x to the top of the stack.
* `int pop()` Removes the element on the top of the stack and returns it.
* `int top()` Returns the element on the top of the stack.
* `boolean empty()` Returns `true` if the stack is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid.
* Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
**Example 1:**
**Input**
\[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 2, 2, false\]
**Explanation**
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `top`, and `empty`.
* All the calls to `pop` and `top` are valid.
**Follow-up:** Can you implement the stack using only one queue?
| null |
Stack,Design,Queue
|
Easy
|
232
|
73 |
hello everyone my name is alvro and in this video i will be solving another problem from the blind lead code 75 problems list today i will be doing problem number 73 which is called set matrix zeros and i think this is a fairly tricky problem in one of the approaches that we're going to discuss in this problem so yeah definitely a problem that you can find in a interview so let's get to read the problem statement and let's get to programming so the problem statement says given an m by n integer matrix if an element is zero set its entire row and column to zeros you must do it in place so in place means that we're going to be modifying the original input which is matrix which is a 2d list of integers and we're not going to return anything so let's see example one so example one we only have one entry which is a zero right here and then we have the output corresponding to this so that makes sense because the row with index one is the only row that has zeros and the column with index one is the only column that has zeros in example two the only row that has zeros is the row with index zero and the columns that have zero are this one and this one which are the columns with index 0 and the column with index 3. so this and this are set to zero okay so now i'm going to discuss how to do the problems so if you want to try these by yourself as usual the link of the problem is in the description and that will be the right moment to pause the video so let's get to it so there's going to be two approaches that we're going to do the first one is going to be less efficient space complexity wise and i'm going to do that first because i think it's a little bit more intuitive and after that what we can do is just modify that approach so that it's more space efficient so let's get to the first one so the main idea here like it says it's if an element is zero set its entire row and columns to zeros so how are we going to determine whether a row or a column must be set to zeros so the idea here is that we can create two storage systems we can use a set i said will probably be pretty good for this problem we can create two sets that will represent the indices of the rows that must equal zero and the indices of the columns that must equal zero so whenever we loop through the entire matrix right in this case for example we encounter a zero and this zero right here is located at row one in column one so in the set of rows right we will enter a one and in the set of columns we will enter one as well and then after that simply what we do is we explore what rows and what sets are stored in those and then we set all those and all those rows and sets equal to zero for example 2 for example right only the first row so the row with index 0 has zeros so then the set of rows will only have a 0 in it but the column set will have a zero and a three because the column with index zero and the column with index three has zeros so let's get to code it so we have um rows to zero as this and then columns to zero is this so we can simply loop through the matrix and then if the current element that we are looking at is a zero that means that row uh in that column must be set to zero so i represents the rows and j represents the columns in this case okay so we have taken care of storing of traversing the entire matrix and knowing which rows and which columns must be set to zero now let's loop through the rows so for each eye and rows to zero i'm gonna add a little space here just for readability so here we know that row must be set to zero so every column in that row must equal zero so for j in range length of matrix sub zero right because let's look at example two since this dimension and this dimension are different length of matrix zero here is 4 which is the number of columns and i is the row that you're at so we're going to loop through a range that's length of matrix of zero long and then we do the same thing with columns in this case the number of entries in a column is equal to the number of rows so for any problem that would be length of matrix here we can see that the length of matrix is 3 because there are three rows which makes sense because each column has three entries and that approach should work okay there you go you know a little bit uh inconsistent with times but the point is that this solution um is one of the most efficient time wise but not really space complexity wise i've tested it before as well so don't worry too much about these runtimes as i said before they're pretty inconsistent as you saw now it's like in the top 88.42 percentile 88.42 percentile 88.42 percentile but yeah so what is the runtime complexity of this problem uh the runtime complexity of this problem is big o of m times n where m is the number of rows and n is the number of columns because we traverse every single element of the matrix at least once and then what is the space time complexity so let's think about it so what would the worst case scenario be storage wise here the worst case scenario will be that every single row in every single column right has at least one zero meaning that rows to zero will have m elements and calls to zero will have n elements remember that sets um have unique elements so at most they'll have m and n respectively so in the worst case scenario we will have m plus n elements stored in memory therefore the spacetime complexity of this solution is big o of m plus n now as i said before in the beginning of the video there is a more space efficient approach and if you want if you came up with this solution by yourself and now want to try to optimize it space complexity wise um now be the time to stop the video and think about it and try yourself okay so let's discuss how to do that so in the original approach that we used right we're using sets to determine what row and what column we must set to zero but that uses extra space so the question to ask is okay is there a way that we can modify the original input so that we can see the input and be like okay well this row must be set to zero or this column must be set to zero and the answer to the to that question is yes there is so how do we do that so the main idea here is that whenever we encounter a column right or sorry an entry that is equal to zero we can set the first column and the first row for that um sorry the first so if this is that like if this is a column i uh sorry a row i and column j then we can set the first entry at that column and in that row equal to zero those will be the markers right just like the sets here were our markers and after that when we modify we simply look at whether we look element by element and then we check whether the first element in that column is equal to zero and whether that element uh whether that entry in the row is equal to zero or not whether the first sorry the first entry in that row is equal to zero or not so let's look at example two for example right um actually let's do example one and then example two because there's an exception to this rule that i'll explain in a bit so here um we traverse through this row there's no zeros here and then we encounter a zero so what do we do so what we do is we set the first element and that column to zero and the first row equal to zero and we just keep traversing so that would be the equivalent of doing the set um operations that we did here and after that it's our turn to go through the rows and the sets um i'm gonna explain in a bit why we do this but i'm just gonna go with it right now uh we're gonna start at the second row and the second column and from there uh we're gonna go beyond and after that we do the first row and the first column and example two will illustrate while we do that so here we start at zero and in this like at any and any given sorry at any given location the matrix that we explore we check whether the first row and the first column is equal to zero since that's the case we set it equal to zero it was already zero so no problem with it here we check whether the first column which is the one here or the first row is equal to zero uh the first element in the row is equal to zero and remember that we modified it so for this case it is a zero and then we go again in the second column because we will d we'll deal with these later uh we go with this and then we check that the first element in that column is a zero because we've modified it before so we modify this to zero and then none of these like neither this one or this one is a zero so why do we do the first row and the first column last so example two can illustrate why so let's suppose that we have process like everything that we need to process right in this case after we've done all the like the equivalent of the set operations these are the only zeros that we have set let's start with the approach that i've discussed previously so let's start with this right here we check whether the first element in the column or the first element in the row is zero they're not so we leave them the way they are similarly with this and now with the two here we set it equal to zero because while this one is not a zero this one is a zero so we set this equal to zero this one we compare with this and with this it's not a zero this is not a zero and then for this one is zero so we set it equal to zero now what would happen if we did the first row in the first column before if we do the first row right here we check the first row so we should we set this equal to zero and then we set this equal to zero right and then we set this equal to zero and if you notice no matter what all this will always be zero because we've previously said every like that we set this equal to zero and we set this equal to zero already so that already does not match our output but this does not take care of everything as well so let me explain why so let's look at the cases for the second row and the second column i think this might be a little bit easy to easier to illustrate what we're going to do now so i'm going to delete this code okay so cases for the second column and the second row so none must be zeros okay then another case is that second column must be zeros and the other one isn't the other cases the second row must be zeros but the other one isn't and then both are zeros so how do we know uh i don't know if it's i don't know if the e files uh the o whatever um so what happens when none are zeros that means that neither the first entry in the second column is a zero or the first entry in the second row is a zero so the first entry in the second column let's see the first entry in the second row that will be this is not equal to zero or the first entry in the second column and sorry there you go so that's what happens there when this happens we have found that the second column must be zero so if the second column must be zeros that means that the first entry in the second column is equal to zero for this one this would be the case right and for this one this is a case and now you'll see why the first column in the first row is a special case in this case right we have two different entries in the matrix where we can just check so we check this one or this one but in the case of the first row in the first column they both share the same one right like the first entry in the first row is the same entry as the first entry in the first column right it's this one right here therefore we only have one entry in the matrix that can either be a zero or a non-zero be a zero or a non-zero be a zero or a non-zero to handle four diff four different cases but that's not possible right because we only have two possibilities either one is a zero or one is not so we must create another variable in this case we're going to choose the column that represents whether the first column must be set to zeros or not so we can create a boolean flag four is the so is the column a zero that way we will have two different things to look to just like we did in the second column and the second row because if we only focused on one right the ent the entry can either be a zero or a non-zero element or a non-zero element or a non-zero element but because we only have one possible element there's only two possible cases that we can cover at most but we need four that's why we create the boolean flag here so let's get started with it so is column zero we'll set it equal to false in the beginning and then we can just look through the to the matrix so for i in range um let's say length of matrix oops sorry for j in range oh um this is another special thing is because we are gonna keep track of the columns right here right um uh with a flag we don't need to loop through these with um with a for loop with the inner for loop so we're going to start at index 1 for the columns and once again remember that matrix of zero represents the lengths of the rows and length of matrix represents the lengths of the columns so when do we want to set the columns equal to zero well we want to set them equal to zero right whenever we encounter the first element of a row that's equal to 0. so that would be if matrix sub i sub 0 is equal to 0 then is column 0 equal to true and then here we simply do if matrix of i sub j is equal to zero then what we do is we set the first element in that column and the first element in that row equal to zero so matrix sub i sub zero so the first element in that row equal to zero and the first element in that column equal to zero and that handles the equivalent of the set operations that we were doing before that handles the indicators now we're going to start modifying um the second row and the second column and beyond so for i and range one length of matrix and for j and range one length oh this should be yes it should be for iron range yes okay sorry i was getting a little bit mixed with the ranges and the lengths and there you go oh i can't type today great okay so if for the current element right so if matrix ah sorry so here we're looping through like any element so if the first element in that column or the first element in that row is equal to zero then we set that element equal to a 0. so if matrix sub i sub 0 is equal to 0 or matrix sub 0 sub j is equal to zero and we set that element equal to a zero now we can handle the first row like we mentioned before right the boolean flag takes care of the zeros just like matrix like in the second column right in this example right here the second column is taken care by matrix sub zero sub one the column will be taken care of by the boolean flag and the row will be taken care of by entry matrix of zero sub zero you could do it backwards as well as you want just make sure that you loop through the ranges properly okay so here let's do the rows first so if matrix sub zero sub the rows first so if matrix sub zero is equal to zero so this is if the rows if first row must be set to zero then what we do is we loop through all the entries on that so for j and range length of matrix sub zero sub j equal to zero and then if the first column must be set to zero and that is determined by the boolean flag right here so if is call zero is equal to true and i know that the equals true is not necessary but i think it might help with readability for some viewers so i'll just leave it there for i in range length of matrix because remember we're going through columns so we're going through the length of the matrix sub i sub 0 is equal to 0. and this approach should work as well it doesn't uh okay so let's see uh the small mistake that we have here so for j and range okay for i and range length of matrix i sub zero sub j okay should be fine um okay all right i'm back um yeah i just made a small mistake here with um with this right here i set it equal to like this before this is the only modification that we need to do just a small error and there you go now this should work um just if you get enough tries it'll eventually you'll see how the memory is just a little bit better so what is the runtime complexity of this problem so the runtime complexity of this problem is once again o of m times n because we run through every single entry of the matrix at least once and now what is the spacetime complexity of this problem well the only thing that we're storing is just one boolean variable and that is of one space therefore the space complexity of this solution is big o of one so yeah that will be the end of the video um i'll hear you have some code if you wanna take a look at it just pause the video and scroll through but yes uh this is the end of the video i hope you enjoyed it and you find that you found it helpful uh this problem can be a bit tricky especially the second approach so take your time to digest it and yeah thank you very much for watching and bye
|
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
|
88 |
Hi, so this is our first problem, it is sorted and this is the first question of 150 questions and it is marked easy. Okay, so basically, give us numbers in this, two, we have arranged in this. Okay Nav and Two both are sorted. Okay, in this we have to print the final result. We have to print the result of these which should be sorted. Okay, 1 2 3 5 and 6. Okay, so basically we have to solve this. The approach that we have is that we basically keep three pointers with us aa j and k so these are three points okay the value of aa basically what should be the value of aa we should have m -1 Okay and what is m and n m -1 Okay and what is m and n m -1 Okay and what is m and n m represent whatever value we have in non zero we have that is ok whatever non zero elements we have in the first array and in this whatever non zero elements we have in this then in the second array then the value of i. We will have m -1, the value of j, We will have m -1, the value of j, We will have m -1, the value of j, we will keep n-1, we will have the value of k, the we will keep n-1, we will have the value of k, the length of the final array A will be formed, so that comes out to be m + n -1, now we will solve this. + n -1, now we will solve this. + n -1, now we will solve this. In that, it is clear to us that we have set our index here, this is i and here the second index we have set is j, in this we have compared both the elements a and both the arrays from end to end. Will start doing will do as long as i and j we have greater than equal to 0 Okay now again there is no doubt that if a for example here we see that a number one's The eighth element is smaller than the six we have, so in this scenario, the last value we have will be six, okay and as soon as this six comes, this pointer we have will be our Near will come here, okay j minus, we will have here, like wise, now the comparison we will have between five and three, again, the j that we have, we will have minus hoke At this point, we will get OK, two will come. Now again we will have a comparison of two and three, so what will happen in this scenario, we will have three and we will have a minus. Will reach the point, ok, again then two and two will be compared, then two will come, then again two will come and finally one will come. Now to solve this, a simple code is written here, ok again as I said and After taking the value of j, taking the value of k while j is gr = value of k while j is gr = value of k while j is gr = 0 i > e 0 and if numbers of two i is greater than 0 i > e 0 and if numbers of two i is greater than 0 i > e 0 and if numbers of two i is greater than numbers of two of j then we will keep the value of k in numbers of one and other wise. We will put this as j and like we did, after this we will decrement the value of k and also decrement the value of a and in this else loop we will decrement the value of k and also decrement the value of j. So or this code run fine its time of complexity is easy there is not much to explain there is nothing here if you like this video please don't forget to share and subscribe thank you
|
Merge Sorted Array
|
merge-sorted-array
|
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
|
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
|
Array,Two Pointers,Sorting
|
Easy
|
21,1019,1028
|
1,180 |
uh so this questions come sub string with only one distinct letter so you giv str s and then basically um the option you have are consider same dat and then you want to count how many time it uh it occurs so uh let's look at this so a you can have I mean when you add this position you have a when you at this position you have a but you can also have a itself and this one you have a or you can have a for the first 2 a or the second a A or another one a individual a right so just keep traversing this and you will see there is a um there's a problem you need to store the number of combination so you can create in Array so INR actually help you to see that how many uh element you have so first thing first like we need to initialize a DP array so this in Array so DP array DP is zero it's going to be one and we starting from the first index I mean sorry uh index one we're starting from index one this is because this letter is definitely distinct and we don't need to count right so this will be initialize and then DP every single DPI is going to be based on the previous one if they are the same right if they are the same you say DPI equal to DPI minus one I minus one + one right you add the one I minus one + one right you add the one I minus one + one right you add the one combination so this would be one this will be two this will be three so just look at this three so what are the uh what are the number of subing uh for this it's going to be what 1 + 2+ 3 is going to be six right so six 1 + 2+ 3 is going to be six right so six 1 + 2+ 3 is going to be six right so six will be the answer if s equal to a AA right so if they are not the same I need to reset the DPI to one so uh later on we will you know uh on the next iteration we based on this one if play the same right and later on uh end we just need to return the Su of su of DP so yeah pretty much this is the solution so I'm put DP new in and then the sizes will to be S lens plus one and initial DP 0 = be S lens plus one and initial DP 0 = be S lens plus one and initial DP 0 = one so in I = one I less than is the one so in I = one I less than is the one so in I = one I less than is the lens i++ and then if they are the same IUS one I B on L equal DP IUS one + IUS one I B on L equal DP IUS one + IUS one I B on L equal DP IUS one + one and else I re initialize my DP I one so this will be it right so after I finish I just return Aras the sord uh sorry AR Str the dp. sum so this will take all of value so sum is actually a trick yeah so here we go so this is PR for time and space this is space all of them this is time also all of them right so if you don't want to use a DP you can use a counter so I'm going to just rewrite this so in count equal to one total equal to one as well so I will make sure I started from index one and then I going to do the same thing so if is TR it I one I inclement my counter right else I reive my count one and every single iteration I plus equal to count so this will be like a trick that you keep adding the current frequency sorry the current combination for the uh for the return number of substring so just a little bit Improvement the space is constant time still all of them so if you still question a common I see you next time bye
|
Count Substrings with Only One Distinct Letter
|
game-play-analysis-ii
|
Given a string `s`, return _the number of substrings that have only **one distinct** letter_.
**Example 1:**
**Input:** s = "aaaba "
**Output:** 8
**Explanation:** The substrings with one distinct letter are "aaa ", "aa ", "a ", "b ".
"aaa " occurs 1 time.
"aa " occurs 2 times.
"a " occurs 4 times.
"b " occurs 1 time.
So the answer is 1 + 2 + 4 + 1 = 8.
**Example 2:**
**Input:** s = "aaaaaaaaaa "
**Output:** 55
**Constraints:**
* `1 <= s.length <= 1000`
* `s[i]` consists of only lowercase English letters.
| null |
Database
|
Easy
|
1179,1181
|
901 |
let's see the problem 901 unless talks and desire algorithm that clock collects daily price quotes for some stock and Returns the span of the Stock's price for the current day the span of the Stock's price in one day is the maximum number of the constructive days starting from that state and going backward for we re which the stock price was less than or equal to the price of the day for example if the price is of the stock in the last four days is seven two one two and the price of the stock today is two then the span of today is 4 because starting from today the price of the stock was less than or equal to for constructive days that means the q12 is in a span also if the price of the stock in the last four days is seven thirty four one two and the price of the stock today is 8. then the span of today is 3 because starting from today the price of the stock was less than or equal to eight first we constructive that this problem can convert to for an element or find the closest elements in the left which is greater than it that means for example in the example the 7212 and its value is 2. we can find the closest Elements which is larger than it is the seven and the index is zero and today's index is 4. so we can use the four minus zero and without the stand is the fourth so how to find the closest elements which is greater than it and in the left we can use monotonic stagger to solve this problem augmentatonica stick first is a stick so he's first thing blast out then it guarantees the monotonic city over the element in it at any time so every time you add the elements first you need to remove some elements from it for example foreign decreasing stake every time when you add the element first you need to remove all the admined which is Which is less than a current element in the stack then add the element in this way we can find the closest and closest Elements which is where which is greater than it in the left for example uh we use this example one The 100 eighth 16 17 16. 75 and 85. this sequence uh because we need to use the index to calculate the step so we use the index as the elements of the monotonic stake uh for convenience uh in here we also write the values first when we travels for the index 0. uh the state is amped so we just add the index value to the stake then let's take current is zero the index is there another values is 100 first which travels to the next one and there are no elements is less than 80. in the stake so we just add the index 1 to the stake then the index become 1 2 but 0 1 and the value is 180 then we travel to the index 2. and the value is 6 to 16. and there is still no elements is less than 80 in the state so we just add the index 2 to the state uh the index is 0 1 and 2 and the values is 80 but 180 and 60. then we travel to the index 3. uh this time we find the yeah a value 60 in the state that is less than 70. so we first needed to remove it from the stack then add the index 3 into the stick so after that the steak become fear in index become zero one and two but zero one and three and the value is 180 and 70. then travels to the index 4. the value is 60. there is no elements is rather less than 60 in the state so just add the other index the index is 0 1. 3 and 4. and the values 100 and 80 and the 70. and the 60. then we travel to the index fifth five uh the values seven three five and we found that two elements 70 at a 60 is less than 75 in a stack so we need to remove the two elements from the stake then add a index so let's become 0 1 and 5. the value is 100 and 80 and 75 last we traveled to the index six uh and found the last two elements is less than each and the index become real and F6 the value is one hundred and uh 85 and every time when I add an element the closest Elements which is greater than it in the left is just the top element in the stake so we can at the same time calculate the span when the Windows tag is amped uh we regard the index as the negative one so first up the index zero this n was one and the one in X1 is also what three plus two is one three is three minus one is two and four six four minus three is one and this fifth is 5 is five index the Spanish five minutes wise four and last index and the Spanish six minutes zero is six so we can according this process to write the code and if in this problem okay first we need to initial a stack we initial in the in construct and in this problem it can not direct give us the sequence but give us the elements in the next method one by one so we need to at least to store the installer element then we implement the mass of the next uh every time when we get her price uh we need to compile it with the top element in the stake in your Loop uh first the state code would not be amped and when the top element in the stack is less than the price less or you could we need to pop the element and then we can filter to calculated the result or the spelling is equal to the current index minus the top element in the state so current index is left side and minus the protect them Peak time Peak then we need to add the first add the index to the stake the index is the Justice the list size and we add a list we can add the value to the list then return the result that's how I thought least I want to find foreign when the style is amped we can use negative one as the at the index okay that's right thanks for watching
|
Online Stock Span
|
advantage-shuffle
|
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day.
The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
* For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days.
* Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days.
Implement the `StockSpanner` class:
* `StockSpanner()` Initializes the object of the class.
* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`.
**Example 1:**
**Input**
\[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\]
\[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\]
**Output**
\[null, 1, 1, 1, 2, 1, 4, 6\]
**Explanation**
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
**Constraints:**
* `1 <= price <= 105`
* At most `104` calls will be made to `next`.
| null |
Array,Greedy,Sorting
|
Medium
| null |
1,189 |
hello everyone in this lecture i am going to explain you about maximum number of balloons given a string text you want to use the characters of text to form as many instances of the word below as possible you can use each character in text at most once written the maximum number of instances that can be formed so here in this example one they given an l a e b o l cable so here in this input we need to find how many times the word baron is repeating so here it is showing we need to show only one time here in this example two in this from this what we need to analyze how many times balloon ward is repeating here it is repeating two times so the output was two and here example three they given lead code here balloon what was not repeating so not exist so we need to show zero so how can we do this yeah i will explain you clearly first we need to create variables and initialize with zero okay so here i created five variables b a l o n for that all variables i'm initializing the value zero and then for character ch string name text to character array switch ch case b here for case b if that b is equal to the elements which are present in this character array then we need to make pre-increment pre-increment pre-increment repeat this logic for other variables also for other characters also for a i am incrementing with a and then break and again for case l reincrementing with l and then break and again fervo pre-incrementing with o fervo pre-incrementing with o fervo pre-incrementing with o and then break okay and for case n again bring in pre-increment with n again bring in pre-increment with n again bring in pre-increment with n and here break so here in this written math dot min mass dot min here i'm mentioning go by two comma l by two because in this in that word o and l is repeating two times so that's why i mentioned in that way again math dot min here now i will mention ba comma n okay in this way we will see now check the program okay now i will run this code we'll check what will happen yeah accepted now i will submit this code yeah success so here simple first i created the first i created some variables b a l o n for that i initialized the value zero and here in this for loop i'm just converting that string to character array and then all elements stored in character ch and here i use which technique so here i mentioned this all variables and i keep a count if the elements are present given input if that are present then it will be shown how many times the word is repeating this is the logic so if you have any queries you can mention your doubts in commentary session and please do like and subscribe for more videos don't forget to click on bell icon thank you you
|
Maximum Number of Balloons
|
encode-number
|
Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only.
|
Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits.
|
Math,String,Bit Manipulation
|
Medium
|
1070
|
258 |
hello guys welcome back today we are going to understand the lead code question right and so let's understand today question we have is uh add digits right 250 uh 258 right and we are going to understand this question so to understand this question give me one second right what do we have to do actually okay so to understand this question what you have to do actually uh you have to understand uh the basic mathematics uh how to implement this question okay so the question is saying that we have uh we have to do add digits right and to do the add digits what we have to do we have to uh we have given a number num right and this number uh actually we are what we are doing we are repeating add all uh its digit until the result has only one digit right so we have to add its digits in into this number and until we find only one digit then we will return okay let's suppose what we are talking about we have n we have given is 38 in this first example so the process is what we have a three we have right in the first and then we have eight as another digit two digit we have given right if you do the sum what we are getting 1 well 11 right now we have uh two uh one two digits so what we will do will again we'll do the plus and we'll get what 1 plus 1 is 2 right means we have to make it one digit whatever the number we have given here that number we will make uh we will do add or add up these digits and until this digit is going to be what one in one digit right till that will do and what the last one digit is have that we have to return right what will we have other two one digit that we have to return I think you got the answer right uh how to do the implementation right so what we will do I will let's go to the browser right and then we will do the implementation here okay so to do that uh what we have to Let's Zoom the little bit okay so here what we can do we have given this number right so uh to do the implementation first of we have given number so if we have this number right num so what we'll do we will find its uh digit right let's suppose about uh digit we have given it is okay digit we have given this one right so this is it if given is let's suppose 0 right so what we will do here will make a while loop right we'll make a while loop and we'll say if num is what greater than what 0 if it is greater than 0 in this case what we'll do we have this digit right that we have taken we will do ah first plus equal to we'll add this number num and we'll take the reminder from where uh we'll taking by 10 okay whatever the reminder will come that is our digit let's suppose actually we are finding our this digit is not over your uh root digit you can say right so I will give the name root digit you will find here so now you understand your root digit right this one after this what we have to do we have num right now num from the num sorry we have we are taking modulus of here 10 and we will get our digits right now what we will do num by 10 will do and we'll get the answer right power will get our after dividing will get our one we will lost one digit now right after dividing now what we will do we'll check now we will check on here if our num is equal to 0 or and we will say and the digit we have write digit root we have if it is greater than what 9. suppose means we have num is equal to zero a digit is greater than root ah greater than what 9 means we have to do the same thing again right or we can say now we will update our digit right let me explain I will explain it like again okay don't worry mathematically then what will happen we will update our digit root now this digital would will start from what 0 the same thing we are going to do right after this we will return 0 sorry D not zero digit like this let me compile first and okay it's working so let me zoom out okay let me submit then I will explain it's working my phone it's working for me consistency is the key let's understand what the question is saying and what we are doing here okay so actually ah what we have given n we have given right and what we are doing we are adding these two number okay previously what I told you if n we have is uh 38 right what we are doing three plus eight we are doing and we are getting one again we will do one plus one and we will say two so two is our answer right so that's why n we have given right n is nothing whatever num right so if this number is given what we are taking a number digit root let's suppose this is digit root okay so digits we are get getting 0 right why we are taking so we will check if num is greater than uh zero let's suppose that we are taking num as a 38 so 38 is greater than the zero in this case what we will do digit we will update like what we'll do uh we'll take mode right we'll take 38 mode are 10 right next time what will happen now our Dr contains means root value is what 8 we have now what we will do we will take the num right num we have the num is what 38 right now our num is what we are getting 38 by 10 right so this will become 3.8 equal to right so this will become 3.8 equal to right so this will become 3.8 equal to 3. now Norm is 3 will now what will happen we'll check if num is 0 and this root digit is greater than 9. so in this case we will update what this case is not that so we will not go here right what we will do will come back to again here now is not now is still greater than 0 so the same code will come here again okay now the same process will follow for here so this is the first time first Loop when uh we'll check again we'll check uh digit root is now what we have will take and this is what we have eight we have previously right now we have to do eight plus actually right and whatever the number is what now three we have and we'll take what 10 right so if we are taking mod of three let's suppose mod of three uh by ten right it will become what it will become 3 it will give you three this value will give three actually okay this is nothing what about three so eight plus three is now what eleven correct now it is eleven but when we go to num and we'll divide what 10 what 3 by 10 will take Okay so this will become white Point by three so it will become zero right now next time num is what num is 0 right now is what 0 we have here as you can see zero point uh something we can say right we have so still now it is equal to zero so in this case what will happen we will come to here this point right and we will say the digit Roots right so we'll come to here actually we'll do the same thing we'll do divide again I write so we'll do we will come to here now equal to 0 digit is greater than this one so if this is greater than this one so now num is what num we are going to update so this is the second time right so now we are coming to this Loop right now our num we will update is 11 because what we have digit contains what eleven so now NM is 11. now dz2 is what TR is what d r is 0 now so this same process will follow again here what will happen Dr will become what again will start with what we will take a divide so it will become 1 initially next time the Dr will come so it will become what 1 plus 1 it is become 2 right and the num will become what 0 num will become first one and then it will become zero so first it will one and then it will become ah zero so when it becomes 0 so now it is what it will become 2 right digits so we have to return that to here I think you got me okay so if you have any doubt please bring me the comment box so uh you will understand okay thank you guys thank you for watching this video If you like this video please hit subscribe this channel so you will get more videos like this right so if you talk about the complexity right the complexity will come what we know this is a mathematical formula right and if we'll do the any implementation it will take off one time only right so the time complexity and space complete DC and SC will take expect is equal to one only okay if you uh want to do the Implement sorry if you want to do the implementation any other way it's very easy right so if you want to do the Sorting uh like reducing the code right what do you have to do just you no need to do these all things here what you will do you will take uh you can take a condition if condition and you can check right what we will check if our num is equal to what zero then we will return what 0 if the number if you will take modulo of 9 and equal to coming what 0. in this case we will return what 9 else what we will do will take the modulus of num and 9. whichever be the value will come that is our answer okay so let me take little space so we will look good like this you can say just we should online okay let's uh run this and submit this so this will work okay because we are taking modulo okay so if you want to do uh reduce this code you can what you can do we are taking first we are checking num zero right so we'll take this num this will take here directly we are here if num is what ah equal to zero in this way what we are returning see we are returning 0 right so we'll say if it is this one means we return 0. otherwise what we will return to return one right plus what we'll do this is the num minus 1 if we'll take the modulus of 9 that will be the same value whatever the value will come that we will return here okay we should work okay it's working thank you guys thank you for watching this video If you like this video please hit subscribe right for the time complex respect it will be of one right we have not take any Extra Spaces or any Loop right thank you guys thank you for watching this video
|
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
|
994 |
to do is um you can think of these directions as starting from the point of origin right so this will be negative one will be um a displacement to the left uh this would be right this will be down and this will be up so basically that is the idea i should think about right so the next thing we need to do is we need to have um we need to loop through and um we will be storing uh the all the rods and oranges in our dq and the format we'll be using is the cell location and then the time right so um so what we could do first is we are going to just do what i just said we are going to say for i in the range and the range is just going to be the length of the grid right length of the grid basically like when you're doing um when you're doing matrix questions right uh this is just a matrix right um they look a bit um the same right so we would say for so you could i have i j or you could have row and then column right so um for j in range and the range is just going to be the length of the grid and then um then at i like so right and we check the value in that specific cell right so we check if it is a rotten one and if it is we put it in our dq right so we say if grid if the current cell i and then j if i j if it is equal to 2 this is a rotten one so we can put it and for this we just put q dot append and um what you're going to do is just going to be i j and because we are starting off right this is the first pass we're just establishing all the rotten oranges before we can start modifying the ones close to them we just thought the number zero like so right so basically um basically that is we need to run through our queue and for that we just say while q like so q uh yeah spelling it correctly and then we um pop off the element from our queue from the left right from the left we know when we are adding them we add them to the right but when we are popping them off we're going to pop them from the left right so we could just do a bit of destructuring and we could say x y and time is going to be dec oh i like calling it um it's q right we assigned it to q right so q queue and what we want to do is we want to pop left like so right so we pop left um after we pop left we assign time to the result we assign time to the results and then uh we need to check that um we move in our directions but before we move on in that direction we move in our directions and we check that the value in the next in the cell to be considered is one before you can convert it to two and also that our directions are valid right imagine you're at position zero and you're starting and you try to move negative one to the left right you can't do that because that is out of bounds so we first make sure that um we're moving in directions that are within bounds and also that the grid in question has uh the cell in question has a one right so we could say if zero and zero is less than or equal to x plus uh our direction dx and um it's also less than the length of the grid we have to make sure it's in bounds remember and 0 is less than or equal to y plus the direction we're trying to move one right d y right and this is less than the length of the first element of the grid right length is grid and this is going to be x right the first element of the grid and what we have here is a y is a one right so we say grid is going to be x plus the direction we're moving in dx and um y plus the direction we're moving in y and this is going to be equal to 1 like so if this is the case right we need to put it in our q but you put it on the right side right and then we convert it into two right so we say q u and we append and what we what do we want to append the x the current x plus dx that's where we've moved in and the y coordinate is going to be y plus d y because that's where we moved in and the time is going to be because one cycle has passed this is the first cycle this is the second cycle or the minute i guess the using minute right so increase time by one like so and then finally what we do is we convert it into two right so we're just going to that cell into two because it has been made rotten right so we say x plus dx and um it's going to be y plus d y like so and this is going to be set to 2 like so that the next thing we need to do is now we need to go through our grid and check that we um ensure that we do not have any one left right like any of them is a one right so for that what we need to do is we just need to go through our entire grid and we don't need to rewrite that code because we already have something like that so we need to check if this is one and if this is one we just need to come here and um we need to return and what we want to return in this case is going to be they want a negative one right so after all this what you're supposed to do is just return uh the results of the number of um what are they called number of minutes right so basically that so what we need to do is um we need to make a couple of corrections first we need to make sure that when we are pending uh we wrap the various variables that will be passing into our queue and in um we wrap them right so we do that here and we also come and do the same um where we are pending also here we are putting we're increasing the the time by one and um where we are checking whether the value is one right so where we move our x and um our y and we also increase our time and we append it because it's going to be um converted right so yeah so basically that at that point and um another thing we need to do i forgot to write in the for loops and i copied the for loop so you should say for in range right we do that here and the next thing we i forgot to do is um here we have to get the direction the dx and di from the directions right so we should write this for dx dy in directions right and then we simply afterwards we run our code and if we run our code it's accepted and if we submit it is similarly going to be accepted the time complexity is going to be o of m plus n um the reason for this is because we actually go through every cell in our um we go through every cell in our array right and check um whether or not it is um whether or not it's a one and convert it into a two and um yeah basically that it's going to be o of uh m by n time and o of m by n naught at m by n space and time right so pretty straightforward in that case thank you for watching subscribe to the channel and i'll see you in the next video
|
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 |
687 |
hello and welcome back to the cracking Fang YouTube channel today we're solving lead code problem 687 longest uni value path given the root of a binary tree return the length of the longest path where each node in the path has the same value this path may or may not pass through the root the length of the path between two nodes is represented by the number of edges between them let's look at some examples we have this tree 555 411 so what is the longest path obviously we can see that it's going to be these three fives here cuz this is all One path and all of them are five there's really no other path there is just the one node one the one node um one here but we can't connect them because of the four so that means that can't be the longest path this four is on its own because this is a one this is a five so the only one is this five here uh similar here we have the tree 1 4 55 so the five two five are together but because there a one obviously we can't link them same with um this four here obviously we can't go this way um but we actually can link these four because you know this one is the sub tree of this is also the sub tree and then we can link it in the parent so again this is one of those questions where it's really easy to look at the problem and figure it out but coding it up um it's a little bit trickier luckily this is following the kind of same DFS pattern that we see uh very commonly where essentially we just oops we go to the leaves and then work our way up so what we want to do is we're going to basically write a DFS function and in this DFS function we're going to go all the way down to the leaves at which point we will start returning up to the parent now what do we want to return to the parent at each call to our DFS we want to return the value of the that last child node um from the left side and the right side so we're going to have the left value and we're going to have the right value and these will be two separate calls to our DFS function what else will we need well we also want to keep track of the longest univalue path we've seen so we're going to return the left value and L longest and what left longest is going to represent is the longest univalue path from the uh left side and the same thing we're going to have it from the right side so for example when we get to this Leaf node here obviously it's a leaf node so it doesn't have any children so a leaf can be its own path so from this one we would return what a the value of five and also the length of the path which is one which is just that node five would call uh it parent which had called um it will get nothing from the left because it's empty and it would get from the right the value of five and one now when we're at the parent and we've called the DFS on the children we're going to check is the current value 5 equal to um either of the children if it is then we can basically add um that one right so we can basically say okay well we now have a longer path so we add one to whatever side matched if they both match then we have to make a decision we can either take the child here uh in the same way that we have in this one but we actually can't go higher up in the tree uh because that will not uh be allowed right we cannot um just do like four and then continue up in the tree if we take something uh a parent node we have to use whatever is in its left child uh left sub tree and right sub tree we can't then go further up in the tree so we'll have to make a decision when that happens uh and basically just update our solution and it could be a temporarily best solution if not we still need to go up with whatever side is longer the right or the left so we'll pick one and then continue up the tree in case there's actually a better solution so pretty standard um we do these problems all the time we go to the leaves do something with the leaves and then start bubbling up the recursion until we get to the end and simply return the best uh value we've seen and all we need to do is keep track of the value from the left uh sub tree that we've just seen um when we call our DFS and also the L uh length of the longest uh univalue path in theist left side and in the right side now that's enough blabbing drawing these like lines it's getting a bit confusing let's actually go to the code editor type this up you'll see that it's quite simple and we'll handle all of the cases uh for determining do we want to use the left side do we want to use the right side both of them what do we do here let's go to the code editor and type it up let's code this up I just realized that uh when we were going over the intuition I actually made a mistake if we look at the problem here um this length this path is actually not um three it's two it's actually we Define the length of the path by the edges between them not the number of nodes so obviously there's two edges here and that's why it's two and same with this one there's two it shouldn't be three that for some reason I thought it was the number of nodes in the path it's actually the number of edges in the path which is fine the logic will be the same I just hopefully I didn't confuse some of you guys because I said three but it said two in the answer okay let's actually code this up first thing we want to do is actually make sure that our root is not empty if it is then we can't do anything so we just return zero we're going to say if not root uh then let's just return uh zero now let's create a variable to store our longest path so we'll call this self. reses and we'll put it as zero for now uh we're going to call a DFS function on our root and we'll Define that in a second and that will basically go through our um logic and update res as we go along and then the last thing we need to do is simply return self. reses cool now let's actually Define the DFS function so we're going to take self and we're going to take a node now remember a node um can basically be uh empty it can be a leaf node or it can be just a regular node that has uh one or more children so let's handle each case uh one by one so we're going to say if not node then obviously there's nothing to do here and remember that we're going to return the uh Val of the node and the length of the longest uh uni value from that node so obviously if there's no node then we just simply return uh nothing right so we're going to return float uh minus infinity for the um the value here and we're also going to return uh zero because obviously there is no node we can't form a path otherwise if we have a leaf node and this is going to be when node. left and node. right are both empty so sorry uh let's see if not no do left there we go and not node. write so if both these are null then we know that it's a um a leaf node um so we can simply return the value of the node and zero because like I said earlier um it's not based on the number of nodes it's actually the edges so we actually haven't seen any um edges yet so the length of the longest path is zero okay now what we want to do is actually process uh the left sub tree and the right sub tree of our current node now that we established that it's not empty and that it's not a leaf node so remember that when we call DFS it returns a value for the um immediate child's value and it also returns a um length of the longest path so we're going to say the left value which is equal to no. left. Val uh left Val and then the left longest is going to be the result of calling oops self. DFS on node. left and the same thing for the right so we're going to say right Val right longest equals to self. DFS of node. write okay cool now we need to actually handle um these values and there's actually four cases we can do here so the first case is when left V actually equals right Val so in this case we want to basically form the tree of basically taking left Val and right Val and then linking them with our current uh parent so we're going to say if left Val equals to uh WR Val equals to node. Val we're going to say that self. res is going to be the maximum of whatever the current self. res is and then two plus the longest on the left plus the longest on the right now where does this two come from remember that we get an edge when we get um when we link a node right and there's obviously we're taking the right and the left so as you can see here this would be the case where we take this left sub tree and then the right sub tree sorry the left sub tree and the right sub tree so obviously then we get two um edges between them so we add two plus whatever the length of the longest path of each one of these is obviously they Leaf noes here so it's zero so it' just be two for this one zero so it' just be two for this one zero so it' just be two for this one which is actually the solution here okay so that's where the two comes from so if they're not equal then we basically want to um check whether not one of the uh children actually equals to no. Val because that means that we can actually continue up the tree which is the case that we saw um here in this example where we're taking the right side we can ignore the left and we can just take the right and try to go actually higher in the tree so let's handle both of those cases we're going to say else if the left value equals to node. Val so we've already established that um these three don't equal each other so now we're just going to check the right and the left separately to see if they equal each other so we're going to say does the left Val equal node. Val uh if it does then we're going to say self. reses is again the maximum of whatever the current result is and one plus the left longest so the reason we do left longest is because we're obviously looking at the left sub tree now we've we don't want to we don't care about the right tree uh in this case uh actually we forgot to return something from this side so we actually want to return what do we want to do so obviously we return the current node. Val now we have to decide what we want to do when we go up the tree because as we saw if you choose to terminate at a parent and take its left and right child that's it you cannot go further up in the tree you can only take one side and then go further up in the tree I couldn't take 444 here and then if there's another four try to link them up that doesn't work you have to pick one so that's why we did the update here in case this is actually the best solution um we're going to take it greedily and then but we still need to proceed up the tree with whatever the best current solution is so we're going to return node. Val because that's the current value of our node and we're going to return one plus Max of left longest and right longest so we want to optimize here so obviously one because we need to link the parent with either the left or the right and we're going to take which one's longer um for obvious reasons okay so the same thing here except now we know that the left is longer so we don't have to um make this maximum here we can simply just return node. Val and we can return 1 plus the left longest uh let's see L longest okay now similarly for the right tree we can say if WR Val equals to node. Val then we can say self. reses oops I can't type today equals Max self. reses so whatever the current result is and then 1 plus the right longest path and then again we simply just return from here no. Val and we return 1 plus the right longest cool um yeah and then the last case is when there is uh nothing that equals to the current node which means that we cannot use the left sub tree and the right or the right sub tree because then we can't form the path we can only do it if they're the univalue right so we simply return uh node. Val and zero because we have no path yet and that's it that's the DFS function pretty straightforward it's one of those where we just return um you know something from the children and then in this case there's quite a few cases you need to consider unfortunately but we have seen this kind of problem before anyway let's run this make sure we didn't make any s silly mistakes submit it and accept it perfect okay so what is the time and space complexity of our algorithm so in this algorithm we need to process every single node once and only once which means that because of our DFS our time complexity is going to be big out of n uh where n is the height of the tree okay sorry the not the height of the tree the number of nodes in the tree okay uh for the space complexity even though we don't Define any extra space here because we have recursion um in the worst case our tree will just be like a link list so basically think of it as starting from the root and then like only right nodes or only left nodes in that case our recursion is going to basically just be n um again so where n is the number of nodes in the tree because we need to count the uh recursive stack frames so recursive stack frames okay so that is how you solve longest univalue path definitely a weird question um it is like a standard DFS template but you actually have to do quite a few comparisons here and taking like the local maximum which might be the global maximum but you don't know which is why you have to um take it but then also proceed up the tree with only half of the sub tree it's it can be a little bit confusing but um relatively straightforward so hopefully this video helps if you were stuck on this question anyway if you enjoyed the video leave a like and a comment subscribe to the channel to help me reach 10,000 subs and channel to help me reach 10,000 subs and channel to help me reach 10,000 subs and I will see you in the next one bye
|
Longest Univalue Path
|
longest-univalue-path
|
Given the `root` of a binary tree, return _the length of the longest path, where each node in the path has the same value_. This path may or may not pass through the root.
**The length of the path** between two nodes is represented by the number of edges between them.
**Example 1:**
**Input:** root = \[5,4,5,1,1,null,5\]
**Output:** 2
**Explanation:** The shown image shows that the longest path of the same value (i.e. 5).
**Example 2:**
**Input:** root = \[1,4,5,4,4,null,5\]
**Output:** 2
**Explanation:** The shown image shows that the longest path of the same value (i.e. 4).
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-1000 <= Node.val <= 1000`
* The depth of the tree will not exceed `1000`.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
124,250,437
|
368 |
The question of Largest divisible subset lead code is, first of all read its problem statement, before that those who want to see only quick solution can go to quick solution according to time stamp and I explained the solution quickly within two minutes or three minutes there. But you can go and see it and for those who want to understand it well, first of all read your problem statement, you have given yourself a set of positive integers and here one more thing is very important which you have told yourself. That is, all the numbers are distinct, right? If you go down and read the constraints here, then you have been told that the numbers are unique, all the numbers are unique. Also, if you read the constraints before the question. If we are going to our constraints, here we know that 10 to the power of 3 is the length of our numbers i.e. the power of 3 is the length of our numbers i.e. the power of 3 is the length of our numbers i.e. the size of n can be 10 to the power of 3, this means that we will keep our type complexity that Do you want to think of an n square approach or an n square approach? If you think of it then it will work. You can also go with n squares. This approach is also acceptable. Okay, now first of all let us understand your problem, consider yourself as the largest. Subset has to be removed. Also the subset should be basically sorted. Those who will give their subset should be in sorted order. Whatever will be written right, even if the original order is not maintained, it should still be in a sorted order. It is true that every pair is What will happen if I have given a subset, this is main and its subset is being formed, then inside this subset one of two conditions should follow, what is that condition, either I divide 3 by 1, then my Reminder should come zero, right? Either I divide 1 by 3, then my reminder should come zero. If any of these two conditions are followed, all the two numbers in the subset have to follow any of these two conditions. This means that if there are five numbers in my subset like A B C D e F, then if we take B and D as our example, then it must have one or the other C condition or follow it similarly. B is with C, B is with E, B is with F. In this way, every number is with every other number, one of the two conditions have to be followed, okay, this is the problem statement, see the two examples below. Let us see, we have given an example of 1 2 3. Inside this, we will have a total of two subsets, 1 3 and the second subset will be 1 2. If we see Apna within this, then 3 / 2 whenever we do Apna, whenever we 3 / 2 whenever we do Apna, whenever we 3 / 2 whenever we do Apna 3 / 1. If you are writing 'apn' from 'lets' do Apna 3 / 1. If you are writing 'apn' from 'lets' do Apna 3 / 1. If you are writing 'apn' from 'lets' like this, then any reminder of it will come to mind. Similarly, whenever you do 'apn 2' / 'baa 1' or 'to' from 'lets' is written do 'apn 2' / 'baa 1' or 'to' from 'lets' is written do 'apn 2' / 'baa 1' or 'to' from 'lets' is written inside, 'la' after 'one', we inside, 'la' after 'one', we inside, 'la' after 'one', we do 'diwa batu' in this case also. Apna do 'diwa batu' in this case also. Apna do 'diwa batu' in this case also. Apna reminder will come only zero of zero is this if we look at it upside down. If Apna sees something like below there is two and above is one then in this case Apna reminder of zero will not come even if we store Apna in integer then this zero of 0.5 will come. It happens, but we consider it as not zero, let us do this, we have this zero of 0.5 will come. It happens, but we consider it as not zero, let us do this, we have this zero of 0.5 will come. It happens, but we consider it as not zero, let us do this, we have understood this thing, one of the two conditions is being followed for both the subsets, if we have to return anything out of these two, it will go, it's okay, it doesn't matter the delay. Can be multiple answers? You can return any of the two. Then we turn to example number two. In example number two, we have given one answer to this and we can simply give this as our output. Why is this so? For example, if you take your t and four, you take 0 and 8, then all the numbers are following one of these two conditions. Right, and you have given yourself one more thing that the numbers will be unique, meaning nothing is repeated. If nothing is repeated, then there is another guarantee that only one of these two conditions will be followed. This is a very good observation. What I mean to say is that if you always look at the meaning, one thing is given to you, that is that There will be no unique numbers, it means that if you pick two numbers A and B, they will never be equal, so it means either a will be greater than b or b will be greater than a. Any of these two conditions will come because it is not equal if it is not and if you want to find out which of these two conditions is happening then what will you have to do, you will either divide a by b or B divided by a. Only one of these two conditions will give the answer whether it is divisible or not. If it were equal, if it were equal, let's divide 5 by 5. I am right or should I reverse it, then the answer is mine. The percentage will definitely come to zero, but if you look at your case, you are dividing 2 by 1 or dividing 1 by 2, the answer will come in only one of these cases, in which there is a small number below, the number below is small, so if I Always make the assumption that if I picked two numbers a and b and a is equal to b or I sorted them from left to right or did something like this that my first number is smaller and the second number is bigger then I only have to And I just need to check b divide ba a I don't even need to check a div ba b because look if the number above is small like above is number one below If the number is big then the percentage will always come which is the smaller number, it means that zero is not coming. Okay, so one observation which is quite important is that we write down observation one at one place. Observation one of ours is that if a is lesson b right? If a < b then lesson b right? If a < b then lesson b right? If a < b then what do you have to check? You have to check simply b divided by a. You have to check whether its percentage is equal to 0 or not. That's all. Do you want to check or can you write in your simple words b percentage a equal 0 is coming or not coming? This observation is one and this is the last very important observation in the scale. The second thing is that how to make your sub. Look, see a. The number is two, if there is a number two. If there is a number two, then it can be a part of two subares, like this part can be a part of six, this part of six can be two, there is no problem with two being a part of multiple series, but in becoming a part. I have to decide with whom should I go and which length should I take because tomorrow it may happen that if I come then 248 is a valid server but 268 is not a valid server right or only 28 is a valid server. So I see that 2 48 is a valid bit but 268 is not a valid bit. If you think carefully about this, if you are a little good in LCM HCF, then you will notice one thing. How did I know that now? A new number has come, whether it will become a part of all this or whether it will become a part of this sub. Now there can be an answer to this. Any one intelligent person can give the answer that if these two are sub-arrays, I have to decide whether two are sub-arrays, I have to decide whether two are sub-arrays, I have to decide whether one or the other is now. The number has come at that, should I put it in this one or put it in both, then someone can tell me that first of all check if mine is to be put above and if I have to put it in the above one, first check whether 8 is divisible by 2. Then you check by four, is 8 divisible by 4, if 8 is also divisible by four, then put eight here. Similarly, come to the bottom one, is the new number eight that has come, if it is divisible by two, is n't it? Pert is 0 and also if 6 Parj A 8 Sorry 8 Parj 6 If this number is also divisible and its percentage is coming to zero then only I will put the second case it becomes false Now see what I mean to say which I have just told you so far Just recited the whole Ramayana a little, what it means to say is that if I have a series from Lettuce like this, A B CD, I have a series from Lettuce, a new number has come to me, number has come, a new number has come to me, now one from Lettuce, is it okay? What I mean to say is that first of all, make your CD e. Now look, I am saying that we have sorted our main array. We have sorted our main array. a is the smallest number. There cannot be any number smaller than a. If the number B has come, then B will be bigger than A. Because of this observation, we are doing this kind of okay. Also, we are going to see another very good observation. What is that observation that if the number B has come then now? So hey, I have only one number, what will I do, I will simply check b by taking percentage a, if it is zero then I will simply put that number, so what did I do, yes, percentage a = 0 is coming, so yes, percentage a = 0 is coming, so yes, percentage a = 0 is coming, so I put b here. So see b percentage a is coming equal to 0 so I have put b. Now hey now if a number c comes to me, if a number c comes then a case will be made that what will I do c percentage a. I have to take care of these two cases but what I am saying is that look b percentage a e 0 I have already checked if b number a If my number B is divisible by A then it means that if any number C is divisible by B then it is automatically divisible by A. This means that if this is the case then it means that it will also be divisible by a, so it means that I do not need to check with a here because when I have entered b, I have already checked that. B is divisible by A. If this case is followed, it means that all the numbers before it will automatically become divisible by the number C. Now look at what I am saying, let's think about it on a larger scale. Okay, let's say this. While doing things, I have put it till A B C D E. Okay, I have put it till A B C D E. Now my turn has come. From the beginning till the end, he would check everything that my condition is not failing at any point and what is that condition. He would simply check whether Neither will it come in increasing order, all these things will come in increasing order, so now the Coming, the one whom we will test is the biggest among all these, this thing is guaranteed, that number is big, that is why they are doing smaller numbers in front and behind, so x percentage a, if e is 0, also x percentage b cd, all these I have to check the case but I am saying that the e is divisible by all these. I have already made sure that e is divisible by all these. So if I simply check whether my x is If it is visible from e, if this percentage x percentage is equal to 0, if this is the case then it means that And I will simply put It is in my mind that yes, I have understood this approach, so now you can go and try it yourself and now you go ahead and understand your main solution. You have understood one more thing that if you are part of a multiple series from Let's. What happens right now is that if e was a part of a multiple series, let's say here a1 b1 and simply here it would be connecting to e and the lower series would be connecting to a2 b2 c2 d2 and e then which of these two One has to keep in mind that I have come here and the next series will be the same even though it was the same till now, the next series will be the same, doesn't it mean that I have come here and joined, so the next series will be the same. What this means is that whatever small series was there, I do not need to take it, no, I always have to work only with big series, I have to work only with big series, so I can maintain it everywhere. What is my particular length coming till now? If my length till now e is coming from lets to four then I have to proceed with four only. If what am I saying by lets to let's I have not yet inserted e. I have not put it here, I have seen here, I have these two numbers: a1 b1, below are these two I have these two numbers: a1 b1, below are these two I have these two numbers: a1 b1, below are these two numbers, its length is up to two, its length is up to four, I know these two things, it will be easier if I paint it with another color. Its length is up to two Its length is up to four e saw that it is divisible by e came here its length is three Then e saw one more time that e is also divisible by d2 but if e with d2 If it goes to zero, then its length will not be three, it will become 'f', that is, goes to zero, then its length will not be three, it will become 'f', that is, goes to zero, then its length will not be three, it will become 'f', that is, whatever series is coming to its end, its length will become 'f' on e, coming to its end, its length will become 'f' on e, coming to its end, its length will become 'f' on e, which is more than three, then e will always go towards the maximum because even in the question, Given, we want the largest divisible subset, that's why, we will always go with the one who has more length. This is a simple logic, okay, we have understood these things, now what should we do if we make a series, then look, ours is always the same. The thing we are checking is whether b2 is divisible by a1, whether c2 is divisible by b1 b2, whether d2 is divisible by c2. By doing this, what can we do, we can make ours, right, we have made each particular number of ours. For e, you can simply write like let's say this is the index of e2, this is the index of e, so e knows that it has to point to e, we can think of it like a linked list e. Why do we have to point to d2 because the length of the key was the highest till now, by which it is divisible, there would be another series below Lets which would be a3 b3 c3, and d3 from Lets, after d, there is f3 from Lets and F. Later e is connecting to it, so e goes with f3 rather than with d2, it does not mean that these are the names of different balls, it does not mean that I have given them in numbering or alphabetical order, it means something about their relation to each other. There is no meaning of comparison, it is just a variable name. Okay, so now what will e do? It will write here that friend, I have to point to d2, whatever my series will be, it will point to d2. Now if lets say, similarly if here. The index of d2 would be d2, I would have written here that I have to point to c2 like this so on and here a2 points to whom a2 does not point to anyone like this what can I do at the end We can find out our a in these two, we make our a and ar out of all these and store their length, then a knows its length, a has its length coming from lets 1 2 3 4 If e knows its length, five, then whichever one had the maximum length, we will move it here in the reverse order that a is visible to him, d2 is visible to d2, c2 is visible to c2, b2 and b2 are visible. By doing a2 like this, let's take out our entire series. This is our main work. Okay, now this is complete from question explanation to solution explanation. Now let's go and write our code for it. Okay for now. I will do this by resetting the old code. Now we will write our code here. So see, I said two things, one thing I have to maintain the previous order, one more thing I have to maintain is that till now I have all the sequence ending at me, what is the maximum. Length of that, I have to maintain these two things, so what will I do? First of all, let's create a vector int previous, it will maintain whatever is the previous elements till now, what is the size of our nam before that, sor in our n. Let's do it so int n equal to numbers dot size, we have stored it, now we have given the size to the previous one, so we have given n but all the elements of the previous one should be initialised from, look here, if it is on a2, then a2 is on which index. Whenever a2 is pointing at -1, it on which index. Whenever a2 is pointing at -1, it means that it is the end, it means that you have got the left hand side of the series, it is right, you also have an example below for which. If you will have a dry run in your future then don't worry. If you are still a little confused then don't worry. Okay, so what are you doing? Here you are saying that the previous will initially point to -1 because any valid point to -1 because any valid point to -1 because any valid index will point to You should not even do this, you have all rights to the previous one, so it becomes yours, one previous one, there is one more vector int length, this has been maintained, how much length do I have till now, okay, now that you have got the vector length, also its length. Will be n and all the elements will be zero sorry one because initially everyone can make a sub sequence with itself whose length will be one l right so this thing sub sequence sorry can make a sub sequence or subset whose length will be One, so what have you done? The length is n and everyone is taking the length n, so here is the length. One has done these two things. Also, one thing that we keep stored is that which is the maximum index that we are getting till now. Which is my maximum length, which index do I have? Okay, so we are maintaining it as a variable int. Maximum lets the answer or is it the maximum length tail? Basically, we are maintaining our tail only, so the maximum length tail and This is initially we can say this is zero we can say this zero I have given it that index but let's say this row l right so it will contain the thing that is maximum length tail will contain the tail of that thing whose length is still maximum okay Now you will understand better when you code it, so what do you have to do? First of all, you have to run a loop inside all the sub sequences. Okay, you have to run a loop, how can you do that in all the sequences and all the sub sequences? Hey, within this, how can we do so, let's say for ant, now see what I am saying, as if you have this length, now what will you do from here till here, what will be my maximum answer, he will take it out from here. From here till here, what is my maximum answer, they will find it. First of all, you will have to decide a start point and an end point, within which you will find your answer, call it one more thing. You can call it Apn From To, OK, From To means from this end to this index. Let's keep the name of both these variables as Apn From To. If you want, you can also keep End or Start. But for now we are going to keep It from end to end the first loop that will run will decide where to is okay so it will decide that tutu should be lesson a plus plustwo okay l right ab apne batte aag ab apne banate illu for int from equals to Now from where does from eat from will also be from zero but what is from will always be less than two plus p 2 plus from what does this mean it means that from lets this is mine to once From will see from here to here once. From will see from here to here. But from can never be equal to two. From will always be less than two. So from. To is our two variables so from should always be less than t plus from we have also done this thing now we know one thing that the one who is to is always greater so it means that from is late and our What condition will we check? We are going to check that numbers. We also have to make sure one thing. We will not have to sort the numbers. We will have to sort the numbers so that now whenever a number comes in the future, it should be bigger than my previous number. Apna had made an observation, for that Apna is doing this thing, so what are we going to do, we are going to sort numbers dot begin comma numbers dot and this Apna has done the sorting also, now Apna has to check Apna What had to be done is to keep our here big, whatever is the big value, if you want to keep that big number then from to percentage numbers of from then if this percentage is coming equal to zero it means it is divisible then I have checked the last number. I have taken that yes it is divisible and along with this I have to check one more thing. I have checked this thing. Now along with that I have to check the length whether I can take it or not like for example see with you. One example is that this has become a series. Now Na A. Look, I have thought that I have made a series with this. Now tomorrow below I have another series a2 b2 and I am now for e. My e is from okay. is and it is too late from this is to so b2 has a series d2 also had a series but b2 which is na is divisible by e so has made a series with the first na now e came forward To see that if I get a big series then I will make a series with him. Now if I see that b2 is shorter than me, whatever is the length of b2, if I make a series with him then it is short then it means. That I do n't want to make a series with him, I will skip it, so I want to make a series here, I want to make a series, first of all I checked whether I can do it from the previous number, now can I do it from the previous number. I am becoming divisible, yes I am becoming divisible, now I have to see one more thing that is my current series can be anything, it can also be like this, I do not have a current series otherwise what will I see Nam of I am Particular at I am currently at two to names of t p 1 What my new series will become Let's say numbers of from psv Is it greater than that of names of two What does this mean What does it mean that from lets or not from lets that a Also, I have written numbers here, numbers will not come here, length will come here, length. Now see what I mean to say, there will be some value inside the length of e, what will it be? Let's say for now that t 3 4 5 length. The value inside of e is f Now I checked if e makes a series with these two then what will be the length of b2 PSV 1 in that case because I am including e I am assuming that the length of b2 Pw, is it greater than the length of e which is currently stored? If not, then I will not do anything. If yes, it means that my new series will be better than the old series, so that is why I have written length of plus and which is the previous number. Which is also divisible, if I make a series with it, if the length of that series is more in comparison to my current length, the maximum length I have got so far is that in this case, I will make a series. Now I have decided that I have to make a series, so it means that the one which is previous to two will point to whom, it will point to the index from, this one has an index from to, that means we are also doing the thing with our point, kind of linklist. This is what you will see below, when you will see the whole thing out, then you will get more clarity about what you are doing, okay, you have done this work, also you will have to update the length, so the length of two is equal to length. Of from plus, if you want to understand what I have written, it means that the new length is equal to the length of from, meaning the length of the previous plus the current element itself, so that is my self and the previous key. If you were maintaining length plus mylfiseva length tail then what does it mean? You will check here. You can also check this loop bar with lets. You can check this in your loop bar and adopt it. Comment is ok, what can you check about the time of the loop that whatever is the maximum length tail from the lets, if it is less than the length of 2k then what will I do, I will update the maximum length tail of which The length is more than the one whose length is more, I have updated it with that. Simple Jatt Apna Kuchh Condition Bhoulle Hain I Don't Thank S Apnah Kuchh Condition Bole Apchn Will Work Now Apn Jaate Apn Do Outside The Loop Apn Do Print Things Will Apn First of all, for auto I in previous, first store what we have previously stored and print it. C out I with space at the end C out and also print our length. With this, your maximum doubts will be cleared. These are the ones in C out statement. At the end of the day, we will make our return empty. Hey, we have made our return just so that we can see what we are doing till now, we are obviously doing something wrong, that is why the error is coming, there are small mistakes in coding, it is okay. If we talk about our case, what we do is copy the value from Y and paste it here so that we can dry run it. We have already written a test case here, so I want to do this. If you want to run your dry run then bring your menu from there, paste it here and delete it for a second, paste it and make it white. Okay, first of all it is previous, so what is the meaning of previous? What happened is that let's say this is the last index, its previous one is three, right, the previous index of the last index is three, if I look at the indexing here, 0 1 2 3 4 and 5, this is pointing to the third index, which means this is pointing to this. A to the third index and who is the third index pointing to? The third index is pointing to the first index. Is it pointing to the first index? To whom is the first index pointing? The first index is pointing to the zero index. Now the row index is pointing to whom. The row index is pointing to NULL or we can say -1. If this is the type of linked list then -1. If this is the type of linked list then -1. If this is the type of linked list then this is -1. Is pointing to and here this is -1. Is pointing to and here this is -1. Is pointing to and here below it I have written the length, whatever is this third index, its length is four, so whatever is the third index, its length is four, so the one here, the one has the maximum which is till now. Also the length has come, that is three, so far one has got the length, maximum three, so as soon as he added three, his length has increased by one, he has played here, maximum length is two, as soon as three has added this row index here. One length has increased like this, so on and so forth and this thing will keep going on, if you ever see someone else's length is more, then you will include it in your answer. Look, till now we had a total of two values, which we got three. Answer: Lake de rahi hai na ek thi four Answer: Lake de rahi hai na ek thi four Answer: Lake de rahi hai na ek thi four ek 36 What does this mean? What does it mean that what series were being made till now? A series was being made. Apni one 2 4 ek was being made Apni one th and six hana or OneTwo and Si, these two series were being made, isn't it? Now after making these two series, it has got a new number 24. Currently, the length of both of them is the same. 24 first joined hands with it and made a series with it. Look, 24 has made a series with 4 2 1. 24, whatever index is on it, its maximum length has become four, meaning look, the length is also visible, its length is four, then when this series. It is visible that the one whose length is also here, then he sees that I will be able to make only a length four from here too, it is not more than my current length, so I will not do anything, but if there was such a series below, there is a 12 before the six from the lets, right? So it could have made a series with 12 but this thing is not possible because if there was a number 12 then that number 12 would have come here also, hence in this case hence a series was made with the above one and this was the best way. Okay. You have understood this thing, now what do you have to do, now you have given yourself the previous numbers, that is, keep giving me the previous indexes. This is the previous index of 24. This is its previous index. I have to enter all these, I will reverse it so that it comes in a sorted order and I will simply return it, okay, this 24 I have stored its index also and I have stored it. You have stored this index which is your maximum tail length, inside this variable you have also stored that index, so now what will you do while maximum length tail is not equal to human, see it has become a little bit like that. Lincoln Link Less, as long as it is not null, let the Y loop run, it has become a type of thing, so what will we do inside this, we should have an answer, let's create our vector int answer here. Now, when we come here, what will we do, first of all, we will put whatever value we have on this particular index, then how will we put it? Answer dot push back is not the names of maximum a length tail, we have put the pushback now. The maximum length tail has to be updated from the previous element. Ok equals to previous of a maximum length tail. This has been done at the end. By the time this happens, it will point to null. In this case null means -1 and your Put all the values -1 and your Put all the values -1 and your Put all the values in your answer before doing this. If you run your answer now then your answer will be coming in reverse order. So see your answer is coming in reverse order. In this case I don't think so reverse. If there is any problem in the order, you can submit it has no meaning in ordering, only then you are not getting the error, if there was a problem, you would have sorted it in reverse order, so this is the solution, now I am a Let me explain it well again, okay, so for those who have come after jumping, this part is that once I briefly explain this question, the observation one number one that I have given to myself is that someone No two numbers can be equal. If no two numbers are equal, it means that one number will always be bigger and one number will be smaller. So let us assume that A will always be smaller and B will always be bigger because we have You have sorted your array. This means that you understand that if you shorten your array, it will be easier. Now why are you sorting your array? We are sorting because always whenever a number is shorter or a number is smaller. If b is bigger than let's then your only need is to make b the percentage of a. You do n't need to make your a the percentage of b. That is mathematically because such a thing happens. Alright because your always keep the big number at the top and Keep a small number below whenever you want to see the percentage zero or want to see a reminder, now the second thing has come and the second observation that you have got is that you have made a subset from the lets. Inside which a subset has been made by doing ABC, CD, E, etc. Also, due to sorting, we have made sure that every number is greater than the previous number, so this is also made in a sorted order, our subset has been done by us. Make share, what does it mean inside this, it means that if I talk about the last element e, then e percentage d = 0 s b a this is with all percentage d = 0 s b a this is with all percentage d = 0 s b a this is with all whenever we will calculate the percentile or try to extract the reminder, it will come only zero now. If a new value f comes, the new value is the name of all the variables. Variable means that there could be any value inside them. A new value f has come to me. Now I am thinking whether I should include it in this subset or not. So what will I do if I have seen f percentage e equals e 0 This observation means that if this condition is followed, it means that whatever f is, it will make the percentage zero with all these also because we have already a Make sure that a is divisible by all of these. If f divides a number, f is divisible by a number, it means that f is divisible by all their smaller numbers, because all those smaller numbers are We are already dividing e. There is no need to divide f within the entire series. We will calculate the percentile only with it. If it comes then it is fine. If it does not come then the condition is false. It cannot be a part of this subset otherwise normal cases. What do we do by dividing f with this and with this with all and see with whom the percentage zero is coming. If it does not come with anyone then it cannot become a part of the mean and subset. This is why Simply, you can check with the biggest value which is in the last because that is the part of the subset. Right, in the last, if you talk about the solution then see there is a number f, this is the second one, it is different from the top, this is the one below, this is different. Okay, this is our main array from Let's, this is not a subset, this is our main array, so inside the main array which is our names, I have to see with whom F can form a subset and with whom will its largest subset be formed. So what will I do, I will go and check with everyone that if I make f a part of e, if I make a part of d, if I make a part of c, if I make a part of b or if I make f a part of anyone, then with whom? If a good answer can be found, then in that case f will be determined from the maximum length. Let's say that if f is divisible by d, then now the length of d will come inside f. That is the length of d. + 1 This That is the length of d. + 1 This That is the length of d. + 1 This will come inside f as length. The second thing is that we are maintaining our previous value here, so if f has decided that it will create a sub sequence or subset with d, then inside f we will store our d. Like there is something else in the preceding d, if there was a b in the preceding d, then we would have stored b here, there is nothing in the previous b is not pointing anywhere, so by doing this, it would have become a series of its own and b. Points to -1, so store your and b. Points to -1, so store your and b. Points to -1, so store your only indices here, all right and below, store your length inside length, so this is the quick solution to this. At the end, what do you extract from these? Let's take here the maximum length, in terms of maximum length, whose length is the maximum, the one who has the maximum length, after traversing that one, traversing it backwards, going to the previous one, a kind of list will be created, by traversing it backwards in the link list. Till unless apan does not get -1 here, apan simply not get -1 here, apan simply not get -1 here, apan simply creates one array, if you see this in your code, you have done the same thing, you have created one previous and one length array, maximum length tail or this will remove that tail. Apna Ko whose length is maximum, Apna has sorted the numbers first which is very important because of observation one, after that Apna has run the loop and in the loop, Apna has seen here that each number is the same as all the previous numbers. If you are watching together, what have I done, the next number has been named Two, the first number has been named One A From, so from From to Two, it is visible, after that I have checked here. I have taken that the first thing is that the percentage is zero. Yes, the percentage is zero. After that, if I make a series with it, will the length of that series be more than the length of my current series? Here, plus is written because I myself I am also including myself that while writing here PS and the old series plus me, what I am doing right now with myself is more than my series because I am taking out the maximum, so in that case I will come in. I will update that friend, whatever is in my previous, that is the previous index, this index is in my previous, also I will increase the length, whatever is my length, I have come down here, I will update my maximum tail if Whatever happens, you will update your maximum length tail accordingly. At the end, your maximum length is 10. Because of that, what will you do? Go here and traverse and then un-lace your traverse and then un-lace your traverse and then un-lace your minus. And index pe nahi aa jaaye apna sub values ko apni array dat denge, at the values ko apni array dat denge, at the values ko apni array dat denge, at the end apna have put all these in one answer array and apna simply return that answer so this is it for this video I hope that you Have enjoyed it. If you have any doubt related to this question or any other question please feel free to ask it in the comments. If you liked the video then do like it. If you did not then subscribe then give it a try.
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
138 |
hey guys welcome back to this video now we're going to solve a coding interview problem copy list with random pointer this is going to be linked list problem a linked list is given such that each node contains an additional random pointer which could point to any node in the list or null we have to written a deep copy of the list we can't return the given linked list we have to create a new copy and we can't reference to the original node we have to create fresh new linked list as the given linked list for example if you're given this linked list then we have to return this link list and here the all the node need to be new they can't reference to the original node and the new created copy need to be exactly same as the given linked list where we have next pointer and random pointer and a value all right so how we can solve this problem now let me go through the intuition let's suppose that we're given this linked list first what we're going to do we're going to insert this node of value 7 with the next pointer and random pointer the random pointer will point to now and we're going to insert in between 7 and 13 the new node will link to this node 13 and this node will link to the new node initially when inserted a new node then the new node will not have a random pointer okay and in between 13 and 11 will insert here node 13 and then here in between 11 and 10 will insert a node 11 in between 10 and 1 will insert a node of value 10 and here in between null and this node one will insert a node one they will be represented like this so here we have inserted node seven that has a next pointer and the random pointer is null okay so here we inserted 7 13 11 10 and 1 now what we're going to do we're going to fix the random pointer here this node 7 will connect to the null node okay and for this node hardin it will be connected to the node 7 then here this node 11 will be connected to the node 10 okay and so on and they will be represented like this after that we're going to disconnect the link and we're going to connect this next pointer by skipping onenote okay here as well let's disconnect and connect here then here let's disconnect let's connect by skipping one node again let's disconnect this let's connect it by skipping one node and so on and they will be represented like this okay for this linked list we have the hit 7 and we'll return this head okay and we'll return this head 7 this is how we can solve this problem now how we can insert a node with next pointer and random pointer where random pointer is null then how we can fix the random pointer then how we can connect each node by skipping one node now let's see how we can do that using pseudocode this is the pseudo code to solve this problem here this code will insert the node 7 13 11 10 and 1 and this node are new node and this node has next pointer and random pointer but random pointer pointing to null node then this code will fix the random pointer like so take a look at this picture i'm not going to go through the sudok hood if i go through the pseudocode you'll be get bored instead i'm going to leave the resources for you to understand this problem and here we have this code will link node by skipping one node okay like this and here we have coffee head equals to this node okay so we'll return the coffee head and here we see this note 7 13 the 11 10 1 null and we have the original node and we have the original linked list 7 13 11 10 1 now so we have the given link list as it is and we'll return the coffee head and here we're just returning the coffee head and the solution will takes big of 3 end time complexity since we are iterate through the given linked list three times and that's equivalent to big of n since here we're not using any additional speech we have some pointer so the space complexity for this problem is big of one and this is how we can solve this problem for better understanding i encourage you to go through this pseudocode and here we have the linked list and you can see how it actually works the source code is available for this problem all right guys this is the solution to this problem if you have any question if any suggestion let us know which problem we should cover in the future if you haven't subscribed to the channel please subscribe to the channel and stay tuned with cs ninja all right thanks for watching i'll see you in the next video
|
Copy List with Random Pointer
|
copy-list-with-random-pointer
|
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.
Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.
For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
Return _the head of the copied linked list_.
The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
* `val`: an integer representing `Node.val`
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.
Your code will **only** be given the `head` of the original linked list.
**Example 1:**
**Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Example 2:**
**Input:** head = \[\[1,1\],\[2,1\]\]
**Output:** \[\[1,1\],\[2,1\]\]
**Example 3:**
**Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\]
**Output:** \[\[3,null\],\[3,0\],\[3,null\]\]
**Constraints:**
* `0 <= n <= 1000`
* `-104 <= Node.val <= 104`
* `Node.random` is `null` or is pointing to some node in the linked list.
|
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list.
For e.g.
Old List: A --> B --> C --> D
InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
|
Hash Table,Linked List
|
Medium
|
133,1624,1634
|
341 |
welcome to april's leeco challenge today's problem is flatten nested list iterator you are given a nested list of integers nested list each element is either an integer or list whose elements may also be integers or other lists implement an iterator to flatten it so to implement this iterator nested iterator class we're going to initialize the iterator with this nested list uh and we have two functions to return the next integer inside the nested list or this boolean if it has another one has next then we want to return a true so this kind of reminds me of using a queue but this is going to be a nested list so we need to figure out how we could move through this nested list and pop off the ones as long as there's the has next now doing flattening a nested list was one of the first youtube problems that i solved but this is different because we want to make it into an iterator how can we do that now if we wanted to do this um they do give us a couple functions that are going to be helpful we could check whether it's an integer or uh if it's not we can return a list the list that it is or we can return the integer but how do we keep track of where we are inside this nested iterator after all we could have an infinite amount of depths and columns it could be structured in all sorts of ways we could have it be just like one depth where it's like listening to your list or it can be here we could have like a list and inside of here could have integer and then another list and then maybe inside that list there's integers and lists so you know keeping track of that there's really not a good way to do that because we don't know how far deep this nested list can go so rather than keeping track of where we are and popping it off like keeping the original structure why don't we flatten it immediately flatten this nested list first using a recursive function because that's normally how you do it we would recursively return the integer or the list and just add that to some sort of temporary and flatten it all in order so we're going to do that let's write a function right in here we'll call it flatten and we're going to flatten whatever is in here and that's the list and we're going to make this a recursive function so let me separate that to make it a little bit more readable so we will first initialize the temp and we'll say for every element inside of our nested list if this is a integer well then that's easy we just append to our temp whatever this integer is we can say i dot get integer now otherwise we know that it's a list right so in order to make sure that we're not just going to extend it by this nested list we have to put it back in here to flatten and recursively add to this into this list but we're going to extend it because we're going to return list now so what we'll do is say extend flatten this i uh but make sure to pass it in as a list all right and make sure to return the temp so now this is going to return to us the flattened dictionary at the very end so what we'll do is we'll just call this n and we are going to call our flattened function for the nested list passed into us next i'm also going to convert this into a queue and i suppose i can just do that here actually let's make that into a queue so now it becomes easy uh to return the next all we need to do is just pop off the left one pop left and has next is literally just whether this thing exists or not because we'll be popping it off once we pop off the last one this will return a false and that would be it so let's see if this works and it looks like it's working let's go and submit it and there we go accepted um so time complexity wise i think it's just all of however many num um you know objects we have or not objects how many integers we have inside of our list and we do have this recursive call so we do use oven space as well but that's all right i think this is pretty optimal there's probably some tricks to make it a little bit faster but uh yeah that would be it i think the big trick here is to figure out how we could instantiate some sort of recursive function inside of our iterator and make sure to just find the dictionary first or i'm sorry find the list first that makes it a lot easier to return the next error and has next okay all right thanks for watching my channel remember do not trust me i know nothing
|
Flatten Nested List Iterator
|
flatten-nested-list-iterator
|
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the `NestedIterator` class:
* `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`.
* `int next()` Returns the next integer in the nested list.
* `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = \[\]
while iterator.hasNext()
append iterator.next() to the end of res
return res
If `res` matches the expected flattened list, then your code will be judged as correct.
**Example 1:**
**Input:** nestedList = \[\[1,1\],2,\[1,1\]\]
**Output:** \[1,1,2,1,1\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\].
**Example 2:**
**Input:** nestedList = \[1,\[4,\[6\]\]\]
**Output:** \[1,4,6\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\].
**Constraints:**
* `1 <= nestedList.length <= 500`
* The values of the integers in the nested list is in the range `[-106, 106]`.
| null |
Stack,Tree,Depth-First Search,Design,Queue,Iterator
|
Medium
|
251,281,385,565
|
1,494 |
difference today let's show parallel coses 2. we are given integer and which indicates there are n courses labeled from 1 2 and we also given array relations where relations i equal to pre-course i equal to pre-course i equal to pre-course i next course i representing a prerequisite relationship between course pre-course and the course next course pre-course and the course next course pre-course and the course next course oh okay so what does that mean it means that we have increases we also have some dependencies oh for example we need to first finish course one uh oh sorry course two in order to finish course one we need to first finish course three in order to finish course one and we also have another condition which is k for one semester we can at most have k courses so the question asks us what is the minimum number of semesters so for this example for the first semester we can take course two and three then for the second semester we can take a course one and then for the third semester we can take course four for this example well we need the first finish course two three four so that we can finish course one but k is only two so we can take two close to three first and then take course four and then take first one and lasso take first course five so third in total we have uh four semesters well after looking at these question descriptions and based on our prior knowledge on how to solve the uh course schedule we thought maybe we can use um topologic search and the greedy algorithm but it will not work why let's see example i think what it is a intuitive solution with the b we still use topological thought and we have a great algorithm here which means for the course have the longest relation uh the pre requested relation we will take it first so in this example we would like to take one first because one first but it will not work let's see why well the condition here is that we have 12 courses and we need to take one first and then take course two and then take code three here we in order to take these six courses we need to take these three courses first and k equal to three if we use great algorithm well because course one have the longest prerequisites prerequisite relation so in the take a course one first in that case for the first semester we'll take course one course four and the course five for the second semester we would take course two and cos 6 that's all since we haven't finished these three courses we cannot finish any of these six courses and for the semester three we can take course three and course seven and close eight for the first semester we can take these three courses for last semester we will take uh course 12. so in total we have five semesters but it's not the optimal strategy would be we take these three courses first and for the second semester we can take ending two uh among these six courses and combined with one course here so we for example would take 7 8 and 1 for the next method take 9 10 and 2 for last semester take this two and the three so in terms of only need four semesters so this example shows us that topological thought plus grid algorithm does not work so we need to use other algorithms what is what will it be well let's look at this constraints less than 16 well it means we may possibly use bit masking since all of the bit masking algorithm would have a very small number of the items inside but we know for the bit masking they usually have two states for each item either zero either one so for this example it also fulfills this requirement which means the items here is courses and data has each item have two possibilities or two states either being taken or not taken well so it seems we can use a bit masking here but how about the dependencies well for one course it has can have uh many other pre-requests prerequisites many other pre-requests prerequisites many other pre-requests prerequisites we can also represent these prerequisites as a binary array well the courses are its prerequisites we make it equal to one other currency are just equal to zero so we can use a binary string as well okay so it seems very clear now we can use the bit masking here so the first part is just to build this prerequisite relation we um for this example the which it means the cos0 has the cos1 and cos2 as prerequisites okay and then what's the general stat a step of the bitmasking solutions it would iterate all the states or we call masks from all of them are zero to all of them are one uh it actually illum a new mu like to enumerate older states it means all of the courses that haven't been taken it means all the courses have been taken okay so for each state we know how many courses we have taken now but we want to add a new semester we want to think of what a course we will take for this new semester so we need to get a current mask we call it a curl mask it represents how many coset we can take for this new semester uh it should fulfill two requirements one is all of its prerequisites courses have been taken the other requirement is this course haven't been taken before so it means the risk corresponding uh look uh the corresponding bit in this state is zero so it means the course hasn't been taken before and we also need to check the pre-request we also need to check the pre-request we also need to check the pre-request prerequisite bits okay after we know which course we can take we get the curl mask but it just means this course we can take it down is it that necessary we need to take so then we just enumerate all the sub mask of this current mask it means the courses we actually take we just try every possibility to update the state or summer mask so this is for illuminate all the summer masks of this current mask if you are not familiar about that or with that i actually made the video before it's just about some common uh bitter manipulation you can find this video in my channel i will also attach the link below uh in this in that video i talked about how to iterate all of the sub mask of a mask you can see the example here to understand the statement okay assume we know that then we just to try to update the minimum semester to finish uh any state so in that case we need a dp array right the db array the range is 0 to this one left shift and we the place we will make this formula transitions here when we find if we add one semester uh it would we can get some new results okay so basically there are three steps we just we can just write the code i will write in the talk so you can understand this algorithm better so first thing is to get the prerequisite relationship it will be and then we just uh iterate this relation relations and then um it would be a pre relation one minus one why because uh we actually want to get uh for each course what it is uh prerequisites so it's like a opposite because here it means we need to take a 2 first then take a 1. so here it would be pre 1 have this 2. and the reason i minus 1 is because here it's a one starting from one but for array starting from zero and then we need to use or equal a one left shift relation zero minus one what does that mean because we won't make this one left shifter uh this bits so that the beta relation zero minus one is equal to one and then either do or with this pre ratio one minus one it makes a pre-ratio one minus one it makes a pre-ratio one minus one it makes a pre-ratio one minus one the corresponding bit equal to one so that's the meaning okay after we make this pre uh requisite relationship then we can do the iterated state from zero state less than one less than a one left shift l and i plus we just oh sorry not i it's a should the b state it just illuminate all the states we also need this dp array uh the size would be one left shift as well and we just fill this dp with n because it says that um it's possible to take every course so we just make it a large number which means the total number and okay after that uh dp0 should be equal to zero don't forget that because like initialization which means uh for zero currency we just need a zero semester after that we need to get the current mask at first equal to zero current must indicate the courses we can take for this semester okay but it don't necessarily mean the course we will take the currency we will take with the core sub mask okay we can write it first so summer mask with the greater than zero and the sub mask equal to a sub mask minus one uh and curl mask okay then we should decide what courses we can take we just try every course i than i plus we try but what course we can take we need to fulfill two requirements first is this course we haven't taken before it would be i of sorry 1 left shift i and it should equal to zero and uh we should make sure all the prerequisites currency have been taken which would be pre i okay pre-i okay pre-i okay pre-i and the state would equal to pre-i what does it mean would equal to pre-i what does it mean would equal to pre-i what does it mean well it means the um it means well it because we have some uh courses equal to one for this prerequisites array right and if it someone it will keep one but if one and zero it will return zero so it will not equal to that so when the pre i and the state equal to p i it means all of the prerequisites of i had been fulfilled okay and uh if we can take that we just make this square mask um take this course would be one left then i okay we just make it equal to one just simply like this statement okay after that we are here right one thing is here if we if the total curses in this sub mask is greater than k which means we can not uh take that because the total number of one in this sub mass should be less or equal than k which means we can take those courses so uh if integer beta count oh sorry beat cult sub mask greater than k we cannot tell we just continue and if dp state or sub mask greater than dp state plus 1 we can update it should be dp state or sub mask equal to dp state plus one what does that mean well because we just add a new semester right so uh that's the stp state plus one means it's one semester this is for the current state how many semester we have taken because we are taking the new uh courses so we just let it or summer mask if this is a current new uh state if the new state is greater than the older state plus one then we just update it equal to all states plus one the neediest master plus one in the end i'll just return deep here uh one left shifter and minus one okay i think it can because the okay i'm not sure well here and okay it is a prairie ref pre princesses match it's match right it's match it's matched right i think if you don't know about the older you just write every everything you can write you know you just write all of the parentheses okay all thank you for watching see you next time
|
Parallel Courses II
|
activity-participants
|
You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship between course `prevCoursei` and course `nextCoursei`: course `prevCoursei` has to be taken before course `nextCoursei`. Also, you are given the integer `k`.
In one semester, you can take **at most** `k` courses as long as you have taken all the prerequisites in the **previous** semesters for the courses you are taking.
Return _the **minimum** number of semesters needed to take all courses_. The testcases will be generated such that it is possible to take every course.
**Example 1:**
**Input:** n = 4, relations = \[\[2,1\],\[3,1\],\[1,4\]\], k = 2
**Output:** 3
**Explanation:** The figure above represents the given graph.
In the first semester, you can take courses 2 and 3.
In the second semester, you can take course 1.
In the third semester, you can take course 4.
**Example 2:**
**Input:** n = 5, relations = \[\[2,1\],\[3,1\],\[4,1\],\[1,5\]\], k = 2
**Output:** 4
**Explanation:** The figure above represents the given graph.
In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.
In the second semester, you can take course 4.
In the third semester, you can take course 1.
In the fourth semester, you can take course 5.
**Constraints:**
* `1 <= n <= 15`
* `1 <= k <= n`
* `0 <= relations.length <= n * (n-1) / 2`
* `relations[i].length == 2`
* `1 <= prevCoursei, nextCoursei <= n`
* `prevCoursei != nextCoursei`
* All the pairs `[prevCoursei, nextCoursei]` are **unique**.
* The given graph is a directed acyclic graph.
| null |
Database
|
Medium
| null |
81 |
hello everyone let's take a look at the code 81 switching on rotating starter route 2. so it's a follow-up of on so it's a follow-up of on so it's a follow-up of on the code 63 rotated started everyone and for this problem um if you haven't finished the coasters way you can practice that first then do this problem okay let's take a look at this problem so the biggest difference is that uh in on lincoln there's three all the numbers in the array are unique but for this problem there can be some numbers that with same value for example in this example 2 5 6 0 1 2 0 some repeated values if we want to check if target is in nums windows target is zero then we return true if target is nothing numbs so return first okay first let's assume uh what numbers are unique and go over the solution of statistics and extend seriously to this problem okay if all the numbers are unique we know there are two cases in general the first case is this one the increasing uh certainly a few increasing values then we go to the smallest value then the large increase versus one on the contrary at the beginning we have a larger increase then we go to the smallest value then there's a small increase here so by looking at some uh middle value we know which condition right first this one the middle value is smaller than the left so we know it's this condition if the middle value is smaller than left then if target is within middle to right then we know we should search right otherwise the research left for this case we know mid is greater than left so if target is wasting left to middle value we switch left otherwise we should write so every time we can drop half of the elements so every reason is log n but for this problem so some same values so mid is not always smaller or greater than left element for example array is seven one two seven it becomes this it's a long flat line that will go to smallest values so some increase then flat line again another example is there is still a flat line then we increase a little bit then we go back to the flat line so for this two example the middle value is same as left also is same as right so we cannot determine or we cannot deduce anything from these three values since the three values are same so we don't know like what the graph looks like in this case we cannot drop half the elements since we don't have any information so only thing we know that uh if target is left some can return to otherwise we can only move that by one so we can only move step by one instead of half of the element so the updated code is like this all codes are exactly the same except here so previously we have if else here we uh if midi is smaller than the left value we know this is the first condition otherwise if mill is greater than left number this is the second condition else we know it's pretty flat we don't have any information which we can do is to move the left by one so in the worst case all the elements in my area same so in this case we can just to do we can just do a like binary linear search so it's owen so this algorithm will be like degraded to the linear search in the best case other elements are different it will be in log in time complexity so the time complexity of this algorithm depends on the contents of the numbers okay that's it see you next time
|
Search in Rotated Sorted Array II
|
search-in-rotated-sorted-array-ii
|
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).
Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`.
Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 0
**Output:** true
**Example 2:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 3
**Output:** false
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* `nums` is guaranteed to be rotated at some pivot.
* `-104 <= target <= 104`
**Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
| null |
Array,Binary Search
|
Medium
|
33
|
207 |
The The The next question that we're going to see is the course schedule you number one okay what is the numbering of the courses from zero or are there 10 courses so from zero to nine are the courses you're going in other periods where prequels it's I a I B I INDICATE DATE YOU MUST TECH COURSE B FIRST IF YOU WANT YOU TO DO A TECH COURSE OK IF YOU WANT A POST THEN YOU WILL HAVE TO DO B COURSE ONLY YOU CAN COMPLETE A COURSE LIKE AN EXEMPLARY IS GIVEN IF ZERO ONE It is written that it means that if you have to do zero force then you will definitely have to finish one course. Okay, so if you have to return, what should you do? True, if you can finish all the courses and you have to return, true, if you do not return all the courses. Let's see an example. Look, we have two courses. It is necessary to eliminate zero, so first eliminate zero, all the courses will be finished. Let's look at another example. Here also there are only two courses, one zero and zero one. If you want to eliminate one, then one. So finish zero and if you want to finish zero then finish it. Now you cannot finish any course because there is a cycle here. Look carefully. If the cycle exists then we have to return the water. If the cycle does not exist then we will have to return it. Returning, that's all the concept of it and we are going to write a code of cycle dictation, let's check it once again, see what was the second output, if you want to eliminate one, then eliminate zero and if you want to eliminate zero, then eliminate one. Karo cycle exists, it means we can't complete everything. To finish one, we need 'Tu'. To finish one, we need 'Tu'. To finish one, we need 'Tu'. To finish three, we take mother. We need again zero individual. You finish people. But if you will not be able to finish any one topic from this cycle, then this is another extra thing, inside this we will have to check from each note whether there is a cycle because it is not at all necessary for this graph to be connected, it is not necessary. If there is any request for each course then like there is no request of hero inside this graph, if we start from zero and run the code of cycle dictation then we will not get the cycle and if we do not get the cycle then we will return the tour. Which will be wrong because we cannot finish all these courses, so we will run the code of cycle dictation starting from every note so that we will easily know whether we can finish all these courses or not So let's see how we are going to do this, first of all we will create a list of lists, we will put inside the list, we will start populating, start iterating, but before that, in this AdSense list, every At one place we will have to insert the name courses first so that later we can insert the values in it, so see how we will do that thing insert the values in it, so see how we will do that thing Now what we will do is convert it into a graph Okay Whatever subject is required, which subject is it, okay, one is necessary for zero, what are we doing to show this, if we have to show one is necessary for zero, then we have to do it. Here we are writing zero, now sir, we have converted it into a graph through look at it, now we will put DFS or cycle dictation code in it, let's start the code of how to do that, see, there are two things in it. There is a stock and one is invited, why will you be included in it, let me tell you, look, this is the director graph, okay, now this is our you, this is our three, and this is our one also wants you, three also wants you, okay like this Maybe and let's take 3 for 1, so is there a cycle here? Look carefully, there is no cycle, so that's why what do we have to do in this, which elements are still inside the start, any If you are accessing an element twice, it does not mean that it is a cycle. If it were an undirected graph, then you could easily tell that yes, I am accessing it twice, it means that there must be a cycle inside this graph, but the director Inside the graph, you can reach that element twice and maybe cycle no. So let's see how we code this thing. How will we tweet our code a little bit so that this thing will be adjusted for us, then we will make a saw, Instagram its size. Done These are the initializations from zero. If you are doing this in C+Plus, then do not forget to initialize it from zero after running the loop, doing this in C+Plus, then do not forget to initialize it from zero after running the loop, doing this in C+Plus, then do not forget to initialize it from zero after running the loop, otherwise your entire code will not work and a lot of time will be spent in working, so let's see further what to do. So we have made it, now what will we do, we will run it through each loop, the code of gravity is the code of grab direction, inside that we all pass everything Our widgetized and current note is fine if it is true from the story also. If the cycle exists then we will return it. If the cycle exists then we cannot complete the efforts. Ok, if it is not true even from the story then we will return it. If the cycle is not true then we can complete these courses. Okay. So now we just have to write this cycle dictation code, a small one and our work will be completed And Chauth is a wait, meaning currently, which note are we talking about? Now what will we see if this note is already there? It is inside the stock itself, meaning we went back to the same place from where we started, considering its neighbors. So what does it mean? Considering its neighbors, we came there again, meaning there is a cycle in it, so if this stock returns. Will give True, let me explain once what it means. If we go back to this note, A means cycle and whatever element we are considering, we will immediately make its value one in its index. It means we have checked it. If there is no cycle here then there is no need to check further, just return it and you will also get trapped in the infinity loop. Now, if these two things are not there then this is the new element which came on the next page of Instagram. Pay one and had also come for the guest. Next pay do one. What will we do now? We will go to all the neighbors and we will also do it tomorrow on request. We have to do it once Now what do we have to do after this if someone Through the same, what all we will pass is the agency list and the number of instan visited and current note. If the cycle has been received and if the cycle has not come from the story then return the dog water but before that remove it from the instan and the dog's current. This element has been removed from the tax Okay, so let's run it once and see once again I am telling you a simple cycle dictation code [ cycle dictation code [ cycle dictation code You can get free requests. Please tell me whether you can finish all the courses or not, when can it happen, I will try and it can happen only then, okay, so I was just thinking that this is the code of graph detector cycle dictation, a little too high. -Fi is not a small thing, is the code of graph detector cycle dictation, a little too high. -Fi is not a small thing, is the code of graph detector cycle dictation, a little too high. -Fi is not a small thing, look, we have written the code here of 20-30 lines and our question has been solved. 20-30 lines and our question has been solved.
|
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
|
332 |
hello everyone welcome to i'll go pundit uh today we are going to take a look at the lead called question number 332 reconstruct right now so this question is a very famous question and it's been asked in multiple companies like uber facebook amazon microsoft and twitter so let's take a look at this given a list of ireland tickets represented by pairs of departure and arrival airports from 2 reconstruct the itinerary in order all of the tickets belong to a main belong to a man who departs from jfk thus the itinerary must begin with jfk so the starting point the starting airport is jfk if there are multiple valid iteraries you should return the ordinary that has the smallest lexical order when read as a single string for example the idenary jfk lga has smallest lexical order than jfk lgb all our reports are represented by three calculators you may assume all tickets form at least one value dietary one must use all the tickets once and only once let's take an example here so we have uh the input which is a source to destination array of source to destination so this is munis to electro jfk to munich san francisco to sjc and uh lhr to san francisco so the output will be jfk munich lsr sfo and sjc so it easily we can understand that this is a graph algorithm right and graph problem and here we are talking about directed graph because we it's clearly saying that the source will be munich and the destination will be a larger so there is a direct relationship between municipal it's a one-way municipal it's a one-way municipal it's a one-way one-man relationship right but there is one-man relationship right but there is one-man relationship right but there is always you can have another uh another direction from lsr to munich but uh either way so this is going to be a directed algorithmic graph all right so what are the requirements here so the requirements are so given a list of dictionaries right so the this is a this is for a person who is travelled from started from jfk so the starting point is jfk and if there are multiple line arrays for the same source and destiny for the same source then we need to return back the smallest lexical order so the given example is jfk to lga and jfk to lgb so lga has the smallest lexical order then lgb so uh it should return lga lj should come first before lgb so that is the uh that is a constraint here right so how do we solve this so the first and foremost we need to construct the graph for that we are going to use the adjacency list so before we are creating the adjacency list as we need to take care of the lexical electrical sorting so we can sort the tickets in the lexical graphic load based on the destination sort based on the destination all right so that will make server life simpler and then we can create the adjacency list graph and after that we can perform a dfs traversal so to be precise this is going to be post order dfs traversal and then we can collect all the uh source airports and then we can return the result back all right let's take a look let's try let's start writing the code for this one so we have the ticket which is input let's do a sorting on it tickets dot sort a b a of 1 not local compare to b of 1. so this basically is going to sort the given input in a lexicographical order based on the destination okay so now let's create the graph let's take it off it gets then we need a map to hold the graph and this is going to be a direct graph so if graph of ticket so this is going to be let's do a destruction unit source destination graph of source encoder so initialize it with an empty array that i understand if the source is not already exists in the graph and now graph of source push the destination all right so now this will this loop will build up the adjacency list graph what next let's define a local variable for to hold the answer the result direct right and let's define the function dfs so take origin as a starting point so starting point will always jfk because this is for one single person who starts from the jfk so that's already given in the question so dfs or jfk so what we need to do here so first we need to see whether the origin exists in the graph so let's do a while loop on it graph of origin and also graph of origin.length right okay let's do one thing let's uh i'd extract this into okay let's leave it for now okay so now we have to do dfs of graph of origin let's get the first destination right so we already did the sorting lexical graphical sorting then we can do a shift right so when you do the shift it's going to give us the first lexicographically smallest destination from the list of destinations and then we can do a dfs on it and once we've done that let's push it into our answer okay so this will build up the answer so the only problem here it will be this will be in a reverse order so what we need to do is let's reverse the answer okay so let's take an example of this one so the graph structure is going to be muc mbc has a lecture as one of the destination that's it has only one destination now let's take a look at jfk has muc also yeah so that's the only one destination for jfk now let's take a look at sf4 this of course has a destination of sjc and uh let's take a look at a lstr okay that lecture has a destination of sf4 all right so this is our adjacency list so we consider all the vertexes all the sources in the graph okay so when you iterate over it right so the starting point will be jfk so it to start from jfk then it will go to munich from units it will go to lhr and then it will go through sfo and then it will the final point will be sjc so the answer will be jfk munich lhr sfo and sjc as it is a post order traversal we are pushing the last element last vertex first so that is sjc and then sfo and then in hr and then munich and then jfk and then finally we do the reverse it will give you the correct result assume we have multiple data elements multiple destinations right so let's take this example jfk sf4 jfk atl sf4atl atl jfk atlsfo let's take it let's try to create a adjacent adjacency list so jfk has a destination sfo and s plus atl and sf4 has atl as well as there's only one okay and atl has gfk and sf4 right so jfk sf4 and atl sfo has atl as a destination then atl as jfk and sf4 as we already will be sorting this by default uh when we get the input so we let's sort this out let's sort the adjacency list right so atl and sfo atl and this is the correct one okay fine so now what happens here so we start from jfk right so from jfk we start the dfs traversal and then we shift the first element so that means atl will be the first element then we'll take atl and then we'll take the first one so atm will be jfk so jfk will come back and so jfk the for next and next iteration to jfk will be sfo so let's do the sf4 here sfm will come back to atl right and then we'll go to the next state element which will be sf4 a so the traversal will be jfk atl the person will come back to jfk and he'll go to sfo then again he'll go to atl and from there he'll come back to sfo so yeah so this will be the uh path and like i mentioned as we do postal traversal uh it will be in a reverse order and then finally when we return the answer we have to reverse it and then we have to return it okay so let's try to run it so jfk okay let's try okay there is only one let's try to add uh this example let's try to run it yeah so looks like we are getting the correct output for all the given input let's try to unleash the complexity before we submit the problem so we can see this one is going to be order of n log n because it's a default sorting algorithm it will take over n log n and this loop is going to be order of n and because we are going to hydrate over each and every ticket and here we are going to do dfs algorithm dfs traversal this will be order of v plus c vertex plus edges right order of p plus c so the final complexity will be and this is again order of n because we are doing the reversal so final complexity will be order of n log n okay plus order of n plus order of v plus e plus and then again there is an order of it and uh which will come to order of n log n which is because that is the hype uh because that is the top one right the rest everything is like smaller than order of n log but yeah we can say that it is order of n log n plus order of n and then worst case complexity and space complexity will be uh it will be the graph complexity right so graph basically uh in a worst case scenario it create n entries in the graph and the vertex basically so it will be order off order of e which will be the space complexity here okay and plus we can say that dfs traversal which is the equation you can say it will be under the order of ps ctrl v plus cs okay so that will be the space complexity all right so as now we have calculated the time and space complexity let's try to submit the problem okay so i have been already working on it with multiple solutions and so this is the best uh possible solution which i could come up with where it's 108 milliseconds and faster than 41 percentage of javascript submissions all right i hope you understood the problem uh thank you for watching we'll see you later thank you
|
Reconstruct Itinerary
|
reconstruct-itinerary
|
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
* For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`.
You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
**Example 1:**
**Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\]
**Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\]
**Example 2:**
**Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\]
**Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\]
**Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order.
**Constraints:**
* `1 <= tickets.length <= 300`
* `tickets[i].length == 2`
* `fromi.length == 3`
* `toi.length == 3`
* `fromi` and `toi` consist of uppercase English letters.
* `fromi != toi`
| null |
Depth-First Search,Graph,Eulerian Circuit
|
Hard
|
2051,2201
|
10 |
hello friends my name is Tushar and today I'm going to talk about how to do regular expression matching using dynamic programming in another video I talked about how to do wildcard matching using dynamic programming today we're going to talk about a regex matching so the question is you're given a pattern consisting of characters and two special characters star and dot add the text you have to say that if this pattern matches the text or not so what does star and dot means star matches zero or more occurrences of character right before the star and dot matches any signal capture so let me help let me explain this with example so a dot B so here we can have any single character between a and B so for example if my text is a C B and if a pattern is a dot B then that is a regular expression match a B a xB all of them are regular expression match as long as there is any single character between a and B on the other hand a b a c b YC b are not a regular expression match with a dot b another example a star b here what we are saying is we can have zero currencies or more occurrences of a followed by B so if my text is B and if a pattern is a star B so that's a regular expression match because we can have zero occurrences of a similarly a ba BAA V all our regular expression match on the other hand is not because we need one B at the end also ACB is not a match because there is no C in this regular expression in this pattern let's take one more example a star B dot star one so here we can have zero or more occurrences of K then we need to have one b and then you can have zero or more occurrences of any character so dot star needs dot means any character star means zero or more number of times a character so way between b and y we can have zero or more of any characters and that will be that expression match so let's see b1 so here dy has zero occurrences of a then we have B and then zero princess of dot star and then this is y so this text matches this pattern on the other hand b and y also matches this pattern because we have one l between B and Y and 0 prints off a BL y a B LM what all of them are match with this like regex with this pattern on the other hand ey is not a match because we need this B a B is not a match because we need this Y so these guys are these text doesn't matches this pattern so next let's see how we are going to solve this using dynamic program so first let's look at the recurrence relationship or how we are going to fill up the table in bottom of dynamic programming so here T is a two dimensional boolean matrix where I is the index in the text and J's index in the pattern so if T IJ is true it means that till I to value and text and J value in pattern there is a regular expression match so how does T IJ gets its value so if string of I is same as pattern of J or if pattern of J is dot in that case T of idea will become T of I minus 1 J minus 1 because value at I matches that energy or pattern J's dot so those characters are already matching so without them or removing them from text and button whatever is left we check if that is a regular expression match or not and that value is coming from T of I minus 1 J minus 1 on the other hand if pattern F J is star in that case we have two conditions one is if we can have 0 occurrences of the value right before this pattern J so it value pattern of J minus 1 for a conducting at 0 occurrence you look at T of I J minus 2 or we could have one or more occurrences of the value right before pattern and we can only apply that if string at hai is same as J minus 1 or pattern of J minus 1 is dot so in that case this takes a value of T of I minus 1 J so basically a value at the top and otherwise this takes a value false if this is not clear it's ok because I'm going to take an example and hopefully that will clarify this logic very clearly in this example the pattern is going to be X a star B dot C and text is going to be X a B Y C so first thing we do is we take a two dimensional boolean matrix the number of rows and number of columns in this matrix is going to be one more than the left length of the text and length of the pattern then first thing they're going to do is we're going to initialize the 0th column and 0th row so false let's look at this value T 0 so this value here I have said true why because if we have an empty string and if we have an empty pattern then be able to count that as a regular expression match which is why this p 0 is true then let's fill up the 0th column so when i filling up the 0th column i am considering this i have n mt i have an empty string for a pattern and for my text i can have any value which has at least one character if that is a case that will never be a regular expression match which is why this 0th column is all false now let's talk about the 0th row so if my pattern looks something like this is star or a star b star what is possible here is that this guy can match with an empty text if a texas empty that still has a reject regular expression match with a star b star because we can have 0 class of a and 0 press of B so if we had something like this if you have your pattern looks something like this then we would have true values on the Z wrote on the zero true but in this case this pattern with this pattern there is no way that any value will be true which is why I have set all the values as false so now with our 0 throw a 0th column set let's move on to the t11 for the simplicity purposes purpose I am assuming that my string my text is starting from my text index and my pattern index is starting from 1 instead of 0 so T 1 and we are here so XT 1 what if you're checking is this X same as this X they are same so what we're going to do is we are going to say what value GRU takes so since string of I same as pattern of JP of I a becomes T of I minus 1 J minus 1 and T of I minus 1 J minus 1 this value diagonal is true so this value also becomes true again if my text if my pattern is X and my text is ax and since they are match so we can remove them and what we are left with is two empty strings and those are the strings were also a match because this value is true so since that is a match and adding X is same value so adding X will also continue to be a regular expression match which is why this value is true next our neck be move on to the next column here the value in the pattern is a and value the text is s X is not same as a so we come directly to this condition and this is false next the value our value the pattern is stored so the value of the pattern is stored we hit this middle condition so in this case we can have 0 crunches of cat to write the 4 star which is a or we can have one or more occurrences of a so in this case for 0 friends what we're going to do is going to stay on the same row and move to back so State v around Israel and we'll move to back and take this value so this value is true so we can take this value that's true as well so let me clarify so here we have X a star and here we have X now a star can represent zero or more occurrences if we considered zero occurrence of a in that case this doesn't exist and we've only have X and we already know that this ax matches this X has a regular expression match with this X because this value is true so we can just take this value true and move it here and you can assume that there are zero princes of a which is why this value here is true next B is not same as X so this one is false dot is dot matches any character so we again hit this first condition where pattern of J is dot so we take the value of I minus 1 J minus 1 so the value of I minus 1 J minus 1 is false this value here so this Reggie also becomes false and C is not same as X so this value it becomes false next let's fill up the next row so now we are able to match this a and this X so the values are different so we take this false value and this becomes false then we match this a and this a so this a is same as they say so we hit this first condition and take the value of T or PI minus 1 J minus 1 so this value true here so this value also becomes true let me clarify so here what pattern is X a or text is I'd say since this a matches this a then we are just going to check without them is rest of the regular pattern matches whether with the text or not and it does because we this one is true so we just take that value here so the next character after this is star so if it's a store we hit this middle condition so first we check is does a can counting 0 occurrences of a work so if to look at that we go two steps back and this value is false so since this is false it means that we cannot consider 0 grunts of a so then you're going to check is the character before star is that same as this chiropractor before star is a which is same as this character which is this condition here so then what we can do is we can look at the value at the top and this value is true so this value becomes true so let me clarify so we have X is star and we have X so first we try to see that does zero currents of a works for that we get rid of a star and we see that is this a regular expression match and for that we check here and that is not a regular expression match if the pattern is X and if my text is X it's not a regular expression match so that value is false so then we check can we consider one or more occurrences of a so since this character the character Y before star was a which matches with this a so then we can consider this as a part of this a star so we can get rid of this a and the check is X is star a regular expression match with X and that value is stored right here the value at the top of the square we were filling and XF star is a regular expression match with X which is why we took that value as T so basically adding a is also going to be a regular expression match then a is not same as B so this value is false dot is the dot can be any character so we get this first condition and look at T of I minus 1 J minus 1 so we look at the diagonal argument that is false so this becomes false and C is not same as a so this value is also false let's move on to the next row so a is not same as X so this value is false is same as a so we look at the diagonal value so we have X a and the f X ie so this a same as this is so we check is rest a regular expression match so this value is not a regular expression match so this value also becomes false a so now our next character in the pattern is star so he need this mill condition so first we check does skipping does having zero prints of a words to do that we go through steps back and this values false so the padding:0 prints doesn't help so the padding:0 prints doesn't help so the padding:0 prints doesn't help then we check is the character before star same as this one so this is Z and this value is also 8 so then you can look at the value at the top so the value at the top here is T so this value the value at the top is true so that's why this value will also become true again let me clarify exit star x ka so since the character right before this star is a so this it could be the part of this a star so we don't consider this a at all and C is rest of this a regular expression match and that is sort right here and this was a regular expression match so we can use that value to infer that adding a is also good continue to be a regular expression match which is why this value is true and which is why we look one row of T of I minus one J next B is not same as a so this value is false dot is matches with any character so we look diagonally this value is false and this becomes false and this will be false finally we hit B so B is not same as X so this value is false B is not same as a so this value is false if we hit start so first we check is 0 occurrence of a so for that we move two steps back this value is false so 0 friends of a doesn't work then we will check is the character right before star same so Katherine to first star is a and that is not same as B so we cannot even apply the other condition T of I minus 1 J so this is false this B is same as this B so then we will check we have this first condition I am going to check without these two beasts is rest of the regular expression of match and that right here and that is a match so this list also match again X a star B and X a B so this B and this B matches so we get rid of them and C is the rest of the regular expression of match and that value is coming from here and that was a match so we just reuse that value to derive that adding B will continue to make them a regular expression match B dot I take any character so we look diagonally up this one is false this is false and this will be false now we our character is why Y is not same as X false y is not same as a false star so we look to back this is false and character right before star is not same as Y so this will be false so none of these two condition this condition does it work y is not same as this so this is false dodj can take any character so I can take Y so then they look at the diagonal value dagger is true so this becomes true again if we have X a star B dot C X a B Y so B dot so this dot can match with Y so we get rid of them and C is rest of the string and at X and pattern regular expression match they are because this one is true so this value also becomes true and finally Y and C is not a match so force and C and X is not saves a false star will not work with C so false dot and this guy seems availab diagonally this value is false and finally this C same as this C so again we hit this first condition and we look at the diagonals and that one is true so this also becomes true so this is our final answer so this pattern and this text do have a regular expression match so the time complexity for this algorithm is o of M into n and space complexity is also go of M into and next let us get the hold for this algorithm main function here is match regex it takes in a character array text and a cat to a pattern and it returns boolean saying that this pattern matches the text or not first we initialize a two dimension boolean arity where the number of rows is text dot length plus 1 and number of columns is pattern dot length plus 1 then as we discussed before t 0 is true this for loop here deals with the zeroth row where we set some values in the zeroth row true if we have a pattern like a star or a star b star or a star B star C star something like that so after we are done doing all this is where the meat of the logic is so I starts from 1 and goes all the way to T dot length and then J starts from 1 and go all the way till T 0 dot length plus 1 and then as we discussed before in the video if pattern of J minus 1 is dot so here over pattern is the zeroth bit based index which is why we are looking at the JIT minus 1 value and similarly for the text I am looking for I minus 1 value because our ints are starting from 1 instead of 0 so if pattern of J minus 1 is dot or if pattern of J minus 1 is text of I minus 1 then T of IJ becomes T of I minus 1 J minus 1 and sift pattern of J minus 1 is star then T of IJ first becomes T of IJ minus 2 and if pattern of J minus 2 is dot or pattern of J minus 2 is text of I minus 1 all this we discussed before in the video then T of IJ will be either whatever the value of T of IJ is or T of I minus 1 J and if none of this happens then T of IJ is false and then we keep doing this till both the for loop reaches reach their end and in the end we return T of text dot length and pattern dot length which is the value at the bottom right corner so this is all I have to talk about regex matching please like this video share this video check out my facebook page and check out my github link thanks again for watching this video
|
Regular Expression Matching
|
regular-expression-matching
|
Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where:
* `'.'` Matches any single character.
* `'*'` Matches zero or more of the preceding element.
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "a\* "
**Output:** true
**Explanation:** '\*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa ".
**Example 3:**
**Input:** s = "ab ", p = ".\* "
**Output:** true
**Explanation:** ".\* " means "zero or more (\*) of any character (.) ".
**Constraints:**
* `1 <= s.length <= 20`
* `1 <= p.length <= 20`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'.'`, and `'*'`.
* It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match.
| null |
String,Dynamic Programming,Recursion
|
Hard
|
44
|
91 |
which look like a magazine me model before you question right flexing like a pogo how's it going guys today you don't want to go over a question called decode ways this is a question that's being asked by Facebook right now so a good question to know it says a message containing letters from A to Z is being encoded to numbers using the following mapping a maps to one B maps the to C maps to 3 so on and so forth and Z maps to 26 so it says given a non empty string containing only digits determine the total number of ways to decode it so just as a quick example if we're given a string 1 2 there are two ways to decode it we output 2 and the reason for this is it could be either decoded as a B which is 1 and then 2 or L which is simply 12 this is a common dynamic programming question or at least it's modeled as one I feel like this is typically kind of a kid this can basically be disguised as like a climb stairs problem I feel so it's kind of like a variant of your typical dynamic programming question you might see or one of them and we're gonna solve this by using something called bottom-up by using something called bottom-up by using something called bottom-up processing sounds really scary it sounds really complicated but basically all it's saying is if you're asked to determine how many ways are ready to code a string of length and you're just going to use all the subproblems up until end to actually solve the problem so what we do is we start with a base case and we determine what the answer to the base cases and then we build from those base cases and eventually solve the problem for n so let's do that now so what we're gonna do is we're gonna make a dynamic programming or array so say n DP equals new int s dot length plus 1 and the reason why we're saying plus one here is just because we actually want to account for the number 0 right if we have no string and we also want to return really the length or the number of ways to decode a string if it's of the length s so we want to make sure we include plus 1 so now we're getting to our base case so we said we're gonna use all our subproblems to solve the larger problem that we're she asked so we want to start with our base case so our base case here is just going to be if we have a length of zero right so if DP of zero what's that can equal it's going to be 1 and so just to make sure I'm explaining this correctly DP is going to store the number of ways to Dakota string of length X or Y right so DP of 0 really represents the number of ways to decode a string of length to 0 which is 1 because there's really no way to decode an empty string now similarly we could just say DP of 1 is also equal to 1 sorry that's wrong DP of one is going to depend on what the value of the first character is so if we look at our mapping again a maps to 1 right so we actually don't have a mapping for 0 so the only thing we need to pay attention to is if our first character is 0 or not so you could say s start care at 0 and if that's equal to 0 then we don't want to have anything we say there's no ways to decode it right because we actually don't have a mapping for 0 and otherwise if it's anything else it's gonna have a mapping or enough one way to decode it so now we have those two base cases really right we said the number of ways decode a string of length 0 is 1 and the number of ways to decode a string of length 1 is going to depend on whether or not it's a 0 so now we can just iterate all the way up till s is length so we'll say for int I equals 2 because we already solved the subproblem 0 and the subproblem 1 while I is less than or equal to s dot length and again this is because we want to know for s is length right we want to include s is linked we don't want to get cut short so now in every situation we want to use our subproblems right so the first thing we want to do is actually evaluate the digit we're on so we're gonna look and evaluate the dujour on so let's do that so we're gonna say int and we'll say one digit equals integer value of and we're gonna say s dot substring of I minus 1 up till I so all I'm doing here is desert value of seems a little complicated but all we're doing really is we're getting the substring of the current character so we're just getting the current character we're on converting it to an integer and now we have it stored in one digit and now the next thing we want to do is we want to get the last two digits or the current digit in the previous digit and the reason for that is because our mapping only goes up to 26 right so it has to be between 1 and 26 so that's why we're getting one digit in two digits because three digits doesn't matter right we can't have a mapping as three digits long so now let's get our second digit so we'll say in two digits and we'll say integer value of s substring of I minus 2i so again it's the same exact thing we're just getting the last two digits now or the current digit in the previous digit combined together and turn into an integer so now we want to do is you just want to check do these things have mappings right so if one digit is greater than or equal to 1 then we know there exists a mapping so we want to add to the current sub problem that we're trying to solve all the possible ways to decode the previous digits which will be represented as the maximum ways of decoding those digits right which is conveniently our DP array so we'll add to our current subproblem the answer to the previous subproblem and now we want to do the same thing but for two digits right but we need to specify something different now right we need to make sure it's greater than or equal to 10 and also less than or equal to 26 so we'll say if 2 digits is greater than or equal to 10 and 2 digits is less than or equal to 26 then we know it has a mapping so we can add to the current subproblem DP of I minus 2 so guys it's really as simple as that so now once we actually have filled our entire DP array up till the end all we need to do is return DP of s dot length and remember the reason why that will work is because our DP array stores the maximum number of ways to decode the string up till that index and the index represents the number of characters we have so this is going to represent in and the number of ways to decode a string of length s or s is length in this case so let's make sure that this works so guys that was using bottom-up works so guys that was using bottom-up works so guys that was using bottom-up processing to solve the leak code question the eCos please it was helpful and help you understand dynamic programming do me a favor give me thumbs up I actually end up doing this question because someone in my disc or channels asked me to do it and throw in a DP problem so if you guys are interested in joining that channel this course server I'll leave the link in description enjoy the video subscribe
|
Decode Ways
|
decode-ways
|
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping:
'A' -> "1 "
'B' -> "2 "
...
'Z' -> "26 "
To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into:
* `"AAJF "` with the grouping `(1 1 10 6)`
* `"KJF "` with the grouping `(11 10 6)`
Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`.
Given a string `s` containing only digits, return _the **number** of ways to **decode** it_.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** s = "12 "
**Output:** 2
**Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12).
**Example 2:**
**Input:** s = "226 "
**Output:** 3
**Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6).
**Example 3:**
**Input:** s = "06 "
**Output:** 0
**Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 ").
**Constraints:**
* `1 <= s.length <= 100`
* `s` contains only digits and may contain leading zero(s).
| null |
String,Dynamic Programming
|
Medium
|
639,2091
|
98 |
hey what's up guys nobody right technically stuff on Twitter in YouTube check description for all my information we're gonna be doing valid binary search tree my grandma's house but I did not want to miss a day of uploading so a medium problem given a binary search given a binary tree determine if it's a valid binary search tree okay so we're giving a route to a binary tree and it's gonna be called is valid BST it's a boolean method we're gonna return true or false whether it is a valid binary search tree so each node we can see has a value a left child and a right child leaf nodes you know like 1 and 3 here right the nodes at the very bottom you could say you can see they don't have children so their left and right values would just be null okay so we're gonna start at the root and you know we're just gonna traverse the tree and make sure it's a valid binary search tree it says assume BST is defined as false left subtree of a node contains only nodes keys less than weight left subtree of a node contains only nodes with keys less than the nodes key okay right subtree only contains only nodes with keys greater than the nodes key so they're not allowing duplicates by this definition so we're gonna have to check against duplicates as well so both the left and right subtrees must also be binary search trees okay so what they're just saying is if you guys don't know this yeah this a BST binary search tree is just where the left children are less than the root in the right children are greater so 1 is less than 2 and 3 is greater than 2 so that is correct that is a valid binary search tree see would return true on this input here but if you look at an input like this where we have you know 5 1 4 3 6 right 1 is less than 5 so the left is less than the root which is good but 4 is also less than 5 and 4 should be on the left in that case so this is not valid and it gives you that exact answer right there so how do we do this how do you traverse a tree right there's a few traversal methods there's very popular ones right so there are you know in order pre order post or those are popular traversal methods and these are just referring to the order you traverse than root note right so out of three nodes right there's a root node and then there's the left and right child right so the root node in pre-order pre means first so it would be pre-order pre means first so it would be pre-order pre means first so it would be root then left right post order root is last so left right root in order root is in the middle so you got left root right so we want to do in order because if you actually look at it in order is a sorted version so binary search is done on sorted arrays binary search trees you've gotta see this traversal pattern as being sorted you know 1 2 3 right that's actually pretty much sorted so from left to right is sorted in a left root right is gonna be sorted in order traversal so we want to make sure that it is sorted right so that's why in order is kind of the one we're gonna go with you we can do this iteratively now there are some weird test cases in this problem so we're gonna have to actually use a double at some point in this problem to handle they do like very high double integer values so we're gonna be using a double and the main idea here is we're gonna use a stack here's the main idea of this problem how we're gonna solve it we're gonna look at this root we're going to traverse all the way down the left side so we're gonna go to the least you know hi the smallest value node sorry my dogs barking the smallest value node in the entire tree and we're as we traverse all the way down the left side of the tree we're gonna be pushing values onto a stack parent node values and then what we're gonna do once we fill up the stack is we're gonna start popping stack values off so the stacks gonna get filled with parent nodes we're gonna traverse all the way down the left side and we're gonna pop stack values off and as we do this we're gonna you just keep referencing you know more and more parent nodes and making sure that the order is in place so hopefully that kind of makes sense so here we go we're just gonna set up our stack of tree nodes here we're gonna set up this double this is gonna be left child val is equal to negative doubled Val you gotta use this because it's weird our main condition is while stack is not empty or sorry root is not equal to null so we use this condition because we're gonna be filling up a stack so while it's not empty we're gonna want to keep traversing but also we want to have or route is not equal to null first because we need to enter the loop there's gonna be nothing on the stack originally so the route isn't null hopefully if it is null we're just gonna return true anyway that will discount that as a valid binary search tree that's how the problem wants it but other than that it won't be null right because then there is some kind of tree so it will enter this loop now within here we're gonna say while root is not equal to null and we're gonna make root no we're gonna traverse until root is null but this won't break out of this loop because we're gonna fill up the stack within this loop right so we're gonna traverse until root is null all the way down the left side like I said and fill the stack up with values push values onto the stack push them onto the stack and these will be parent values right you could think of it as parent values because 5 is gonna go on the stack then one's gonna go on the stack or two is gonna go on the stack then one's gonna go in a second in this tree example it would be one on the stack then two on the stack then four on the stack right so we're pushing these parent values onto the stack root equals root dot left and we're traversing all the way down the left side now once we actually fill up the stack with all of these values when we traverse all the way the left we can start popping values off the stack and this is just gonna be a parent value right here now we want to make sure that the parent value is definitely not less than the left child value should always be less than the parent value and we're gonna return false that's why we can return true outside of this loop because we're returning false we're doing all of our checks to make sure that it's good within we're trying to disprove within this loop that is a valid binary search tree so if we find any discrepancies here or we find an error in the binary in the structure of the binary search tree we'll return false and then if we make it through this entire loop we can return true right so the only check we really have to do is okay is the left child less than the parent if that's true we're gonna be good right and each level right we're traversing we traversed all of the left notes right we're always traversing the left notes because within each iteration of this loop we're checking are we at the left most node we could possibly be at this current level and if not we're gonna keep going putting on the stack and we're always doing the parents because the parents are essentially left nodes anyway of you know the parent like every left node is pretty much gonna be some kind of parent in a bigger tree right so you know the parents get popped off so we got the parents covered we got the left notes covered the only thing we don't have covered is we do have to traverse the right side at each level if there is a right side so we just have to do this root is equal to root table right in each level and we do have to assign this left child Val whenever we do at right after we do this check it's like the left we go down the left we put all the nodes on the stack these are parent nodes and we compare against left child Val it's a minute first because it's gonna be the very left most node anyway so after it's a very MUC mo so we come around again right so if we put one in five on the stack or two and one on the stack we look at one and it's gonna be null versus one it doesn't even matter we have this negative double so we're gonna say is one less is a one less than the minimum value possible no obviously not okay but then we go to two is two less than one because it's just gonna be the previous value because we signed left child value to the previous root so the root is the parent right it's gonna be one and then is one less than this minimum value no and then we say okay left is equal left child value is equal to one and then we go around and then two gets popped off the stack okay is one less is two less than one no and then you assign the next one but you always have to check to the right no to so when you get to two then you say okay root is equal to three okay so now you know what I mean it keeps going so basically you put all these parent nodes onto the stack you pop up you know each iteration of the loop you're making sure you're at the leftmost no within this loop filling up the stack making sure you're filling up the stack you're popping those parent values off making sure the left is less than the parent this is parent less than the left and whenever there's write notes to traverse you make sure you go down those bright paths too with this line right here that's it you just prove within the loop and you return true on the outside so I'm one of my grandmas sorry if it was a little bit different than my videos I don't even have my mic I didn't you know maybe there was a interruptions or anything but I don't think it was that bad so I just want to make sure I post every day because I want to grow the channel and yeah that's it so please like and subscribe to help me do that and you know I'll be back in my house later today and I'll be maybe screaming working on some more videos for you guys thank you guys for watching comment below videos you want me to do ask me any questions you got and yeah that's pretty much it see you in the next video alright
|
Validate Binary Search Tree
|
validate-binary-search-tree
|
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_.
A **valid BST** is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** true
**Example 2:**
**Input:** root = \[5,1,4,null,null,3,6\]
**Output:** false
**Explanation:** The root node's value is 5 but its right child's value is 4.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,501
|
493 |
Find employment in solve problem on device only code fennel is big problem he sees first life interiors name do the number of river in the rate and condition was one to three condition on the side and our which main condition of that one meaning from name will be Gare In which the meaning of age will be eye number index. Ok if you type eye number intex aqua simply then it will be like this. Eye should be Great Dane jan22. What does it mean? Does it understand the meaning if you are here, let's say if you are here enjoy fear then the condition is like this. There should be, meaning the condition should be justified, two grated is 10.22 and Abhijeet is right, there is grated is 10.22 and Abhijeet is right, there is grated is 10.22 and Abhijeet is right, there is nothing like this, you are from Greater Noida, so this condition is from f4, it means love cannot be formed for 214, right toe, in which cases such a pair can be formed. He sees, let's go, so you can see, if it happens that I am here, then the phone number in taxes and things is this Wolverine Dipper, so what is the condition, let's check, if you can see here, I am greater than 2G. Condition aa bhaiya for better than two into one, condition is through for better than two, such conditions can happen, so if there is Fukushima-1, then we have got a solution, Fukushima-1, then we have got a solution, Fukushima-1, then we have got a solution, right one lovely one has come, so we have a new one, what more love is there in this, like this Condition is deciding if there is any such love then let us check then in this case you can see that if I come to our three, if it comes to one then the condition will be fulfilled, meaning we can see that this condition is going to happen. Means I3 was nh32 * Vansh yes bhaiya free is Means I3 was nh32 * Vansh yes bhaiya free is Means I3 was nh32 * Vansh yes bhaiya free is more so he is just proud so we can become eid pair so first we had love and now this lovely will go total to two means total account is done second solution has come and Can any love be formed that you brother, if it has come on the face and on life, then it will become a pair of Kayan, will you chew and check? What is the condition of such a condition? Five pleased and mother should be better than two mother. Two into one, what check is cut and yes brother, if you share more than 532, then our condition is two, then this chapter will be created, so earlier we had one day has gone and one day has come and a total of three lights, it cannot increase further, right, so If we can't go any further then we have three solutions in total, so we have to bring 13 in the output, that is, how much love can be made in the total, there we need the right simpler in the output, now brother, what will be its solution, so first see what is the root solution right? Draft solution can be like this, suppose we had ai here and we had g vidh meaning Jaymala, previous song will start. Okay, there will be fail point on the front, we have taken it at two points, now what will we do, then we will complete it on less. And we will check what was the condition of foundation and cigarette argent or right, so is this condition definitely present? Is it two Great Danes? * * It is not there, brother, you Great Danes? * * It is not there, brother, you Great Danes? * * It is not there, brother, you can never be like this, right to body, if it is not so, then move this point forward. Two ok ji, now it has come here that r two can be such a condition means two great day three * may be means two great day three * may be means two great day three * may be no brother two greater than six cannot be then ok Jaipur will move ahead will come here will do with the foundation no me too Is it possible here, can he check, can you check, can it be two into one, no brother, it will break and become equal, that means it cannot be greater, so brother, it is okay, there is not even a condition, so do one thing, start again and then If there is a selection then it will come here and where the I Plus people will come, rate OK ji laddu will be on 43rd that you for data entry into one can be 323 324 can be for better than six can't send it is ok Take it forward, this is how it will be done here, can the forbidden fail for the letter 10.22 No, Vijay B, it cannot for the letter 10.22 No, Vijay B, it cannot for the letter 10.22 No, Vijay B, it cannot be done, ok then do one thing at o'clock, is there any team off, can this be done? Yes, it can be done with Bhaiya also, let's decide right there * Yes Brother, decide right there * Yes Brother, decide right there * Yes Brother, this is forbidden, so what will you do, and this is what will come, you will make it 14, you will not make love into a math, first work on an account, hello, okay, make comedy t-20, as soon as you an account, hello, okay, make comedy t-20, as soon as you an account, hello, okay, make comedy t-20, as soon as you do, remove the zero and Do that, i.e. do, remove the zero and Do that, i.e. do, remove the zero and Do that, i.e. press the account and make it powered plus, then the work will be done. Now our master, our Aayi will come here, he was here, now our Aayi has come here, the one from I Plus people will come here, right now Kallu 2315, what condition did you take, justify it. Please check and tell me if it is 512, no brother, it is not a condition, then it is okay, I will move ahead, where will it come to you tomorrow, ohri grated no1 * it can be like this, yes brother, it can be 322, it * it can be like this, yes brother, it can be 322, it * it can be like this, yes brother, it can be 322, it can have an album if it is like this If it becomes pollution free then it is okay then remove the forest and make contrast plus, it will mean right, ok, I will stop from now on, because it is outdoor, it will start within seconds, so it will come here, NGR will go here, ok, check once. Do it bhaiya for fy11 yes bhaiya let's check 5 can be done which means greater life Chotu *vansh yes bhaiya can be life Chotu *vansh yes bhaiya can be life Chotu *vansh yes bhaiya can be five better than one can be so ok who is in this tour so do one thing for two Remove two and make it work plus and make it free and return it for free. It is simple that you can make iodine. If there is edit pollution then how will you do it? If he sees it then we can code it basic like this. I said, I took 120 earlier, I told you. On this, get the account first or it is okay if I can work after this, then start with friends, the loop is fast, start with the right suggestions from here, turn on the net and check, it is okay for I Plus One, I password means wherever. And fold two to less, how many means, check the condition like this, if it matches with the point, then do control plus. Here you can write that the condition from zero is plus, it had become soft, that thing would have happened by doing like this. If we get three news, then return three samplers. Simpler, if you do like this then what will be the solution? No brother, we will get slow duty because for this there is a mixture of time, that is aversion, why that on inch because we say follow the history. For loop is slow and steady state cooperative one means consensus on Tuesday, there is no problem but we have to introduce time complexity a little, so definitely see how you can activate it. If you want to watch this video, means you want Optimus solution, then which phone? Whatever you need, I will tell you the marks and you will need marks and Suraiya, in this video of yours, I will explain mine, I will explain it very well, there is no problem, just watch the video, you will need it in the front, there will be legal hurdles, the problem which I had solved, you are the one. Earlier I thought you play the playlist and you will get it ok and it was a very good marriage if you want then you can watch it. First we understand that Master's desires kill very simply in tears and divide the market then who will do it? Let's give what it means, let's say it's a rock, okay, I've tried it's a rock, stop, let's say there is a garage with it, fold it, send it to me, stop, let's say it's an average, okay if we If we divide it into pieces then the rock will look like this, it will become white like this, it will become a device like this, some things may be small like this but in the end all the elements will be divided into small parts like this, okay then what will we do with it? Understand the country, we will add this dress, by adding it like this, one will pass and by adding two parts like this, a little bigger pass will be passed, then what will we do, we will add 125 and like this one Shravan will go, then what will we do, we will add it like this. The word will be formed, we will add it and it will be formed like this, so by doing this we will fold it. Okay, for now let's assume that we have six preventions, how will we join it, divide is very important, how will we divide, if I divide then it will be like this. I will make it midnight, okay, so we will divide this also by chilli, we will get it from the media, I will get it from the transaction want two three four five six seven, if we divide this trend by two then we will get it, so if you point the mit and divide it. If you give a text like this, it will appear on the website OK and right part means this area will go to the right OK now on the wrapper, if you divide it again, what will happen 4126 will come home, it will become wrapper. And if you delete it will become 2130. I will give it again like it. If you divide 1070, it will become 1017 Leopard. After this, the C divider will become the white part. Now if we divide it is simple, party one first. After this, it will go to 342. After this, Twenty Metal Twenty-20 will After this, Twenty Metal Twenty-20 will After this, Twenty Metal Twenty-20 will become 3230, meaning this is left right, this is the point, so we do not have to device it, so you have finally got Singoli, it is right, so we have Successfully divided this nice rock in such a short path, so now what will we do, if we angle it, then how will we do it, if we give it, then that saint made forget this point, okay ignore this point, so now accept that I did. Had you divided earlier, had you edited the ride, then you would have said, if you have been divided, then why have you made such a structure, then look first, I have put a monk here at the back, right, first our security station was from there, you can see the fee structure was 5126. Till 2030 it was from 30, I divided it and brought it like this, after this it felt like this, after this it was brought like this, it was divided while doing it was right simple, so after this, what did I do by turning it on, how who will do it, what does it mean? Who understands the meaning of doing, who does the meaning of what will I do? Patwan is started, find dry ginger in it, what will we do if it is started in some school, we will return it. If it is sorted, we will return it. Now look, 4123 Kshayari has been made, now we will give it a shot soon, it is fine. We will start, after starting, then we will transfer this to this and we will start this again, we will transfer this, by doing this we can turn it on, so see how I controlled it, you can see the quality is 120 sprite single element means 34 points if There is no album Singh Gill, it is not shifting, we know this, first it went here and then it became soft, 2051, then the one which is 2031, came here and the one which is 2139, I came to the spot and saw that 2130 Singh. This is the element, I transferred it and saw 3128, I shocked it right, now look at the left side, this is the right side, so we will check the left side first, I set it first, started it first, now Turn on this left side and right side, that's it, this part of ours is now left side, right and right side, you are half. Now we will click on it, so you can see that first 31.78 is a single element, meaning there are first 31.78 is a single element, meaning there are first 31.78 is a single element, meaning there are seven 34 points in the statement. In Chinese small format, we will not talk about this because this is the side part, now we will check that this loop is slow, Rahul is Rahul, which point will be on the first, meaning the root of the tax return and will return on the 7th and starting here, you would have given I was shocked and made seventeen, now what was earlier was 108, first you will be able to see, in the current short format, now in three developed, it has come to 317 shots, right now it has become 317, now we can see this. The chocolate part is the point of Android, this one has been pointed and I have shot it here to 317, now this one is Raiwala and Electronics, now I will call two, that is, I will point this one and who will do it on those too, so since it is on which one. So here I had water, I have just increased it, that is, I have replaced it, and after this, I have just replaced the last cord, that is, it has become impure pollution, now what have I changed it a little and came here. For this, give us an edit yoga which will impress Shravan like this, but it will take a little time complexity for this, but what will happen if you do it like this, you will become a master, but brother, how will I get the account, that question may come in your mind. If yes, then you can see the account version problem for that, but I am also going to discuss in this, how I justified this account, that is, I have tweeted a little in it and Tata went to us, then we will definitely see how the account will come to us, which was the initial stage. At that time I was of internal and J point was pausing the old right it was and was shifting it in the pocket. I have also written here that the point will remain for the party one, I will appoint the crowd, good songs, what will I do that which condition is there? I will try to get it done as it is, i.e. suppose if such a condition is added and if the i.e. suppose if such a condition is added and if the i.e. suppose if such a condition is added and if the phone matches this condition then I will say ok, the condition ends, if the troop returns then tweet one point. Plus the account and if it does not work as per the condition then what will we do? If the work is not done then what will we do. If the work is not done plus then I have written many returned interview tips and simple tips, so you have to know what will be the condition for 4123 in this case forty-one. Great * * I was giving forty-one. Great * * I was giving forty-one. Great * * I was giving pause to Shyam ji, right, it is through a condition, no brother, a condition is passed, so what will we do now, if the condition is for, then do one thing, turn it on, first do it on the phone, make a call, it will be 2351. It has come to the left side, now move our IMG forward, where will the jail come, it will come here, the right end which came at thirteen, AB will move ahead and come to 2520, now look for 2030, we will check whether If it is crossed then the right one will start then let's see who will do from 2018 then in between we will check this condition Condition Name Hi Meaning To Empty End Norms This Meaning Fati If Name Correct Meaning * Norms This Meaning Fati If Name Correct Meaning * Norms This Meaning Fati If Name Correct Meaning * Inki If To In 232 If it is more than 234 then it is ok then it will contribute otherwise it will not ring but in this you can see 2013 is not more than this means what will happen if position is made Kantala will not happen Tata also account is equal to zero Right so what will we do with this if As soon as the condition does not work then just turn it on, ok call that it is done 3020 sampler is ok, I like it and the part is right, electrolyte is in a good part 3128, what will we do now, which is 2641 and we will take it. Here will come our eye pointer and here will come the pointer for us, meaning this point will remain here, what was happening for the lip, the IR is right near the printer, the element is prescription and the hand is right, here also the same and if you see, then the right party 's pass limit. The dot has 's pass limit. The dot has 's pass limit. The dot has come before that in the end left element meaning the pass in the lift is the courage, iPhone is tried next to it, now I want the same thing, if you can see then 2641 0, now we can see, it came before 2016, expenses on nh-31, now we We will check the condition expenses on nh-31, now we We will check the condition expenses on nh-31, now we We will check the condition for this, we can send you no, if one condition is false then nothing will be tweeted, okay, after this, if the condition is passed, then we will move ahead, okay, if you had written, I would have given Rs 33.33, after that, whoever is anti. If the condition given Rs 33.33, after that, whoever is anti. If the condition given Rs 33.33, after that, whoever is anti. If the condition is passed and there is still 30 rights then what will we do? If we do it for Twenty-20 then the do? If we do it for Twenty-20 then the do? If we do it for Twenty-20 then the condition will be used. If the condition is passed then what will we do? We will still zero the account. We will still check the account which is 41k meaning. If it has come to Twenty means it has come to the last element, then what will we do? If it has come to Fati One, now you can say brother, it is victory and 20-points, so we have tweeted for these 20-points, so we have tweeted for these 20-points, so we have tweeted for these because which one are we? If 2016 is making 30 rupees, then it will make pocket money on spending time with life. It is semi, it means if it will make money with Kunti's chutney, then it will make 30 rupees with party people also. This is confirmed, so what will we do now, this is also possible. It means which ones will be kept torn, it means we will take pure with 5130 also and keep doing this, it is simple, it means accept where it is now but it is not that it is not like this, the first must have reduced, this mantra is fine if it happens, come Atiq Ahmed Jiya 30pm Aloo chaat has come on these at 1431 so we will check the condition 251 Twitter is 10322 means ₹ 2 laks so what will happen Twitter is 10322 means ₹ 2 laks so what will happen Twitter is 10322 means ₹ 2 laks so what will happen once gone on them means account plus ok account will be warm means account chirutha 087 is done simple now we We will check it, look at it was 41st, now if we are already on anti, then we have antibodies, so what will we do, if we check, we can see that it is doing 200, then we will say ok, it is through, then you remove one from the account, class will become 10 and It will keep on increasing so let's see and what will happen after this traveler product is left, that is, what can I do, I have tested it and turned it on, I have got the part, that is, but when I will get it. Now we will work for the right. Right is the last part in the pot. We have taken the chord of 3. So now we will work for the flipped part meaning three. The eye pointer is on the team and the end points are over there and let me tell you JNI in 1953. Single element means shot is appointment, now what will we do, we will check the condition, for left and right part of train intake, for urad se, condition is false, right cannot be more than 150, then foundation, if pause condition is positive, will not do, will move ahead. By moving you forward, it has become like this 1737 10:30 It means now brother, 1737 10:30 It means now brother, 1737 10:30 It means now brother, do this point that I am the late one had become and this one point had become Raiwala, so above this one, it is above this, right eye is seventh above and This is a lot on three or now let's check for this 70337 was the greatest one to three that you are yes brother six seven is more effective then again the pound will increase more meaning first cheetah will go photo no problem we will work on it first Okay, what will happen after this point which is the seventh right, what will happen now, yes, this is already a point, that is, if it is on the last element, then what will happen or instead of OTP will come, then see, it has come on the team and is given on the teaser. It is already ready that we will make these also straight. Okay, so if you see, for 10:00 there is two, that is, see, for 10:00 there is two, that is, see, for 10:00 there is two, that is, three, two. Okay, so it is smaller than that small, that means if the condition is to have a good condition, then want will go after this. Let's see, after this you can see that we had the right in such a short format, so if we turn it on, after turning on which, you can see, then the last part is old man for developed and developed. All that work has been done, so now we will cover who will do the thing 710 We have the rider come Ultimate Right and Ultimate Ralph from Canada Now we will do this for these two elements Our now high point guest is above and a pointer was. Now we will compare the thing with thirteen, it is very simple, let's try it, now we have pointers, hence above them, the meaning is I, which is the point, above G, it means right and you can see the condition is true, if the condition is through then it is wanted. Will do it brother eats these so FD is more than Kshatriya has more votes than Kshatriya, now what will you do Chi if there is condition then give it a go ahead, the reason will come on intake, now what will we do for computing A37 Yes brother, the condition is passed, it should not be more than 3215. If the condition is passed, quantity will not do, what will we do after this, we will move forward from Foundation for All, now let's see, what will we do after being on right ten in the team, we will compare them with thirteen, meaning we will comb three* falls. three* falls. three* falls. What will happen after this? Now we will come to high school on anti and G is still at three but can share with 2003 because I have made the first love. If you are making love with thirteen only then these Meaning will also be made with , so these Meaning will also be made with , so these Meaning will also be made with , so what will we do if we keep it, what will happen now, if there is J point, then take copper, two into three, yes brother, it will be unbreakable and * only if you learn the meaning, it is yes brother, it will be unbreakable and * only if you learn the meaning, it is yes brother, it will be unbreakable and * only if you learn the meaning, it is more, then what will happen to 101 now, i20, NDA knows seven But ok, what will we do now, we will do 7.22, here what will we do now, we will do 7.22, here what will we do now, we will do 7.22, here this is Mittu, so we will take one consideration on this, ok, what will happen after this, we will come to this and we will check, thirteenth, now it is 24, 2010, but Abhijeet is for the team now. We have to check for the team also, if not fly then we will be taken back in this condition because 2 ant is never greater than 1020 then ant quantity can be bittu integrated 120 can not be less if friend part is failed then we will come here Will do it for 2016, ok brother, please check for Twenty20 and tell me, 2016 is here, it has moved forward, it means that the powder is complete, it means you have come to 31, now we will accept this, which one will we take out and this year 2016 Because if a serial is made with two entries, then China will make love with Indies also, so which one will we keep, now what will happen, we will check the financial strength for this, now have I made any mistake in this literature, it will not be a lesson, things are fine here. If it is here, it will be here. If you want, then there is such a condition that it means 2063, it must be more or it must be more than Chintu, then this pal is right after this, we will not go. Now if you can see, now we have come, so on 30. If you can see the cent, then whatever is there, you are free with it, now it is done, now it will move ahead of China, if it is 7:00, then move ahead of China, if it is 7:00, then move ahead of China, if it is 7:00, then yes, this is the condition, it is ABC, because of this, it will have more attitude than F-18. Meaning, one will be added, right, now what will have more attitude than F-18. Meaning, one will be added, right, now what will have more attitude than F-18. Meaning, one will be added, right, now what will happen is 2013, all have also come, we will check for three, if we do 320, then we can see the tan * do 320, then we can see the tan * do 320, then we can see the tan * What will happen, toe entry will be done, and yes brother, if it is more than 2620, then it means one has come on Twitter, yes brother. After this, check what will happen now, there is a lot of it, that is, like is on the pin, then we will take you forward and take it on and check, for this, we can see that 250 vehicles are grated, 1023, yes, it is true that it will return, now what is the high? I have come here, I have made some mistake, it means I have not come here, I have come on torn forest, so it will fly, now it is at such a place, it means 5172 more, if your benefit is broken then it will also break even more, now what will happen, I have come on cotton and 680 Right If you could have seen this final 10-02-2014 you could have seen this final 10-02-2014 you could have seen this final 10-02-2014 More than this, she was a mother, more than this, she will do tuition, if we tweet, what will we do, will we check the account, this is how the comment box was getting passed, right, I did just fine If you haven't done it, I will check. You can see what happened. So here I got one right, it became one, here I got it became two, now here I got it became Rupi, now here you got me for. Now it's done, here it got two, it turned white, it got it right, it got it here, it got seven, it got it here, it got it I got mine here, hence the account is done, now I got the value here, the account went here, and I got the account here, now the account is done, meaning the account will be you, the account will become difficult, 230, it will become simpler, what will we do now, we will court it and understand how to apply it. You can ride, if you limit it like this, I mean in India, then the account will not come, check it, okay, so now we will check it, what will we do by courting women C plus, if we are going to vote in both then we will do one PAN. For that, I will need Moksha Strike, so I will give such a note. Okay, I will give such a note which has more marks, so I have dipped it very well and have kept it step by Diwakar that if it exists like this, then after this. When we support, we will compare and cut it. Okay, so if you have more marks then you will remember that I have added, so basically it is very easy, but if you do it is very easy, what will we do, you can see these three here. Name is Rahul, if there is a press share, then what will we do? We will take intensity equal to norms for telling. Okay, why because we have vibration, that is, whatever we have to take, we will take that yoga, that is, the last indexing will join it. Okay, so what should we do? Indian breakup name, top ten. After this, we will call a function. Now don't think which function it is. Just remember that I did one such shot from the master and if we have to write this function, then Amit has given a note. I have given a little reference in the note. How have we done for this, what will we do after this, will we pass the norms and or mother enter in its own right shoulder, the element which is footballer, we will compass it to Range Rover limit, meaning the element which is on the index of two and in Ujjain is August element, then We will pass this number to India, which is the pizza bread, the element on it, right, so after this, we will make it a little lower, after this, we will take the function, we will give the function of WhatsApp, okay, so what will we do for this, first private in ur heart. Let's copy the start to Moksh Servant, so that we do not make any mistake, what will we do after this, it is not me, here I had done an adipose and I had done zero number in it and in this we have made the last dress, so we will do the same, what will we do first? We will decide on a name, okay Norms and after that, what will we do, we will pass it to Interested, okay, let's say Chart Index, what we will do, we will pass it to Independence, okay N, we will press it, what we will do after that, let's say if our There is a hero element in the address or there is a limit. If there is a limit then return it. Zero is fine and if you return two then do joint and if such zero percent means some element is happy then say whatever means rebel. Two, what will we do for this? Heer, we will say, if there are installed apps, this is the chart index. If it becomes like this, Greatest Hits becomes equal to Indian track, then we will say, there is one element percent in it, which is zero element. How to do it, then what will we do? Beat. Will edit from here, are busy, okay, this is due to death, now brother has done this, now what will we do, now we will become this encounter because we are just an account, I told you when I was explaining that we also need law, meaning each one. After doing this, less people will definitely return, so for this we need, then what will happen in account is equal to two, what will we do, we will make the box in the middle to zero, we will say that if there is meal, we will check first, start in Amla, ok, send the starting, then we will spread it. After that we will have class and what will we do? Start it with Indian Tech - Cut one, Start it with Indian Tech - Cut one, Start it with Indian Tech - Cut one, you can say why you have done it like this, then how can you type? Resting in this world and answers-2 big, what is there in this, a world and answers-2 big, what is there in this, a world and answers-2 big, what is there in this, a little test case failed. If this happens, what will we do? Index - Will come, it what will we do? Index - Will come, it what will we do? Index - Will come, it is the same, it means it is not like this, there is no cure, there is the same thing, if you try to explain, what will we do by doing this, Bittu, we will do it, okay, by doing this, Meera went to us, very Sanjay Bhaiya, please meet us like this. Now what to do, see, it happens like this, it means WhatsApp doesn't know what we are doing in the market, Kripa Shankar is ready, so whatever question we ask for the question, we do the account like this, we will take a controller, comedy old accounts class like this Sorry, you can send this message account classical to master we did WhatsApp right Masha and Bear so for you I am selecting this so you will know which one I will call the function you like so I tweeted WhatsApp So they came to know that we have to call the qualification, take the leg piece, I am copying it, now what will we do, pass the norms, okay, norms, and pass, started, okay, staff winds, and pass, many of them, pass it like this, so be it. We will cut the part which is on the lips side. Okay, by doing this we will mute the left side part. Now why did I tell the left side, it means the area, which means cases 12345, 876. This point means Muslim Always 125. There is such a groom, what will he do with this part on the left side, he will leave the Ishwari part, okay, what will happen after this and will he leave the oily part, so for this we will have to fold it from left and right, light okay, so our village. Please leave equal to my and reduce it, just check it completely, we will not give points from here, we will pass master's standard but in this we will pass me plus one, why because we know brother was second annual seeking for aid. It means the one on the right side which is Sagar, its starting index is meat plus one light and the ingredient which is from it is Android, so what will we do, we will call it index, we will index it and I have made India reside in it, so this is the left side end. Right side now what will we do now we will march then account please equal which march now this volume has to be muted the part of what is this which send it to the mart, we have got it I know 23456 and are responsible from Tytler and Malu speech so now we have to give it a The second one is the one in which we agreed on these, now this audition's demand ad used to be as if it was already 98364656 from Amazon, to which I asked how the sweater came, then it came like this, then what did I do, I took these two and after testing these two, I again read the anti-A So, again read the anti-A So, what do we have to do, we have to forgive this dough, okay, by shortening it will be butter, so that's why I have to write the March function, so we will write that function first, it is very simple. Now what will we do, we will pass it in starting, okay, I have passed the trading tips, now what will we do, we will talk on the meat because brother, we need what we used to do, there was a career in which what we used to do, we will take the starting index and put it on mute. Will start and again by taking these and doing this, if they were doing like this, then assume that there is some error in 12345 SEZ in which the deceased used to shift from here to here and were doing this and this with this, so what will we do, we will pass the meet. After this, we will give them the password, right, very simple, what will we do now, we will make the account medium because we will have the work, this is the function, see it is simple, very simple, private, so what will we do now, this income is like this and the fourth is like this copy. Will do the difference will know that I that you were a my suit here I will march okay because here I must have left or Android started we have to set alarm for was elected and difficult so what we will do is pass us in this If the starting index is Meet and Immediate, it will remain like this, meaning it will go as it was, there is no problem, but the extract will be added, it will go to Intimate, you need to know that we need a green chilli, even if you don't get it, you will also not get the picture. And if we don't get Viplav, we can't like what. Hmm, so that's why we need it. Okay, and the mixture is very simple. We will make the difficult things easy. Okay, after this, what will we do? We will tighten the day and send it down. That's all, now we are on this. What is the function in account? It is equal to 0, what will the function do in this, i.e. the operation in this will i.e. the operation in this will i.e. the operation in this will add the account and this one will delete the account. It is very simple, now what will we do, after this we will create a temporary agri in smart. It seems that because we are doing in-place solution, that is why doing in-place solution, that is why doing in-place solution, that is why I have kept it for you, take a look, then I will tell you, it will come in Independence, this size, rate, ego is temporary, whatever is its size, we will write it like this, that means, let's say this is how we will do it in India. - Why do you mind against doing this last one - Why do you mind against doing this last one - Why do you mind against doing this last one because if you do it like this then it was different from humans then learning will come in it meaning if there is sediment then it will be consumed - 0522 meaning if there is sediment then it will be consumed - 0522 meaning if there is sediment then it will be consumed - 0522 600 then if you have to do it in class also then 27 People of Sal will get the same treatment, it can be emphasized, in this, first we will tell that it is 13 inches, okay, after this, what will we do, after this we will take the paint index, which will be Dr. The index is 120, which India is shocked that it is saying black. Its Intex Aqua is ok, after this what we will do is that rims I is equal to start index like I have what is in it like it comes that stock index this I will start I have started that is correct no problem but it is not a matter of this What will we do after this? Rai Someshwar Dungar What should I do in this, I will make a lie because we are told that + is the right side address, because we are told that + is the right side address, because we are told that + is the right side address, its starting index is middle class one right, how to know 1578 934 shells Next, the add right side of the website is a tabloid, this meet right is on the right side Have to take that right morning starting and 198 starting which is limit 179 so it means no is meet plus one meter reader so after taking bath in Mithila in Noida then let's point to 1 Must be doing the entry point Light has become very simple Now we What will we do after this, we will run the file, now there is a little tweet in it, first we will run that file to reveal the account, then like we master, runs free Facebook, first for the lips and right side, then we cycle for the lap, so by doing this Will get then what we do is copy but will look once more in this because we need contract and clove will go file come lace that medium to minute till okay so eye lashes dormant means from late side to lips your which are small which starting index means Zero is zero meat that which India means the goods should be smaller than the feria six, okay then it will not work after this and there should be this condition, it has been mentioned that the thing which is definitely the index is smaller, okay which is Indian. Tac is shorter than that in English is here and acts of this past sample now what will we do if it happens like this then there will be loss people will start then what will we do we will check on this there was a condition on this we know that name size vintu name It is a very simple trophy, we will check it, how to do it, we will take a plate, we will do it later, first we will see it, when the condition is like this, we will copy it and turn it around. I like going to the office very much, that is, by doing this If you take the condition topic, then it is understandable. I told you very well that the attached bath is the size, it is more to * Name fixed, many here, is more to * Name fixed, many here, is more to * Name fixed, many here, I had decided in such condition, what will we do after this, there is a little free part after this, if so What happens is that you do one thing, account please equal to meet - I do class account please equal to meet - I do class account please equal to meet - I do class one, why brother, why did you do it like this, he tells you, after this, do one thing, go Plus, but now you tell me, because brother, you had such a condition. For this, why have you done this, there are many, very simple solutions and few which I have given to you, 26-8-2016 and 40 you, 26-8-2016 and 40 you, 26-8-2016 and 40 and here I have given Fifty One and Educational, so this is also called Vansh Question, which means Patti One also keeps getting it. It is 2016 for Dhakiya tank but in the old days after it was opening it na 441 means it should be done first means if this point would have come here like this then the hunter should come here after this. Okay so how can we work for this also. Will do means will reduce the team for the party people, there is a lot of scolding, there is light, so what can we do for this, we can take it on the exam, suppose we have 134, light on food and one more point, means voice has to be taken on the right side, one on 2nd floor. The other part is on the portal website, it is done on the right side, now Malu ji appoints this and I am pointing to this, OK, now assume, will one condition be satisfied, that is, the condition is correct, it is not necessary, why is it not correct, one? Better Than can never be 2121 so this one will not be there so let's go ahead and let's also appoint this one again is appointing it to come basically appoint Gati so we can say let's make three great free greater than Two into one is right the greatest and two If we have come to you - we have done it, then this point is you - we have done it, then this point is you - we have done it, then this point is returning zero, after this we have been called, then it started uploading plus one, this point will do quantity 1, this was done brother, but explain the part of second element of treatment. So let's talk about those people vehicle 12345 cannot be added on matrimonial website, meaning want to right side cannot be added like this, Batamaloo is like this and the website matters, let's now make it a hunter and do two points, what should I do with Android 24? It can be to * ne judge hai karega mait brother ko one hai kya hai nahi hai can be to * ne judge hai karega mait brother ko one hai kya hai nahi hai can be to * ne judge hai karega mait brother ko one hai kya hai nahi hai then I will say if it is not of things then it will not happen here also it will happen here meaning it will come here now then it will happen ji is still here So what will we do, is it free greater than one * what will we do, is it free greater than one * what will we do, is it free greater than one * Yes, this is that, this is the part of 1.5 inches from here, it will come here and a quarter of an inch here, 1.5 inches from here, it will come here and a quarter of an inch here, 1.5 inches from here, it will come here and a quarter of an inch here, jobs after it will come here, also four quantities or acid was to be found but When he comes here, he will come here, when he sees a party worker, he will come here, brother, he will come on two, then he and here he would do ₹ 1000 for leftover food, meaning for better than want do ₹ 1000 for leftover food, meaning for better than want do ₹ 1000 for leftover food, meaning for better than want two, meaning for return. There was 12381 control panel but this one. Didn't control the photo because G has moved ahead now in the afternoon, so how will we make it work, that is, how will we make it work for the phone, so what we did is, fry the minutes of its meal, then the flashlight, so what all did we make for minor free. Took and after that what will happen if you stop it? Meet - I mean, I was just what will happen if you stop it? Meet - I mean, I was just what will happen if you stop it? Meet - I mean, I was just pointing at three, I was calling right now, when I was calling Ai and I was crossing life, what did I do even then 4 - crossing life, what did I do even then 4 - crossing life, what did I do even then 4 - also What would happen if Wandsworth Dip came to this point and got it pointed here and this happened here, then we recorded the video, I wrote, we took it from here, meaning that if we took 20 rupees, there should be an account for this also. And by doing this, we can keep easy for the second element also, so we have written account Dr to cash plus minus plus one. If you have not understood, listen a little more allotted, people will understand, Paul Simple. Logic is light, ask, let's move ahead, now I understand that I have done it like this, account plus is equal to medium size, Chauhan has the bus, it is very easy, now what will we do, after this we will read, it is a very simple step, after this and 1 inch Will take teams, will be used, if this happens then do one thing, if it is not so then let's coupler, what I was doing was taking I forward, meaning if it is a foundation course, it will take you forward then I am the one, it is simple, after this What will we do after this, we will go and do one thing which was like this, let's copy it again we will do it like this, find Inter High School Students and thing plus one, we will do it like this, okay if it has gone out of the files, now we will take it for this. What we will do is run the file and do the same as we did here, what was here and fold it once, okay this point will shoot us, simple repeat, now we will cut it, okay we will deposit the cash if We all norms I, if it is like this, means the first indication is on the right side, if it is bigger than that or right, then what will be bigger than that, meaning Z, so if it is like this, then do this, send this, short s means like havoc. That is, give plus to its index, meaning we will replace it, we are fine, what should we do, the original is this, that is, as per its reminder, that is, the tip that is admitted in the website or in the size, we are just grinding it with this. And the point is being pressed, so for this we have received a check, it is just simple water and what will we do after that, if this happens then do one thing, do this, copy it, go to the office tomorrow, I will do this if If this happens then press India but if you do all and plus then add plus to it then this is our function which means it becomes red and this is a simple volume of one file high. If this happens then it means suppose if you pointer I am younger than Meet, so if you are connected to the internet then people offer it, so now people run it, verify that we were doing like this, we are fine, we used to do like this, we will open it and present it, meaning if this happens then come. Do the maximum if let's say it's not so if let's say if it happens so greater than e request oo in intake rate if these are lost do it after the index on the right side I'm fine same index if it happens So do one thing, which was like this, by the way, more people, police, paste it, okay, only went to the files, this is follow, now we have to do one thing, the topic is to increase the height, so we can go and do it like this. In the press, you all said that you can do it Sampat, I will tell you like this, if you want, you can use other methods too, Fold said that you can replace, I will just do it like this, okay, so our hair is as it is right and its point was 0601. After this, there was Norms Right which was the second secondary on which we have to replace, after this there was Right Start and Access Settings, where is Starting Default, which Puri has to be pressed, Home, Stock Index, and after this, what will we do, we will fill in these English and this is the instruction. If I can give it will be done, meaning study and research started, with whom he will go, he will be contacted, now what will we do, semi plant and return to the account, if the return on equity is less, then this is our less, after this, one soldier, one racket, this is done. Have a function ride, now I have to ram it and write it, let's see the problem that was coming, I have folded it, you can see, here I have shown the bulk of the started juice, here, there was a problem in a little nickel. But I did it and there was no problem, so after that I have written and seen that it is working, that is, even after submitting, I have seen that it is working, so leave this zone 7777, after that go to C+Plus. 7777, after that go to C+Plus. 7777, after that go to C+Plus. On C Plus also, I roasted the same beans, okay, you can see what is the same beans code, I just did a simple thing there, I started it, what is it after this, now you can see by roasting it too, so simple like I did, you can see. I have a to-do, this will also I did, you can see. I have a to-do, this will also I did, you can see. I have a to-do, this will also work, okay, you can see, this too has been avoided, so by doing this, you can do it directly, I do n't know how, I am the answer to Shiva Reddy Plus, so I can do it by doing this, so let's do it for today. Bye if you have any diet then you can ask in the comment section and yes if you like the video then please subscribe. Like it and go to the comment section and if you have any problem then discuss it. If you have any doubt then click on it. So let's do it for you brother, see you in the next video.
|
Reverse Pairs
|
reverse-pairs
|
Given an integer array `nums`, return _the number of **reverse pairs** in the array_.
A **reverse pair** is a pair `(i, j)` where:
* `0 <= i < j < nums.length` and
* `nums[i] > 2 * nums[j]`.
**Example 1:**
**Input:** nums = \[1,3,2,3,1\]
**Output:** 2
**Explanation:** The reverse pairs are:
(1, 4) --> nums\[1\] = 3, nums\[4\] = 1, 3 > 2 \* 1
(3, 4) --> nums\[3\] = 3, nums\[4\] = 1, 3 > 2 \* 1
**Example 2:**
**Input:** nums = \[2,4,3,5,1\]
**Output:** 3
**Explanation:** The reverse pairs are:
(1, 4) --> nums\[1\] = 4, nums\[4\] = 1, 4 > 2 \* 1
(2, 4) --> nums\[2\] = 3, nums\[4\] = 1, 3 > 2 \* 1
(3, 4) --> nums\[3\] = 5, nums\[4\] = 1, 5 > 2 \* 1
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-231 <= nums[i] <= 231 - 1`
| null |
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Hard
|
315,327
|
878 |
ass problem for today from the hot pocket and magical number so concerned magical divisible by either a or P okay and we have to determine a magical number and it has to be in the model of tennis to connect the seven so taking the example if n is 1 and we have two numbers given what is the first magical number which is chisel by hand up two or three in this case two and second example says you have to find the fourth number which is 2 pi so initial numbers which are divisible by 2 works we have 2 3 then we have before which is like - we 3 then we have before which is like - we 3 then we have before which is like - we have 6 number but first one but also by other two are things - and we have three other two are things - and we have three other two are things - and we have three sixes of four so that's what the answers in goes for the N equal to 5 you have some numbers divisible by 2 3 4 6 8 okay and there is where for work so we have some numbers and you have the perfect numbers and we have the constraints that the hand can be I mean it's a very large number a 10-4 mean it's a very large number a 10-4 mean it's a very large number a 10-4 name and the value for a and B is bring it out before we actually go and what if an A or B can be run out what will be the end magical but if this area are being given to us one of them is one new doctor would be any thanks we find how many of the elements which are less than packs how many numbers are there less than purgatory so will there be any numbers which are divisible by pot yes we need to take LCM of 23600 by six numbers how many elements will be there less than hunter which one divisible by K we know how many numbers will be consumed by a thing is it co-op it's a equal to three thing is it co-op it's a equal to three thing is it co-op it's a equal to three people to see if we have each other we are saying and same of a and B which is six right yeah how many values for this one that is 6 how can you tell me how many and use six if five left 3 minus 1 7 and why have you done this - 1 because we have you done this - 1 because we have you done this - 1 because we have to remove 1 extra 6 which comes after LCM of so we have to remove that number so we have the way how we can find the number of elements which are less than the current element and divisible by a or B right yeah now can we use that to somehow find which is the nth number so we are saying is this some value which can become either n this can become a or we have to find some value in this case we have chosen 11 we have to find some banding which will give us this value equal to what is asked it will be the minimum value of the magical number given the constraints if I must and equal tops you have to find an equal to three and they are two numbers given and he put it can you please repeat your voices breaking I am asking given the constraints of the problem this is all this last case and these constraints what can be the minimum value for the nth magical table and what can be the maximum value for n magical so we are given that it's a positive number right so without that awesome generality can visit the minimum that can be won because I am getting it yes ok and what can be the maximum magical number so we know here we can do maximum this value and can be maximum this well let's assume the signal this is these values for now what can be the maximum value in this case so if we have to find only three elements what will be the maximum that the output can it may be well written inside that but what is the probability of maximum can we assume its maximum number into the number of times because the maximum number will take it to the highest power and somewhere in between you will definitely catch up at four yeah if a and B both are fixed then also that number would be 18 third number so now this is for this problem and what else can be Amin on next based on these constraints 10 to the power 9 into 40,000 just from the problem for the problems sake and to a specific example and the way you can handle this page number in your program is only to protect modular does you have to return the answer was murderous let's ignore that for because if you do one model is in between operations you will lose this calculation the modulo number it's not always going to be a it right is never going to be diversifying number it's not going to be a factor for any of those so how many digits will be in this then get it we have ten in the Sun they have ten in this right so definitely this is going to cross by ID just like it may not fit into integer once we multiply it with this it was if we have ten lists one nine into somebody which even has all zeros it is definitely going to be at least 13 or 14 or effect until just enough time here so let's assume we have minimum value that can be there for any problem we have maximum value that it can attain and we have a way to find out this equation then find out the position of that number in the entire shape based on the equation based on the common statement now does this ring a bell these three equations we have these three data points can we use bangle researcher so bounce for the missus for then apply this farmer to find out what is the position how many numbers are next are going to ten number which others in this range right which are magical numbers so definitely and we are looking for suppose I just take an example so definitely this range is not want exponent is our range and an estate problem of this set then we are able to find a number where we get the exact numbers it doesn't make sense now yeah and if we are able to find a number suppose X plus 2 that'll also give you a magical number the length of 5 because if there's no number in which is a magical number so in that case what we will do is keep moving left to find this five and once you have reached you know element of X minus 1 giving you suppose oh because you're more passed the last element magical you I hope this is Aaron if it's fun I can take an example charge good others guys is this glass so the time complexity of your solution is not in it is log of Max Weber ya max value okay yeah this is case we can safely assume it's going to be in the maximum work that he will be tenders to part 9 this is going to produce essentially if we consider a 64-bit value 1 so it's we consider a 64-bit value 1 so it's we consider a 64-bit value 1 so it's going to be 64 sometimes 65 this part is clear confuse anyone in this one I think we are done with three problems for today the buns they were a try not the victim is there any other approach problem I think for these three problems I the apart from the odd any problem any huh approach they would like to discuss brothers magical number there may be some other approach also this was just one of the other pros that I can think of but that may be a complex time complexity is one of the numbers like to start with and then based on next to multiplication which others a smaller just continue on that like people who will be small as I go with this one so it's like happen to have these numbers like six the kind of merging two sorted arrays okay and if you see clash or same then you can just take one of them take them out two by two and then three next I see there's a same number which is already in saturdaya and there's a lot I can skip this one problem in this case is this is going to be off thank you I confess I hope there's a presence of them yes and you don't have to actually expand these numbers you can just keep a multiplication factor yeah and then keep incrementing it for I thought of this method only from the description point of view I think this is the engines approach that comes into the mind and valid solution but given that it's a hard problem and the input bombs are too high that definitely can fill the time capacity cases for people so we need to find a better solution here anything else guys you have in mind for discussion today I mean we don't have any other questions for today I can stop the recording and if you guys have any other system
|
Nth Magical Number
|
shifting-letters
|
A positive integer is _magical_ if it is divisible by either `a` or `b`.
Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1, a = 2, b = 3
**Output:** 2
**Example 2:**
**Input:** n = 4, a = 2, b = 3
**Output:** 6
**Constraints:**
* `1 <= n <= 109`
* `2 <= a, b <= 4 * 104`
| null |
Array,String
|
Medium
|
1954
|
1,685 |
Hello friends, today's problem is Sum of Absolute Differences in the Sorted Array. In this problem, we have been given a sorted array. We have to return an array of the same length in which what will each element represent, the absolute difference of that element from all the other elements and Their sum like if we take this example, we have to return an array of three sizes only, what will be each element like what will be the zero element, difference of this element from f, how much is my -1, how much is this difference of this element from f, how much is my -1, how much is this difference of this element from f, how much is my -1, how much is this -3 is 2 and What is the difference of 3 - 1, 2 and what is the -3 is 2 and What is the difference of 3 - 1, 2 and what is the -3 is 2 and What is the difference of 3 - 1, 2 and what is the difference of f - 3, difference of f - 3, difference of f - 3, what will be their absolute value, one and three, we have to take their sum, how much is the total, four, what has become of our first element, four, then what is the next thing we have to take. How much will be the absolute difference of two from the remaining two? One will be how much will be from five, how much will be two be the sum of both, three will be five. See for five, how much will be the absolute difference of five from two, what will be the absolute difference of five from three and what will be the absolute difference of five from three. If two comes then how much is the sum of both, if five comes then th element becomes our f and this is the array we have to return the absolute difference of each element from all the other elements and their sum. Now if we see this array in this if we have to zero position. If you want the result then what will be the difference of one from four, difference of one from six, difference of one from a, difference of one from 10 and the sum of all these Now we are given that our array is sorted, if I consider any element like if I consider si then I know that the elements before this will be smaller than this. The elements after this will be bigger. How can we use this fact? We can write it like this. What will be the answer for si? I know that the elements before this will be small. If I do my difference of sis with that then my positive will be 6 - 4 This then my positive will be 6 - 4 This then my positive will be 6 - 4 This will become 6 of 6 My 6 This will only be zero Same element does not matter What will happen in the bigger element 8 My 6 10 - 6 It will What will happen in the bigger element 8 My 6 10 - 6 It will What will happen in the bigger element 8 My 6 10 - 6 It will be like this if we see The portion before this is, if we look at this portion, what is happening to us in this, six times two of ours is coming, this diff has come, we have to take the sum of them, diff has come, this diff has come, we have to take the sum of them, we could have written it like this 2 * 6 we could have written it like this 2 * 6 we could have written it like this 2 * 6 basically. 6 p 6 How can we write this 2 * 6 basically. 6 p 6 How can we write this 2 * 6 basically. 6 p 6 How can we write this 2 * 6 and what would we have in minus 1 p 4 This would have become which is our current element times two minus which is the sum of our these elements 1 p 4 And what would have been this two The number of elements in our Before this and this six, what was our current element, our two elements were before, the current element was six, the sum of these elements in 2 * 6 minus, was six, the sum of these elements in 2 * 6 minus, was six, the sum of these elements in 2 * 6 minus, similarly, how can we write the portion after this, ours was this, we had to take the sum of these two. Right, if we see our -6 -6 has come two times, then we our -6 -6 has come two times, then we our -6 -6 has come two times, then we can write like this -2 ta 6, what is before that, can write like this -2 ta 6, what is before that, can write like this -2 ta 6, what is before that, our 8+ 10, this is coming 8 + 10, this is coming, our 8+ 10, this is coming 8 + 10, this is coming, our 8+ 10, this is coming 8 + 10, this is coming, what is this thing, the elements after this. The sum of the elements after this minus the number of elements coming after this, how many elements coming into which our current element. Then we just have to take the sum of these two portions of this portion and our at this position. The result will come like 12 - 5 kitna aaya 7 result will come like 12 - 5 kitna aaya 7 result will come like 12 - 5 kitna aaya 7 aaya here 18 mi 12 kitna hai 6 aaya 7 p 6 13 Our result will come at this position What have we done, for whatever element we are trying to find out the answer, we have to We know that the elements before us will be smaller than that, the elements after us will be bigger than that, so what did we do? How did we find the difference of the first element 6 -1 6 - 4 difference of the first element 6 -1 6 - 4 difference of the first element 6 -1 6 - 4 How did we find the difference of the next element 8 - 6 10 - 6 We saw that How did we find the difference of the next element 8 - 6 10 - 6 We saw that How did we find the difference of the next element 8 - 6 10 - 6 We saw that Our 6 here was coming two times, so we wrote it like this 2 * 6 minus 1 we wrote it like this 2 * 6 minus 1 we wrote it like this 2 * 6 minus 1 + 4 which was the sum of our element, this became what + 4 which was the sum of our element, this became what + 4 which was the sum of our element, this became what happened on the right side, we saw -6 happened on the right side, we saw -6 happened on the right side, we saw -6 was coming two times, we write -2. * 6 And was coming two times, we write -2. * 6 And was coming two times, we write -2. * 6 And when we looked at the remaining elements, they were even, this thing became true for each of your elements, like if we look at this 8, what will we write for it, 8-1 8 - 4 8-6, we will write this as what will we write for it, 8-1 8 - 4 8-6, we will write this as what will we write for it, 8-1 8 - 4 8-6, we will write this as before. So what will we write for later 10 - 8 This is how we will write Now here see 10 - 8 This is how we will write Now here see 10 - 8 This is how we will write Now here see how many times 8 is coming in th times 3 times in 8 minus our 1 p 4 p 6 is the sum of our previous elements and the number of elements coming in. In 8 This will become the equation on our left side. What will become of the right side? 10 - 1 * 8 Our one time What will become of the right side? 10 - 1 * 8 Our one time What will become of the right side? 10 - 1 * 8 Our one time is coming. I can write it like this 1 * 8 So many is coming. I can write it like this 1 * 8 So many is coming. I can write it like this 1 * 8 So many elements were after us in into which is our current element and here What will come of ours, whatever are the elements after this, their sum, like if we look at this, 24 - 11 their sum, like if we look at this, 24 - 11 their sum, like if we look at this, 24 - 11 how much has come, ours has come 13, how much has come here, 10 my 8 2 has come 13 p 2, how much has come ours, 15 the same thing if we take out for this four Let's see 4 -1 is going to come to y and here what see 4 -1 is going to come to y and here what see 4 -1 is going to come to y and here what aga 6 my 4 8-4 and 10 ma 4 the sum of all of these is aga 6 my 4 8-4 and 10 ma 4 the sum of all of these is aga 6 my 4 8-4 and 10 ma 4 the sum of all of these is what is coming to us here 1 in 4-1 what is coming to us here 1 in 4-1 what is coming to us here 1 in 4-1 jit is the first element into the current element into minus Our sum of all these elements and if we look at the right, what is ours - and if we look at the right, what is ours - and if we look at the right, what is ours - minus 3 tom 4 min 3 tom 4 and what is there before 6 p 8 p If the sum of our these elements tell us the sum of the elements before this. Tell us how many come and tell the sum of the elements after it and tell us how many elements are coming. So we can use these two equations to find out our answer for this element. Now how do we find out how many come before us? Elements are coming later, see how many elements are coming and how much of them are coming. If our total is A elements, let us assume that our index starts from zero. 0 2 3 4 Now assume that if we are at this position, our index is two. We are putting a loop and trying to find out the answer for this, so our index is currently two, we are at this position, we know that before us there will be only t elements, whatever our index number is, there will be that many elements. Why because our index is starting from zero. If we are on IA index then we will have I elements before us. We know the earlier elements. How will we know the subsequent elements? We know that the total is our A elements before us. Aa elements is one element so if we subtract i and one from n then our next elements will come like total I had five elements out of five i was on second index 2 and -1 for its own aa was on second index 2 and -1 for its own aa was on second index 2 and -1 for its own aa What were the elements before this element of mine and one element was itself, how many subsequent elements will there be in the total minus the previous elements in minus this current element, how many elements have come after this, so if I know the previous elements, then I can know the next elements. I can also find out the count of the 1st element, so my counting problem is solved. Now all that remains is, do I have to find the sum of the Alices before this one? I have to find the sum of the Alices after this one. What can we do for that if we use this array? Make a prefix sum. What will be our prefix sum? For this, one will come. For this, 1 will be 4, 5 will be 1, 4 will be 6, how much will 11 will be, plus 8 will be how much will 19 will be, 10 will be 29. If we maintain a fixed sum array Do this, what will we know from this that what is the sum of the elements from our starting to the current index Y? With its help we can find the sum of the elements before it and the elements after it. How do we know that the sum till here The sum of the elements from our starting till here is 11 and we want the sum of the elements before that, so what we have to do is to subtract whatever our current element is considered, like what was the sum of our till here, it was 11. We are getting to know from this that if I subtract six from this, the sum of the elements before it will be obtained. Similarly, the elements after this, how will I get the sum of so many portions, I know where is their sum from the beginning till the end, in my prefix array. How much is there at the last index of 29? If I subtract the sum till this point, if I subtract 11 from 29, how much will I be left with? 18 will be left, which is 8 x 10. What will be the sum of the elements after this, if my total sum is this much in this. If I subtract the sum from this till then, how much will be left which is the sum of the elements which are the elements after this, then if we maintain the prefix sum then we can easily find out the sum of the elements also, so in this we will do this first. We will maintain the prefix 15 5 11 19 29 After that what we have to do is to loop over each element. Our indexes will start from zero. 0 1 2 3 4 First we will try to find out the answer for the row. We will start from zero. What will we know, there is no element before this, we have zero elements before this and our sum will be nothing from the left side, how many elements will we have on the right side. Total - i -1 5 how many elements will we have on the right side. Total - i -1 5 how many elements will we have on the right side. Total - i -1 5 - 0 - 1 i.e. there are four elements and How will we know - 0 - 1 i.e. there are four elements and How will we know - 0 - 1 i.e. there are four elements and How will we know what is the sum of the elements after this 29 -1 28 This will tell us 29 -1 28 This will tell us what was our equation from our four elements, which is the sum of the elements after this minus the number of elements coming to us and which is our current value. 4 * 1 If we subtract 4 from 28, current value. 4 * 1 If we subtract 4 from 28, current value. 4 * 1 If we subtract 4 from 28, we will get 24. Similarly, if we have to calculate for fur, now what is our i, is one, then how many elements are there before it? What will we do if one element is 1 * 4 minus the one before it? There is a do if one element is 1 * 4 minus the one before it? There is a do if one element is 1 * 4 minus the one before it? There is a forest of elements, so how much has come from here, 1 * 4 -1 3, from here, 1 * 4 -1 3, from here, 1 * 4 -1 3, how many elements will be there after this, we have 5 -1 -1 how many elements will be there after this, we have 5 -1 -1 how many elements will be there after this, we have 5 -1 -1 elements, so what we have to do is minus 4 * 3 and the elements after this. 4 * 3 and the elements after this. 4 * 3 and the elements after this. How will we get the sum 29 - 5 How much has we How will we get the sum 29 - 5 How much has we How will we get the sum 29 - 5 How much has we got 24 And what is ours 24 - 12 And got 24 And what is ours 24 - 12 And got 24 And what is ours 24 - 12 And from here 3 12 P 3 Our 15 This is the answer We can find out for each element What will we do First of all, we will create our prefix array, so what we have to do is that initially there will be zero element at our zero position, after that we will loop from one to A and what we will do in it is that our first prefix was sum plus our current number, prefix sum. Of a my plus names of aa became our prefix array. After that what we had to do was to put a form on our array and find out our answer. We had to find out the answer for each element. For that what we had on our left side. How many elements are there in, how many will there be, whatever will be our index, how many elements will there be on the right side, how many will there be, total, our n min aa - 1, how many elements will there be, how many will there be, total, our n min aa - 1, how many elements will there be, how many will there be, total, our n min aa - 1, how many elements will there be, one thing, what did we want on the left, we wanted even, which is our current prefix sum, even prefix. There is a sum, if we subtract the current number from it, then the sum of our left element will come. Similarly, what will be our right sum, which is our total, where will we get the prefix time? At the last index of the ray, then our total time is minus which is our till now. If we take the difference of these two in the time till then we will get the sum of the subsequent elements, after that what we needed was that what is the difference from our left element, what is the difference from the right element, from whom was we getting the left count into. Number of i Number of elements on the left in i Our current element in minus Sum of elements on the left Similarly, what will happen in the case of right, the bigger elements will be on the right, the sum will come first then how many elements are there on the right in minus Our current number Sum of these two We will take this answer for that index, we will find out for each index and in the last we will round our answer, what will be our tree from this, here we have put an A size loop, here also we have made an A size loop. Put a loop and inside them some constant operation that what will be the time collection, what will be our space complex, we are running by maintaining a prefix array for which what will be our space, why do we have to maintain this prefix array because we need the sum of the left side. And then Copley, we need the sum on the right side, so we know that we will start our loop from zero starting till the end. Instead of maintaining this prefix arm, if we keep calculating it at run time, like when we calculate zero, then it Add it when it comes to one, add it at the end. Instead of maintaining the entire array, if we maintain a variable that what we need is the sum of the elements till now and if we want the sum of the elements. If we find the element sum then we can easily subtract it from the total sum, then simply what we will do is that instead of maintaining the entire array, we will maintain a single variable so that our space complex comes from T of A to OFV. What we were doing in the approach here was that we were creating a complete prefix array. Instead of this, what we will do is that first we will find the total sum of the array, what is the sum of all our elements, after that instead of maintaining the entire prefix, we will only We will run by maintaining a variable. In the beginning, our prefix will be row. Then we will make a loop from 0 to n. What will we do in the loop? Now our zero index, this element has been included. What will become of our prefix sum? If we add this element, then this is our Prefix becomes even, then again the rest will remain the same, what will be our left count, what will be our i, what will be our right count, n - i - what will be our right count, n - i - what will be our right count, n - i - 1, this will be how much will be the left sum, we know what is the sum of our elements from the beginning till now, our prefix. The sum is in this variable. From this we will simply subtract the current element, then the sum of our left element will come. What will come from our total sum minus the sum till now, the total sum which we have already calculated from that. If we do this If we subtract the prefix sum, we will get the sum of our right element. We have the count of the left element. We have the count of the right element. The left sum has arrived. The right sum has arrived. All we have to do is, we have to use our formula. How many elements are there on the left? This is our What will we get in the left sub in the current element minus required how much difference will we get from the left required how much will we get in the right sum minus the right count how many elements are there in the right in our current element This is the difference of our right elements of both We will take the sum, this is our answer for that index and we will find it out for each index and return it in the last. What we changed from our last approach is that instead of maintaining the entire prefix array, we first total the total. We have found out the sum and then maintained a single variable. With the help of this single variable, we can easily find out every element of our left sum and right sum. What will happen to us with this? Our space complexity will be reduced by fun. What will remain of us? There is an A size loop here and there is an A size loop on Y too, our tale also will remain of A and our space will be reduced, what will it become? Thank you guys.
|
Sum of Absolute Differences in a Sorted Array
|
stone-game-v
|
You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104`
|
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Hard
|
909,1240,1522,1617,1788,1808,2002,2156
|
474 |
hey everyone nintendo said hope you are doing good so let's start with the question so the question is one and zeros okay so what is given to us we have given an array of binary strings str's and we have also given two integer m and n so what we have to do we have to return the size of the largest subset of str such that there are at most m zeros and n ones in the subset okay so we are given a string str uh this is a binary array okay and we are given a m n so m will represent zeros and n will represent one so we need to find out the subset of this given string like which is the largest subset which will like all the string in that subset will have like at most m and ends so that will not cross m n okay and set x is a subset of set y if all the element of x are also element of y okay so let's understand with an example okay let's see so we have given our m okay so we have given a m and n so we have m equal to 5 n and n equal to 3 okay and we have given this string so we need to find out that subset which will have the so we have to find our subset uh which will have your like at most m and n and m will represent zeros and one n will represent one so if i give you the like tell you the output for this so for this the output is your 1 0 then this 0 1 then this one and then this 0. so if you count a 1 in this so this is 1 then this is 2 then this is 3 so which is less than or equal to your n similarly if you see the 0 so this is 1 0 this is 2nd 3rd 4th and 5th and 0th is also less than equal to 5. so subset is basically like you it's the difference between subset and subsequence or your substring is like in substring or in subset we have to maintain the ordering but in subset we can take any element in between either we can skip from between so as you can see we are not considering this let's say we'll consider this only so let's say we take this in an example so we have one zero one okay now we have take four one inside this so then we can only take one so let's say we take this so this is also the valid output but like your zeros is also less than three less than equal to three but you can see the length for this is true but for this if you take the largest output we have n equal to four okay so if you can think this it's just a question like a knapsack so we just have to either accept it or reject it okay so we initial we have m equal to five and n equal to three so we have two option either we will accept it or either we will reject it okay so what is given to us so we have given uh 10 to us so first we will start from here so we have this 10 okay so if we accept this that means our your m will reduce by 1 so m will become 4 and your n will become 2 similarly here your m will become m if you rejected you don't take the limit so m will remain same as it is and n is also same ok so after this we have again the second string so we'll start from here so we have this option zero one and here we also have same option zero one okay so we again have two option either we will whenever we accept it we do plus one okay so that we will count uh basically which string we have taken or we have rejected okay so if we take it with two plus one otherwise we will not do any will not do anything so if we take it our m will reduce by three so m will now become 1 and n will become 1 okay and if you don't take it m will remain as it is and your n equal to 2 okay now here we again have two option either we will take it or not take it so if we take this we have uh your m will become two and your n will become one similarly if you don't take it this will remain is edge at m five and three okay now again we have option so again the next string is this so this is triple one zero one okay and this is also triple one zero one and this is also triple 1 0 1 oh okay similar triple 1 0 1 so we are at here okay so if we take this we again have two option if we take this r m will become one two three four so that will become minus three because we have taken oh sorry zero so it will become minus one because it is two and this n will become your one minus 4 which is minus 3 okay now you can see this is in negative so that means we are going something wrong so we will not take we will not go further similarly we if let's say we will not take this so our m will become one and n also one okay so here we also have two option so like we just have to solve this problem except or reject okay let's solve this completely so let's say we'll accept it so we'll do plus one okay m equal to one so we are at here so we have two option for so this is our one okay so either we will take it so if we take it m will remain 1 and n will become 0 and in this case m equal to 1 and n equal to 1 okay now we have option of we'll move further we have 0 either we will take it so let's say we'll take this so m will become zero and n equal to zero and we do plus one okay so whenever your m equal to or n equal to zero we just return from here okay so if you just return it so you can see this is plus one it will come here plus two then it will return here this is not this is zero only so this is only plus two till here now here we return so this will become plus one this will plus three and from here we'll return its plus one okay so you can see we are getting the maximum output from this so we just have to do every time maximum of either we will accept it or reject it so with just a simple zero one map saying either we will take it or either we will just skip it so let's write the code for this it's just a simple implementation of zero with knapsack so what we need a recursion function so let's just create a new function return solve and we'll pass this strings we'll pass m will pass and then we'll start from zero basically we will say like you have to start from here then you have to move for then you have to move further okay so what we need to write in recursion int solve string str and m and n and your int index okay then what we need to do we have two option okay before two option we need to count the zeroth and one inside this so let's just count the zeroth first zero equal to count 0 and will pass the current element okay and we can calculate the 1 from it so we just do 0 basically reduce 0 from the given string so str index dot length minus zero so we got the one remaining one okay now what we need to do uh we have two option either we will accept it or either will reject or let's just skip okay so what we need to return in the answer we just need to do math dot max so whatever give me maximum i will take it so whatever like after skipping i get the maximum i will take that answer accept or skip okay so what we need to do we just need to check in the accept case if our m basically that is 0 should be greater equal to 0 and our n should be greater equal to 1 then and only we can accept if let's say the remaining m and n are smaller so we like it will become negative we don't have to call the recursion for that so we just do it except equal to we call the recursion function solve will pass the string array and we'll pass the remaining 0s now m minus 0 and we'll do n minus 1 and we'll do index plus 1 okay and we'll do plus one because we have accepted otherwise we just do skip equal to solve string we pass same m with space same end and we just do index plus one okay so whatever the maximum just return that okay now we need to add the base case so base case is f here so if your index reaches to the end of the string array or your m plus n becomes 0 then at that point you just need to do return 0 from here you don't need to do anything uh i think yeah we have to write a count z function so this is just a simple counting a zero from a string so string s and 0 equal to 0 for care to care array and we just check if rc is 0 then increment zero and just return the zero okay i think we have covered all the cases let's run it okay let's see so this is accepted let's submit it okay it is taking time oh so we got the tle okay let's see the constraints 600 okay so as you can see this constraint are not bigger but for smaller constraints it's working fine but when our m and n is increasing it is giving a tle and why it is giving it because we can see the recursion tree we are solving the same problem again and again okay so there might be a situation like when you solve for m equal to four and equal to 2 there might be from reject you got the same problem again so what we can do is we will use the property of dp so basically memorization the same answer okay so what we will do we can see like what are the values that are changing okay so if you can see the recursion called m is changing your n is changing and your index is changing so three things are changing okay so if we store that these three parameters and they result in a variable and whenever the same parameters come again and if we store if we see like that is stored already we can get from the uh like we don't need to call again the equation and solve that part so what we will do we create our dp and this dp we will be three dimensional so because three things are changing so dp and dp equal to new int and we'll give m basically we'll do m plus 1 because in the array it will be 0th indexing so n plus 1 and we need to pass trace.length this we and we need to pass trace.length this we and we need to pass trace.length this we can pass same as it is because indexing here it start from zero okay so what we need to check if your dp of m comma n and your index is greater than 0 then you don't have to solve it you just written dp of m n and index and in the last whatever the answer you are getting you need to store it so dp of m your n and int equal to this okay let's i think yeah looks good to me let's run it okay there is one mistake oh so we missed the semicolon let's run it okay this is accepted let's submit it yeah so our code is submitted we can see we are again taking a extra memory like we can also optimize it uh like how can we optimize it if you can see what we are doing it uh we are every time counting zero like we are counting the same if i show you in the recursion this zero zeroth one if we count at only once then why we have to count it again for this frequency similarly we are counting this triple one zero one four possible outcomes one two three four so if my tree is nested you can see the call for the same string uh come again and again so we can basically remove this from here so instead of passing this string array we will pass the frequency array so we'll pass we'll create a count array and this value of the same length of htrs.length and this will have htrs.length and this will have htrs.length and this will have two basically your zeros will represent how many zeros it is have and one will represent how many one it is so we just do for end and first string as two str's we just copy or cut this from here we don't need it now which what we will do we will just pass the s inside this count s and we'll calculate the one from here okay so let me just take a ith variable and i equal to 0 so what we do is just do i of 0 equal to 0 and count of i of 1 equal to 1 and we just do i plus okay and in this we will pass the this counter instead of this string so let me just change it like it's up to you if you have to optimize you can submit your question till here also but i think it's better if you optimize it so now we just do count of index of zero so this will represent zero and similarly count of index one and similarly we have to reduce here also count of index zero and it will be count of index of one and we need to pass the account instead of sds okay yeah looks good to me let's run it okay oh sorry it will be count dot length now run it so this is accepted let's submit it so you can see like the memory difference between this and your code is also becoming faster so if i just open both of them so this is the previous one uh it's taking time yeah and let me just open this also okay so for the previous one if you can see this is taking 230.6 mb and runtime see this is taking 230.6 mb and runtime see this is taking 230.6 mb and runtime is also 641 millisecond and it's 9.7 only increasing but if you and it's 9.7 only increasing but if you and it's 9.7 only increasing but if you can see it is taking only 88.1 and your runtime it is taking only 88.1 and your runtime it is taking only 88.1 and your runtime is also reduced from this so yeah you can optimize this yeah hope you like it thank you for watching video and do join the telegram if you're in doubt any concern thank you
|
Ones and Zeroes
|
ones-and-zeroes
|
You are given an array of binary strings `strs` and two integers `m` and `n`.
Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_.
A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`.
**Example 1:**
**Input:** strs = \[ "10 ", "0001 ", "111001 ", "1 ", "0 "\], m = 5, n = 3
**Output:** 4
**Explanation:** The largest subset with at most 5 0's and 3 1's is { "10 ", "0001 ", "1 ", "0 "}, so the answer is 4.
Other valid but smaller subsets include { "0001 ", "1 "} and { "10 ", "1 ", "0 "}.
{ "111001 "} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
**Example 2:**
**Input:** strs = \[ "10 ", "0 ", "1 "\], m = 1, n = 1
**Output:** 2
**Explanation:** The largest subset is { "0 ", "1 "}, so the answer is 2.
**Constraints:**
* `1 <= strs.length <= 600`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists only of digits `'0'` and `'1'`.
* `1 <= m, n <= 100`
| null |
Array,String,Dynamic Programming
|
Medium
|
510,600,2261
|
451 |
Hi gas welcome back tu my channel so today our problem is short characters by frequency so in this problem statement what have we given here we have got a sting s and we have to sort this sting in descending order based on The frequency of the characters. Okay, so here your answer can be multiple, so if you turn even one of these, it will be submitted. Okay, so what is this problem, let us understand it through the example, then we will see how. If you can solve this, then this is your first example, it is a tree, so what is the frequency of T in it, what is the frequency of R, then what we have to do is to sort it on the basis of frequency in decreasing order, which has the highest frequency? If yes, then your A will be first, what is its frequency, then you will be the times, then you can see it anywhere, it is okay in any order, this can also be the answer, so if you donate any of the two, then this It will be submitted. Okay, so see the example. What is given in it? C A. So here what is the frequency of C? What is the only frequency? Three. Okay so here the frequency of both is 3. So here CCC A B is the answer. The answer can be A C B. You can do any of the two and it will be submitted. Okay, now come to the third example. What have I given you in the third example? A B. Now read this and it is in lower case. If yes, then we have to treat these two separately, then how will you know this when you see the example here, I have given you that this is uppercase and this is lowercase, we have to treat it exactly like different characters. If it is different then its frequency will be one and its frequency here, I have taken three here, two here, it will not work, both here, take two here, van here, take three, so the highest among these. Whose frequency is that of B, so we will keep B first, after that it is the difference between these two, whether you keep this first or now keep this first, then we can do both. Okay, so now here we have this problem. How can you solve it? Look, what you have to do is to store it, you have to see the character as well as the tractor and here we have to see the frequency also, you have to see the right character and also its frequency, so at this time you With which data structure can we do it must have come to your mind that we can map it, so what will we do in the map, we will get to know from you what is the frequency of which character here, so what will we do? If you do towers through each element, then first you will get your team here, then you will get R, then the frequency of R is here, then I will get only one frequency, there is van here, then this I will get its frequency, you are right, so you have got it. Now what we have to do is on the basis of the second element, we have to arrange it, so what we will do is store it in the vector first so that we can shorten it, on the basis of the second element. Okay, so what will we do, we will take the vector of feet. Vector of par will be first, your number will be your integer, so what we will do here will be constant, then the frequency of R will be van, the value of A will be frequency tu. Now what will we do, we will do sort function on that, which will do on the basis of your second element. If it sorts, what will it do? If it shortens, it can be either of you. First, this is done, okay, now what will we do, we have done it here, now we take an answer sting, now what will we do here with this element. We will see what is this vector, this is the first element, so this is the first value in the first element and this is the second value, okay, so the first value, what we have to do is to append here for how many times, the second value is of foot. Till these times, what do we have to do, attend here, we have done it, now we will come here, this is R, your first value is square and this is the second value, so what do we have to do, first value is this second value. Till the time, if you have to end here, then here is van, then it will be eight, from here also, you have to append t, for how much time, van, till the time, if you have to end here, then this will be your answer. What will you do finally, will you return the answer? Okay, here we can do it with the help of vector and one, you can also do it with maximum priority, like what did you do here you created it, then now the value of the map. What will you do? Why will there be maximum priority? So why will there be maximum priority? So here you have to keep the character in mind and also keep this in mind. So the shortening of maximum priority is based on the first element, so we have to see it. No Merrily Sorting, so what will we do, first element will be put in integer in this and second element will be put in this, what will we do if your character is ok then here what will be yours then this will happen then R will come then it also has a van then R will be there then what will happen here And this will go here, okay now what should we do, we will take the answer from it, the same process has to be done here also, the first element will come out, then the one which is first and the one which is second, what is the second value, what to do as many as the first. The frequency is till the time, how much time is it, we will take that much time, what will we do here, for how long will we do one or two times, then we will take it out, then this is van and t is t, we will suspend it till van time, then this Bob will come out and will make it an art, so this is yours, if you say, then your time complexity is also there and people are also there, it has to be okay because we will do the sorting in this and why is your priority in this, so in this also those people and that are there, okay then. Let me show you both the codes, look, this is your vector, what will we do, we will see each element of the string, after that we will prepare the map, this frequency will be ready for you, okay, after that what will you do, the first character will be in the foot, after that Will be integers. Okay, now what will we do, we will insert an element in the vector. I am yours, I will be your value. So in short, we have done a comparative function on it, what will it actually do, it will sort on the basis of second element and that too in descending order, so give a second greater here, it is 20 seconds, what will it do for you in descending order? If you do this in the opposite, then what will happen to you, what is yours in descending order, then it will give you the vector by shortening it, then what will you do in the answer, what you have to do again is to make a string, then you will see each element of the vector, ok then If you get a vector like And what will happen is that your The first one is from, we will do the process here also, we will take the map, we will store it in the map, then we will take the priority, the leg that I will take for priority, first it will be an integer, then it will be your character, then what will we do, I will insert the priority and sort it here. There will be no need to do this because your right is of maximum priority, it does this on the basis of the first element, so we have taken one later, that is, the frequency has been placed first, in this, party key is OK, what do we have to do with the process, string is here. I have taken it from the name, I have solved it long ago, so let me explain to Suji, this was also prepared okay, here also you will prepare it in the same way, then what will you do with the sleeve, will you return it, okay so I hope you understood. If you liked the video then please like, share and subscribe. Thank you.
|
Sort Characters By Frequency
|
sort-characters-by-frequency
|
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string.
Return _the sorted string_. If there are multiple answers, return _any of them_.
**Example 1:**
**Input:** s = "tree "
**Output:** "eert "
**Explanation:** 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer.
**Example 2:**
**Input:** s = "cccaaa "
**Output:** "aaaccc "
**Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers.
Note that "cacaca " is incorrect, as the same characters must be together.
**Example 3:**
**Input:** s = "Aabb "
**Output:** "bbAa "
**Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect.
Note that 'A' and 'a' are treated as two different characters.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s` consists of uppercase and lowercase English letters and digits.
| null |
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
|
Medium
|
347,387,1741
|
1,530 |
prediction from weekly contest 199 from read code so let's start the first question is very simple it states that you are given a string s and an integer array indices of the same length so as you can see you are given a string and some corresponding indices okay so let's assume that four corresponding to c five first point into o six of corresponding to d and so on and now you have to what you have to do here is you have to sort or you have to arrange all these indices according to its correct order and then the correct word will form or a new word will form according to this from this word when you will sort this indices a new word will form and you have to output that new word so that's the simple question i'll take on to the code part now so what you can easily do here is you can make pair of all the characters and corresponding indices then sort them this is and then print the new word so that's what i have done uh take the vector of pair of integer and character okay and then what you'll do you will push at every position on the vector the indices which is stored in this vector and the ith character from the string then sort the whole vector and then the final answer is just you can also like because you have to return it out make a new string and iterate over the whole vector and then because the character is stored in the second place so ai dot second convert it to character and add append it to answer and then return so that's the first question which is very simple the second question can we do in two approaches we'll like take the look on both the approaches the question statement states that you are given n bulbs arrange from zero till n minus one okay so if the ith bulb is on it is corresponding to one and if the ith bulb is off it corresponds to zero then what you can do the following operation in which you can choose any indexes and then all the bulbs starting from that and this is till the last indexes will flip this current uh current state so as you can see then this is the target state you want to reach so how many minimum number of operations of flip you have to do to reach the target string i'll tell you more with this example as you can see because the initial string is all zeros everything is off in the start okay so everything is off which is denoted by this configuration then what you can do you can choose the third bulk if you choose the third ball from the last then because all the bulbs starting from this will flip till the last so it will become like this now what you'll do if you choose a full first bulb now then it will make both of them on but these will get off and then what you can again do you can again choose the second bulb if you choose the second bulb then this will get off and this will get on so that is if you see how we are doing you can actually do this in the logic part also so i'll tell you how so let's assume that uh i'll take this example only okay so what you can see here is because everything initialized with zero in the start one two three four five okay iterate over this state of the bulk because you have seen once find out the continuous stretch of ones okay now because all of them are one you can just correspondingly do one operation and convert all of them to one okay because it is starting from last you can also mark a j variable which tells us from where does this we are finding actually sub arrays of continuous sub arrays of ones okay now j denotes the ending point of this country sub area and i denotes the starting whenever you find a continuous sub area of one and j is the last point then because you can flip all these character in one operation you can correspondingly flip all this character and it will become like this okay now because there is zero you cannot do anything just make your j point to this now the next correspondingly starting position of one and because there is no more character you have to flip this now to make this if there are some more stretch like this one zero one so as you can see if this is i and this is j this is the next continuous stretch of once what you can do here is if you because you want to make this as a hole once so what you can do you can first make this whole one because everything is zero then this will become one and this will change its flip this part will get flipped so you can again do a flip on this part except this three part which you have to change and then it will come to the new the target state we want to use because as you can see this is changed if we change this whole because let's assume that it is 1 0 and 1 oh sorry 0 because you have changed this now if you take this whole it will become like 1 0 but we have actually make this one but we don't want this from this state has disturbed so what you can do if uh we will just flip this part it will become like 1 0 1 and it will reach the final point it's our target so that's the first you can find continuous stretches of once and j denotes the last point i denotes the first point and whenever you find a contrast stretch you can flip if rj is the last point you can do it in one step but if j is not the last point you have to do two in two steps okay and that's the whole trick you can this is like somewhat a larger code i have written down this code also okay and which this is a total target j is denoted by minus one because we do not know what's the last point of one it might happen that there is some zero and then there is like one so what we will do we will iterate from the last indexes to the first index and if what we find that the target value or the target value is one and j is minus one j is the last index is minus one because it means that we haven't find out the last index or the starting of the continuous sub area then we make rj equal to i this is the last index of the continuous sub area as if we find that the target is zero because when we know how we know that this is the control stretch one we will only know that when we reach a zero point because we see that one and then a zero which means that this continuous sub array has finished continuous sub array of like once has finished and then we have found a zero so this is the ending point on the starting one this is the ending point okay so if the target value is 0 and j is not equal to minus 1 in which means that we haven't find our last index then this is the j then what we can do here is j is not equal to minus 1 which means that we have found out our last index and we have found out our starting index only so we will check that if j is last index the last index is then the total will increase by one only s total will increase by minus like two and we will again make r j equal to minus okay and we'll do the same for if we just find out j target value equal to 0 and we haven't found this one okay but let's assume that there are all ones and will come out of we will check that okay we will make rj point to the last value and then i will go out of this iteration and we haven't found a starting value so what we'll do we will also check that in the end if we go out of the value and we haven't done anything we'll also check that whether there is some eye left which is this so you can do it in one flip only okay so this is somewhat a little bit uh logical but the code is blending in which if j is equal to minus 1 then if it is index total plus which we have done the same else equal to and the answer is 2 that's the whole trick you are just finding out the continuous sub arrays of size 1 or continuous sub arrays which are only having once okay the next logic can also be because if we just found out that the state is like 0 1 now if the consecutive elements are not same if the two elements which are not same then we have to do a flip to reach the state why because let's assume that there are zero okay now if we want to make because these two elements are not same we have to at least do one step to make this reach this state so we can do one step then because there is again not change not same then we have to do again one step to reach this state okay so what this means here is for every change for every bit which has changed and also we have to add append a zero in the start for this logic we have to append a zero in the start because we are missing actually one more flip okay because let's assume that there are all ones and then a zero we will check every consecutive element this has this is same and if there is no zero will come out of this uh for loop and there is no change but because everything is one we have to do at least one flip we have to do one flip to make it all zeros because there is all zeros we will do one flip to make it all once and thus what we can do for doing this we can append a zero in the start of the string and whenever we will check the consecutive element if there is a change if the consecutive elements are not same we will append our answer or we will increment the answer so that's the second logic i written down here it's a very shorter logic in which we will append in the target in this target string in the append in the start a 0 again and then what we'll do total is the total number of steps we will start from back to the front if the is element and the previous element i minus one element are not same then incremental and just return to two that's also simple code okay you can also come up with both the ideas okay now move on to the third code the third part the third question states that given the root of a binary tree okay and an integer distance now what you can do here is a pair of two different leaves of binary tree is said to be good if the length of the shortest part between any of them is less than or equal to distance so what this means actually here is so let's assume that the distance between any two leaves you have to find out the dish distance between the leaves two different leaves so what is the difference between three and four one two three so what this means actually here is you are given a wine entry and you are given a distance you have to find out how many leaves distant leaves are having a distance three or less than three i hope you understand so as you can see in this uh tree this is a binary and we have to find out the different leaves which has a distance of three or less than three because these are the four leaves this is this can be a distance this can be distance and so on and thus as you can see if these are just distances because this is one two three four this is between four and six is four but we can only find our distance between which is less than or equal to three and thus there are only two uh pair which is four five and six seven which are having distance equal to two at those answers so we have to find out these so let's move on to the drawing board to make it more clear this question comes to me when i see that the constraints are very small the constraints are small enough and also what you can observe here is you are just looking for the children because okay let's assume that these are the two leaves now if you want to find a distance between these two leaves we have to find out this period because as you can see okay distance between this and this is this so it will always find if you know the parent of this of any the leaves you want to find out then it is just the distance between this parent the height of this from this parent and this from this point this is the addition and this is the whole trick so if you know for every parent what are the distance of its left child and what are the distance of its right side what i mean by it is for every node if we know what are the leaves it has on the left side and how many leaves are having it had on the right side and what are the distances of those leaves we can easily find out because let's say that for this node we know that for the right or for the left side it has two leaves which has the distances two and again two but on the right side it has one more it has one leaf which has distance equal to one so what you can easily do here is you can just iterate over for every node you can find out because we have these leaves what are the possible number of pairs good pair we can form a good if the distance is three we can take a pair of two and one and the total number of good pairs are two okay so it right over just find out the left leave distances right these distances of every node and then what you can do you can check that for every pair because for every node we can make we can add these distance with resistance and if this distance is like less than or equal to d you can form a good pair so what you can do you can recursively uh iterate over the whole tree for the children for or for the leaves what you can see because it is the uh because for the uh children there is no way you can because there is no left or right tray this is the leaves so what you can do for the children you can just push the distance which is one okay because this is the distance now for two now when we come to two the distance will check that better it has left side whether it has right side yes what you will do you will take the distance of its left child and right side hit it over them we will make up here that add every child every values in this vector to the other vector so one plus one equal to two which is less than three so this will form a good pair okay you add this there are there more here we can form no we cannot perform more so what we will do we will take these values and send them to its parent because these distance will send to the parent because this parent will send or help the upper parent of this node to find out the distances of its leaf node because for this node how we can find out how many leaf node it has and what is the distance so what we will do for every node what we will do we will send a vector and the vector will store all the leaf values because the leaf value is this we will iterate over all the leaf values and add one to it because we are moving one level ahead the distance will increase by one because for this node now that the leave distance is equal to two and we have stored the leap distance equal to one so what we'll do when we move one level ahead in the recursive recursion what we will do we will take all the leaf nodes which are stored for which we have for the left child and the right side add one to it now it will become two and you will send this vector to this node now this node will store that i have seen two leaves of length two and this will send that i have seen one leaf of length one okay so as you can see two and one and thus for this node now it will check how many leaf nodes are there on that slide left child which is two and two how many distance leave are they on the right side which is one make pairs this and this can form here and this and what you can do here is find the total number of pairs which will be less than or equal to distance and add it to the total that's the whole logic i'll take under the code part now the code is you can make answer to be a global variable and then this is the okay this is the count pair function we will make the distance also global which is a distance between the two nodes and then run a dfs on the roots on the root node and then return the answer and dfs function will return a vector we will send the root as the starting value we will make a new vector of a vector of integers which will store the distances of which will show the heights of every leaf node from the particular root node we are given if the root is null then we will just return the empty vector okay else what we'll do we'll recursively call this same dfs function on the left child or on the right side then what we'll check that if the left child and the right child both are sending a vector which is empty because as you can see if we call for the leaf node the dfs on the leaf node because there is no node here and no node here this is null and for the null we have seen that we will return the empty vector and we will return an empty vector here and because there are empty vectors on both of the side it denotes that this is a leave and what we'll do if this is a leaf we will push back as we have told you because it is a leaf will push back the distance of this leaf node with respect to itself which is 1 and then we will return this new vector because for the leaf node there is no left and right side we cannot find out more pairs with respect to this node so we will just add the distance of this leaf node which is one and return this vector then what we will do is for if this is not a leaf node it is some random node in this whole tree then what we will do we will find out it's left all the total vectors or distances or height for the left child and for the right side make a o of n square loop and for every left and right value we'll check that whether the value is less than equal to d increment answer and after incrementing the answers what we'll do we will add all the pair or all the leaves which are on the left side okay get rid of all the leave distances on the left child add one to its value and add it to the a vector which we will send by its parent and do the same for its right value also we are just iterating over the left and the right child leaves and adding one value to it because we are moving one level ahead and then return this i hope you understand the logic and the quote for all of the three questions if you still have a dollars please mention down thank you watching this video in the next one keep coding bye
|
Number of Good Leaf Nodes Pairs
|
check-if-a-string-can-break-another-string
|
You are given the `root` of a binary tree and an integer `distance`. A pair of two different **leaf** nodes of a binary tree is said to be good if the length of **the shortest path** between them is less than or equal to `distance`.
Return _the number of good leaf node pairs_ in the tree.
**Example 1:**
**Input:** root = \[1,2,3,null,4\], distance = 3
**Output:** 1
**Explanation:** The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.
**Example 2:**
**Input:** root = \[1,2,3,4,5,6,7\], distance = 3
**Output:** 2
**Explanation:** The good pairs are \[4,5\] and \[6,7\] with shortest path = 2. The pair \[4,6\] is not good because the length of ther shortest path between them is 4.
**Example 3:**
**Input:** root = \[7,1,4,6,null,5,3,null,null,null,null,null,2\], distance = 3
**Output:** 1
**Explanation:** The only good pair is \[2,5\].
**Constraints:**
* The number of nodes in the `tree` is in the range `[1, 210].`
* `1 <= Node.val <= 100`
* `1 <= distance <= 10`
|
Sort both strings and then check if one of them can break the other.
|
String,Greedy,Sorting
|
Medium
| null |
1,732 |
all right hello welcome to a new video we're going to this problem called find the highest altitude number 1732 it is an easy problem Le code so let's go and get into it um yeah so um there is a biker going on a road trip the road trip consists of n plus one points wait the road the B there's a biker going on a road trip the road consists of n plus one points at different altitudes okay biker starts his trip at Point Z with UD equal to zero we given an integer array uh integer array gain named gain of length n we're gain at I is the net gain in altitude between points I and I + altitude between points I and I + altitude between points I and I + one okay uh for All For All Points okay return the highest altitude of a point um I'm kind of confused actually um the road trip consists of n plus one points at different altitudes the backer starts at 0 Z with okay so they're given an in Array gain of length n where gain um at I is a net gain an altitude between points I and one okay um return the highest altitude of a point um okay so you're given gain length of n we're gain at I is and that gain in altitude between points oh between points I and I + points I and I + points I and I + one between I and I + one I still don't really get it let's look at the output right at the examples so um I'm pretty sure they will give me an example so uh input so the gain is is5 so that's like the net gain and altitude between points I and I + points I and I + points I and I + 1 I don't really get that how is in that game between points I and I + one but game between points I and I + one but game between points I and I + one but whatever okay so um altitudes are 05 four um then one6 the highest is uh the highest is 0.1 which 0.1 is wait are they saying that oh like the actual like gain okay they confuse me on the way that they say that gain at I is the net gain and altitude between points I and I + I + I + one um can't they just say like it's the Net game where you get from going to I like I don't know that's really I don't really like that wording it's really confusing okay so um let me read it so there's a biker going on a road trip the road consists of n plus one points at different altitudes um the biker starts his trip at 0 Z with altitude equal to zero you're given an integer of Ray gain of length n where gain at I is a net gain altitude uh going to that point um return the highest altitude of a point okay so I like this now okay so I think I get it's not really making sense to me um that much but when I go through it hopefully you will so we know that our input is just uh an array called gains gain which just uh ins array and then our output is going to be um our output is just going to be uh integer it's going to be um highest altitude highest net altitude which is just in an INT um then to note that um we start at zero um but uh but gains at zero is equal to first Net game okay um I think that makes sense um that makes total sense okay so what we're going to do is we're going to go through some examples to kind of uh get into my head of if I do understand this or not so let's say um example one right uh we're given gains as one two and three okay and so at this point we start at zero right but then we add plus one then plus two which is three and then plus three which is six so we can say that the highest gain is going to be our highest altitude is six so that's the output uh I'm pretty sure that's how it works so let's say we have negatives now so let say we have 10 um and yeah 10 and then 10 okay so um so we start at zero right so 0 + so um so we start at zero right so 0 + so um so we start at zero right so 0 + 10 that's 10 so that's already a candidate for like the for the highest altitude we've seen so far and then 10 right that's uh zero and then 10 again which is 10 so actually let's make this 11 right 11 so then in this case 11 would be the highest altitude we get so we return that um and then I guess I have do have some questions I should have asked some questions before so some questions are um what is the men size of gains right um M of Gaines is one and then I don't think the values of games really matters uh to me that much so I wouldn't ask that question but they do specify in the constraints um so yeah um I think I'm kind of uncomfortable with the understanding of this problem so let's go ahead and kind of get some tools to kind of help us solve this problem um which is the matching phase I like to call it so um we going to have like a sum value uh sum variable it's kind of hold the sum and then I guess we can use the max function or method whatever it's called um and then we can use some if statements we don't really need if stat actually just keep doing that and then for loop I think those are all the tools that we need so let's go ahead and kind of plan it out um so first off I want to initialize VAR so I want to initialize a sum is equal to zero or res is equal to zero actually no sumal to zero and then we need a res is equal to umga 100 I'll do negative Infinity right um no it's actually zero that zero is U is equal to sub right um and then um I want to go through a for Loop right so four I range going through the length of uh gains um I want to say that uh gain I want to add to the sum every time we go so I so sum uh gets um gets the gains added to it so gains at I right and then we're going to check if um res is equal to either res or res is equal to the max of res or um sum at this point and then that should work um it work with a negative so yeah and then in the and I think just return res it's pretty simple this looks like it works so it work for this one because zero one and then two okay and so on so yeah and also starts at zero so it's awesome so we don't really need to worry about like starting res at negative infinity or whatever I'm pretty sure I can just copy and paste this into my code and it actually works so gain is not defined oh it's gain accepted and it works it's pretty bad why is it is there b solution or maybe no people just do what I did but um I don't know this is just RNG I guess yeah just RNG yeah it's just RNG uh so that's fine so yeah that works and yeah that's pretty much it
|
Find the Highest Altitude
|
minimum-one-bit-operations-to-make-integers-zero
|
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100`
|
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
|
Dynamic Programming,Bit Manipulation,Memoization
|
Hard
|
2119
|
5 |
hello everyone welcome to another video of programming problem Solutions in this video we are going to look at lead code question 5 longest P dring substring so let's get started let's first cover the problem statement it says given a string s return the longest pelring substring in s just to revise a Pome is a string which when spelled forwards and backwards is the same for example A B A when spelled forwards it's AA and well spells backwards it's ABA as well so it's a valid Bing room now let's look at the provided example in the first example we have two palindromic substrings first is Bab and the other one is Aba both are of length three when this is the case we can return any of them so both are accepted as a solution in the next one we have C BBD in this case paric substring is BB as such the answer is PB and at the last we have the constraint of this problem the string length will be between 1 and th000 and the string s will only consist digits or English letter so it will be alpha numeric that's something to keep in mind when coming up with the solution to come up with a solution we are going to use a Brute Force approach let's look at this with example so given we have a string a b c b a d what we will do is in this string we will trade over each character that is starting from a ending at D when at each character we will start with two indices left and right for each iteration we expand outwards and compare the two characters if the characters at index left and right are the same we continue expanding outwards if they're not the same we can confirm it's not a Pome and as such return early once we confirm it's not a p Drome we move on to the next character that is we move both left and right to next and then expand again in this case the left moves to a while the Right Moves to C and then we compare again since both are not equal we can move on to the next character in this case the next character is C we repeat the same process and expand outwards so left has B and right has b as well since they are both the same we can expand outwards and then move on to a and again the characters are equal we can expand outwards now since we reached the start of the string at a and also the right character is not equal we can safely say that this here is a valid P room that is a b c b a we store it in a string that has the longest P room we have encountered till now and then move on to the next character to repeat the process Now we move the left and right to B and then expand outwards again left move to C and right move to a since they're not equal we can move on to the next character so we move on to a then again expand outwards perform the check they're not equal we can move on to next as such we reach the end that is D at the end of the iteration we can return the longest P room we have encountered till now in this case our pad room had odd number of characters so when expanding we were assuming that both left and right are at the same character but in case if we had a even length palr it would have two characters at the center let's look at it with an example a b c b a d in the case of even length Pome our left will be at one C and the right will be at another C and we do the same thing that is expand outwards and compare the two we keep on moving outwards until we have a valid Pome it is better to understand this with a code example so let's have a look at code first I'm going to create a helper function that takes string and two indices from where to start or where to expand outwards and Returns the longest P string starting from those indices expanding outwards so here as you can see Pome helper takes the string and left and right indices returning the longest palindrome starting from that index inside it we will start a loop the first two condition of a loop are that our left and right are within the length of the strain the next condition here is the condition for Pome or a valid palome that characters at left and right are the same if they are same we keep on expanding as such left will be left minus and right will be right ++ minus and right will be right ++ minus and right will be right ++ when this Loop exists both the respective indices that is right and left will be at a character which is not part of the valid palome as such we will emit it and return the last valid Pome character so you can use slicing to do that start from left + one or the last that start from left + one or the last that start from left + one or the last valid character up till right since it's a half range we don't need to do right minus one it will only go up till right so to revise what this function does is takes a string and two indices left and right inside it makes sures that we are inside the length of the string and then expand outwards until it's a valid P drum at end of it we return the valid P drum by slicing the string now let's write our main function so longest Pome substring takes a string and Returns the longest palindrome in it to save the longest Pome we will create a result variable which holds a empty string at this point next up let's start iterating over string Corrector by corrector for this I'm going to use a regular for loop I is equal to z i less than the length of s and i++ first up let's check if it's a valid i++ first up let's check if it's a valid i++ first up let's check if it's a valid or length palindrome in this case we can do Temp and call our palindrome helper function and then pass I and I which is we are assuming that the character that we are on is the center of all palindromic string and then we check if Len of temp or length of temp is greater than the current length of result that means we have a new maximum length p as such we update the result to store it result equal to 10 next up we call the helper function again this time we will pass i n i + 1 so this time we are pass i n i + 1 so this time we are pass i n i + 1 so this time we are assuming that I is at the center of a even length Pome we repeat the same check again that is if temp is greater than equal to the current pic string length then we save it and in the end once we have iterated over all the characters in The String we return the result so when I was explaining I was using left and right this is what we did here comparing left and right and expanding outwards but inside the mean function I'm using just I and then I give the seed values for left and right for or length palindrome we say left is I and right is I as well for even length Pome which has two Center characters we say start from I and I + one whichever say start from I and I + one whichever say start from I and I + one whichever is the greatest we save it and as such we return the result at end of iteration so at the end we will have the longest pic substring in the given string let's do a small check to make sure that it's working as expected I can do result longest P MI sub string let me give a b c b a d and then fmt print Lin the result let's run the program to see the output so we got a error for slice out of bound or out of r that is because we are doing right minus it should be right Plus+ to expand it outwards let's right Plus+ to expand it outwards let's right Plus+ to expand it outwards let's run the programming in and see the output as you expected we are getting AB CC ba which is the longest p room now let's try with the other case which is cbbd in this case we expect BB to be returned and as expected BB is returned the time complexity of this solution is o n sare since for each character in the string in the worst case we would have to iterate over all the other characters in the string or in order of O and square that's it for the solution I hope you enjoyed it if you have any questions please post a comment under the video or reach out to the Discord see you in the next lesson happy coding
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
1,678 |
hello quick introduction to the video my name is Cameron I'm a graduate Apprentice software engineer currently studying at Glasgow University and I'm using this video as a way to sort of rubber ducky debug a Le code problem just attempt to solve it h talk through my thought process H hopefully solve it and hopefully it's useful to someone watching this so the problem I'm going to be attempting today is 1678 goal parser interpretation so I'm going to read out the description uh you own a goal parcel that can interpret a string command the command consists of an alphabet G left bracket right bracket and R left bracket a l right bracket in some order uh the parser will interpret G as G left bracket right bracket as a string o and left bracket a right bracket as a string a these strings are this the interpreted strings are then concatenated in the original order given the string command return the go parser's interpretation of command Okay so this would be G this would then be o and then this is a l so go okay that seems simple enough I'm going to switch over to my notes so ideas H I'm also just going to copy over one of these commands so given this example I'm just trying to think how I would do this in my head I think we would have a pointer um that would check whatever the first charact what the Char the current character is if the current character that you're on is a g then go to append G to the concatenated string it's first of all iterate through items or iterate a pointer through letters if let uh letter at current pointer is G then add G to the output string and move pointer a long one uh if current letter is left bracket and the next the current if sorry I letter at current pointer is left bracket and the next letter is a rate bracket then add o to the output string um then the last thing we're going to do is if have let current pointer is left bracket and then next is uh now I'm going to go back to the constraints here it actually says con command consists of G left right bracket and or this so you only need to check these first two that's how you know it's an L as long as these two it starts with left bracket a you that's how you can differentiate them so that's what I'm going to and I didn't really look at the constraint so the only other constraints is it's between one and 100 so uh if it's a light bracket in the left bracket and the next letter is a an a then add oh and move pointer along to cuz there's two items there's the left and the right um in fact we don't even need to do we need to do that we can it wouldn't really matter we move it along one or two we'll just say that for now and move pointer along to add um a sorry just going to put these in quotes just to make it a bit clear okay so sorry this is all I added here this is what I ended up with so iterate through a pointer through the letters so the letters here are going to be command for letter pointer and range length of letters um of letters letter _ pointer is equal to G then output do pend do pend we're going to pend G and then we're just going to do F letter here's letter _ pointer is equal to this we're also going to do this if we're going to check the next one letter pointer + one if that's equal one letter pointer + one if that's equal one letter pointer + one if that's equal to this then we're going to do output pend oh and then we can actually just do else cuz that's the one other command here else output pend a and we need to Define output and I think that's all needs to be done we'll return output and hit run for letter pointer and range it's not letters sorry it's command okay let's try this uh string object has no attribute pend I think it's just plus equals right okay what did I get H um ah this should be indented one there we go yep submit perfect so that got accepted thank you very much for watching the video hope this was useful to you in some way um even just seeing someone else's thought process behind solving one of these questions if you have any other sort of solution that was maybe a bit more efficient uh please leave a comment down below I love discussing these problems and Y thank you once again for watching and I hope you have a great day bye
|
Goal Parser Interpretation
|
number-of-ways-to-split-a-string
|
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order.
Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`.
**Example 1:**
**Input:** command = "G()(al) "
**Output:** "Goal "
**Explanation:** The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal ".
**Example 2:**
**Input:** command = "G()()()()(al) "
**Output:** "Gooooal "
**Example 3:**
**Input:** command = "(al)G(al)()()G "
**Output:** "alGalooG "
**Constraints:**
* `1 <= command.length <= 100`
* `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
|
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
|
Math,String
|
Medium
|
548
|
5 |
hey everyone today we are going to solve thetical equation longest paric subing okay so first of all um we need to understand paric subring so when I think about a solution I usually start with small and simple input because it's easy to understand and find a solution but this times let's start with like a big input like this so question is how did you find the longest paric subring in this input so I believe you choose one character then um expand the rength to left and right at the same time so if you find the longest pic substring directory so you are not human so actually uh this is the main idea of solution today um but problem is that we don't know where to start so that's why U we need to shift start point one by one so point is we need to shift start point one by one to check longest paric substring but what is the start point so since a paric substring is like a mirror from some character it's good idea to consider current index as a center of paric substring and expand left and right at the same time so for example so if we have input like a b c b a and if we start from C so in that case um we can separate this string into like a Ab and C is the center and ba a so um ab and ba is uh is a mirror when C is Center okay so let's see one by one so input string is a b c d a and uh we use a left and right pointers the both pointer start from index I so uh let's begin so first of all um so we can create definitely Parr right because now we are all pointer pointing a so only one character is a paric substring so that's why Max number max length should be one and left pointer move Left Right pointer move right from um current index because a center Uh current index is a center of um paric substring so next we move next and next but um left pointer is now out of bands right so that's why we finish iteration so in this case uh we will get one as a max length and uh how about so let me change the color and how about here so also we start from left and right and uh again so single character is a paric substring so one and uh after that we move left pointer here and the right pointer is here and I compare left character and right character but they are different right so that's why um if we start from B so maximum length should be one right so same and so let me change color again so we start from uh i l r so C is a paric substring right but one and uh move left so now left is B right is B so left character and the right character is the same so in that case our length should be one two three right so max is now three and then move next so left is a uh a and the right is a so they are same in that case max length should be one two three four five right and then um left pointer move next and the right poter move next but they are out of bounds so we finish iteration okay so let me skip rest of starting point B and a because we already found our max length and uh we did the same thing from B and A but of course solution called check the pic substring from b and a okay so next question is how do you calculate length of paror be found I mean this max length five so from this example um we found a five as a max length so simply if we subtract left pointer from right pointer so seems like we can get length right so right minus left and now so when um max length is five so left pointer is now minus one so minus one and the right pointer is 0 1 2 3 4 5 so 5 minus one that means six right but wait so max length is five so it's longer than um max length we found so the reason why this happen is because two pointers stop at next position of max length of parind when I is two and left is zero and the light is four so we found five as a max length right but we don't know five is a max length in the current iteration so we try to move to the next place to find a longer parind even if we don't find it in the end so that's why left and right Point are always overrun and stop at max length in current iteration plus one so we need to subtract minus one from left and right calculation so that's why this formula should be right minus left minus one but uh you still don't get it because we have two pointers expanding at the same time so you think we should subtract minus two so this is a calculation of index number so index number usually start from zero not one so right minus left includes actually minus one already so for example so a b a so if we have ABA and uh so left pointer is here right pointer is last index so in this case actual length is three right but if we calculate the length with index number that should be two right index two minus Z so it's already like include minus one compar with actually length so that's why uh we when we have two pointers and the calculator actual ranks right minus left minus one works well so now you understand the main idea of my solution but I'm sure you will not pass all cases so can you guess why so the reason is that I explained the case where we have all length of input string in this case five so point is we have to care about both o lengths of input string and if even length of input string so let's see one by one so we can use the same idea so let me write it briefly so if um we start from index zero so max length should be one right only a and how about when we start from index one and uh expand left and right and a and Bs are different so in that case max length is one right and then next so and expand left and right and B and C so max is one and how about when we start from index one 0 one to three in that case also max length is one right so is this uh correct actually no right because uh this range is a um paric substring right BB so we should two instead of one so why this happen let's compare two cases so regarding all length of input array so Center position of parum is definitely on some character array so when in current index number is two so C is the center of parum so how about the even length of input array so these two be are like a parind right so Center of parind should be here actually not on the character right between two be so uh that's a problem so how can you avoid this so my idea to avoid this is we start a left pointer with current index and a right pointer with current index plus one so we start iteration as if we are coming from between the characters so for example when index is current index is one so here so left pointer start from um also index one but right pointer start um current index number plus one so let's see one by one so now our left pointer and right pointer pointing the same character different place um so B and B so in that case we continue iteration so left pointer is now index zero and the right pointer is index three and uh they are pointing different character right A and C so we finish so do you remember the formula right minus left minus one so in this case right pointer is three and the left point that is z minus one that should be two right so that's why we will get the correct max length so we can use the same idea for both cases but the start point is different so that's why we call the same function twice in one iteration yeah so that is a basic idea to solve discussion so without being said let's get into the code okay so let's write the code first of if not s so in that case we immediately empty string and if not the case so start point should be zero and end point is zero and then uh we start iteration for I in range and the length of s and uh calculate um like a max length of um both case so let's create like a expand um around Center so passing the um string and the left pointer and the right pointer it's same right and uh let me copy this and this is a even case and uh as I told you left poter start with current index and the right Point start with current index plus one so we check both cases at the same time and then so let's create a expound uh around the center so here oops So Def expand around Center and uh string and uh left and right so um y left is greater than or equal zero so this is a like a auto bound check and right is less than length of S and S left character equal s right character in the case uh we move two pointers to next so left pointer should be minus one and the right poter should be plus equal one because we start from Center I mean current index and then after that um as I told you so formula is Right minus left minus one and then let's go back to here all and even and uh so um in this case we take like a max length of OD and even so max length equal max out and uh even and then if max length so current length is greater than so previous Lings so previous Ling should be end minus start in that case um update start and end point so start is current Center position minus max length minus one and divide two so and the end equal so I plus max length uh divide two so uh let me explain why we need to minus one okay the minus one is used to calculate the length of parum correctly based on um like a case or even case so here we try to get the length of half parindon um except Center characters so in this case max length is five right and uh Center character should be three and so we want to get length of ab so in this case two right so if we don't use minus one so we can calculate so max length is five by two equal two right so we will get the correct length so if we use minus one so that so max length should be 5 minus one is four right and divide two equal two so actually the result is the same but um let's look at the um even case so max parum is two right here so two and uh so if we don't use minus one so that should be 2/ 2 is 1 and uh if we so that should be 2/ 2 is 1 and uh if we so that should be 2/ 2 is 1 and uh if we use minus one so that should be 2 minus one is 1 divide two is zero and uh as I told you we want to get length of half parum except Center characters so in even case we have two Center character right BB so we exclude these two numbers so that means we want to get zero right so that's why actually this calculation is correct so that's why we need to um use minus one and uh since um so in both case uh since result is not affected by like minus one so that's why we subtract minus one for the both cases and then so I forgot return so after that all we have to do is just return s and uh start to end but we want to include this end character so that's why we should plus one yeah that's it so let me submit it look's get time complexity of this solution should be o n squ so N is a length of input string s so this is a because this code use a nested Loop the outer Loop runs for each character in the string and inner loop expound round Center can um potentially Run for the entire length of input string in the wor case so leading to the like o square and the space complexity is o1 so this solution code use constant amount of extra space for variables like a start and left right and the function parameters so that's why1 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
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
913 |
hey what's up guys this is chung so today uh let's take a look at this one number 913 cat and mouse um so this one is a very interesting problem because you know i think recently this week we just had like another cat and mouse number two as a weekly in the weekly contest so but so i would like to try to explain this one the first problem uh for the cat and mouse game so for this one like a game we have like on an undirected graph here and still we have two players mouse and cat and who plays in turn so which means that this is another like game theory problem okay and so um so at each sorry so the mouse starts at node one and it will move first and then the cat always starts at node two and there's also like a hole at node zero so those are three like a fixed uh position and during each player's turn so they must okay they must travel along one address which means that they cannot stay still they have to move in one of the direction okay and additionally so this is like the conditions that so it's easier to be ignored so basically cat cannot move to hold to the hole which is not zero and then the game will end in three ways so the first one is that you know if the cat and the mouse are on the same note then cat wins and if the mouse reaches the hole first sorry since the cat cannot reach the hole so if the mouse reaches the hole then the mouse wins and the third one is like the one that's a little bit tricky so if ever a position is repeated which means that if there's any uh if any player visits any of the node he has previously visited then it's going to be a draw game and then you need to return 1 2 or 0 respectfully so that's it and here we have some examples right so this is the graph here and so for this one like the mouse starts with here at 1 and the cat starts here so for this one we have output zero which means that this game is going to be a draw game why is that because so the first time the cat will move to three right and then the cat will move to five right and then the mouse has to be has to move and then he will move the mouse will move to four and then the cats will move back to two so and then the mouse come back here and then the cat will come back here so i'm gonna move repeatedly so which means that this will gonna be a draw game the cat basically the mouse cannot really reach the hole and but the cat cannot catch the mouse either so here's another example right so here we have a mouse here and a cat at here obviously right so the mouse would reach the hole directly without being caught by the cat um yeah there's some like uh constraints here so you know i mean for this kind of like uh game theory problem you know the i think one of the common uh strategies to a dfs right so we have a dfs with a actually so like top down dp we have some state and at each of the three at each turn the players will play out optimally so in this case like basically so when i say the players will play always play optimally they will always try to win right so in case of the mouse right if any of the basically from one of the state they will have like many other states here right so if any of those states can give the current player a win then the current player will definitely go to that state okay and uh and vice versa right so if that state will give the current player a lose the current player basically it will definitely not go in that's uh that scenario it will try other scenarios until there's nothing i mean so another scenario is that like if all the scenarios that there are there will be always a lose and then the current player has to return or lose right so that's gonna that's for the case of win or lose but for this one we have like the uh we have a draw case that's going to be a more difficult and you know you we you can try to uh maintain like a visited uh notes along the way but that's gonna be a little bit gonna be very hard to implement and another way of handling this uh draw case is the uh no we can instead of you know basically we have a dp here so the first one is going to be the mouse right the second one is going to be the cat so the for the third one you know what we can do is that we can introduce a another second a third state which is the total the current moves and i mean if the moves is greater than the total nodes than the two times the nodes then we can return zero so it means that you know whenever the moves is greater than the two times then that then the two times the number of nodes then we're saying that there must have already been a move that has already been uh visited sorry there must be have already been the move that have visited a node that previously visited already because why is that let's say we have a note right so since two players will take no we'll make the move uh in turns so to move to visit each of the nodes once it will needs uh nodes moves but if the nodes moves have already is already greater than the two times the nodes then there has to be a player that has already visited a previously visited nodes that's why we can return a zero and so for this part i mean i'm not hundred percent confident about the uh this upper bound but i think with this kind of uh this uh description here i believe it's so it's safe for us to use this condition to return a zero so yeah and basically that's going to be the uh the idea of the uh the top down uh dp solution right and uh so besides that the top-down dp actually for this kind of top-down dp actually for this kind of top-down dp actually for this kind of game theory problem uh so for this one it also introduced like a bottom-up it also introduced like a bottom-up it also introduced like a bottom-up uh solutions uh where i'll explain later on so but let me try to implement the first one which is the uh the top-down dp which is the uh the top-down dp which is the uh the top-down dp so we have a dp uh the first one is the mouse right and we have a cat let's mouse cut and moves and then we're gonna have like the uh the lru of cache right none so for the uh exit point like i said if the moves is equal to the length of the uh the graph times two right so if this one is uh greater let's see or greater right then we return zero and if the mouse is equal to the cat then cat wins which means we're gonna return two or the mouse is equal to zero then we return zero we return one which means the mouse wins so now let's take handle the uh the scenarios uh separately which means that you know the first one is the mouse turn so we just use this one if the moves uh divided by two equals to zero right that's gonna be the uh the mouse turn because in the end what will what we're gonna do is we simply return a dp of one two and zero so the moves and then we can what we can do here so like i said we have neighbors right neighbors in graph of the mouse so we have answer right so the uh you know the answer is going to be the dp of neighbors right and then the cat dots and then we have a moves plus one that's going to be the recursive dp car right so now we have a new position for the mouse but the cat stays the same basically so if the answer is equal to one it means that what means the mouse wins so if the current one is a mouse turn and there's like a state there's a next step scenario that the mouse can win the mass will definitely go there go to that direction which means that we're going to return one right and then in the end i mean if nothing wins there's no wind we can return two but like i said this is only the win or lose case but in this case we have like what we have about a draw case which is a zero which means that you know before returning two and so what does it mean it means that you know let's say there's no winning scenario for from mouse but before returning uh before the meeting the loose let's check if there's any scenario can give us a draw because draw is better than losing the game so that's why you know here i'm going to create like a flag i'm just i'm going to call it 10 draw right at the beginning it's going to be the false so basically i check if the answer is equal to zero so if any in any of the scenarios we can get a draw then i'll mark this one can draw equals to true so in the end before returning false i'm going to check if the can draw is true then rather than uh rather than being defeated i'm okay to make this uh to make a draw game else return two okay yeah so that's that you know and now the second one is the basically it's the cat's turn right similarly right so it i think it's pretty much the same i'll just copy and paste here instead we're gonna use the cat right to get the neighbors so here the mouse will stay the same but we're gonna have like a new uh cat coordinates so here uh similar for i'm going to do answer equal to 2 which means that if the cat can win so the cat will definitely go that direction right otherwise i'm also going to do a like a draw check here so here instead in the end i'm returning uh a one in the end yep i think that's it so let's try to run the code oh did i uh line 16 oh sorry c yeah excuse me so didn't make any mistake here so we have this one if this one's zero it can draw neighbors is that cats two cats yeah i think everything looks okay to me um oh did i is this one let me check yeah i remember that there's like a condition right additionally so cat is not allowed to travel to the hole so which means that you know here while looping through the neighbors for the next move for the cat we need to check that basically if neighbor is equal to zero we simply do a continue yeah okay yep so this time it works um yep and so for the time and space complexity right i think the uh so we have like uh what's gonna be the and so let's say the n is the length of the uh length of the graphs basically the length of the notes we have like uh n times another end here right basically that's going to be the moves of the this is also the end to end so it's going to be a another end so it's think somewhere i think close to n cube i mean even though we have another like for loop here right inside of the tp here but this one is bounded to the uh to the structure of the moves here so which means that if we have more moves and this neighbor will be less i mean basically this one is not always going to be a n because and it depends on the depend on the structure of the uh um of the graphs here so yeah i would say the time complex is still close to the n cube yeah so that's going to be the first approach which is the traditional top-down which is the traditional top-down which is the traditional top-down uh dp solutions basically you know so this is like another like classic game theory problem which where we just uh handled each of the players separately and for each of the players we always play out optimally right so if there's a like winning uh strategy it the player will definitely go with that otherwise and it will go to the second best option which is the draw game and the last one is the loose cool so that's the first approach and for this kind of problem you know like i said instead of the top down there's like another way to solve this problem which is the bottom up so what does the bottom up means it means that you know the uh we process the states from the end instead of from the beginning so processing from the end means that you know we have some states that we know uh who will win eventually so basically you know here are the states we know that either the cat will win or the mouse will win and we know all the other states for those kind of conditions and the problem is that you know and so from this kind of a certain win or lose state we can basically we can go to the previous city state and we can get uh the result for the previously state right so which means that you know let's say i'm giving you i'm going to give you a example so let's say we have a m c and then we have like a turn so let's say the turn is the mouse so let's see the this mc one is the is a state so one means it's the mouse turn and two means it's the cat's turn so let's see for this state we know this one the result is two means that for this state i mean it's a mouse turn to move and the cat will win based on this state then what can we get so i mean remember so this is the final state and there like many state can go to the current can go to this state and since okay since this one is the mouse turn so which means that the previous to previously states must be the cast the cat's turn and since the uh since the winning state so since the result for this state is the other one is that the other players win so we can just certainly get certainly uh deduce the we have another state like m dot c two and then dot 2 and here we have our m dot c3 dot 2 and then we have a m dot c4 dot 2. so all this states there's their result are also going to be two which means that you know at this state the cat will definitely win because there's like a neighbor right which will be the night the next state that can give a can guarantee a win for the cat so that you know at all these kind of parents or the previously states the cat will definitely choose this state similarly for the uh similarly if this one is two and the uh and the result is one so in this case the uh the turn it is cut so the turn it the contour is cat but the uh the result is the miles will win so for this one it's going to be a different scenario but similarly right the in the previously state so all the states going to be the mouse state right and then for all this kind of mouse state they're always going to be a 1 instead of 2. because similarly because the mouse will definitely choose the scenario because the mouse node the next state there's a state that can give the mouse a win so and that's basically that the idea right for this bottom up and we so basically we start with the uh we with the known uh we either win or lose state and we just try to populate all the states from bottom up and then in the end the states that we didn't get to populate will be the draw state and then after this kind of bottom up populates we can simply return the uh we can certainly check the starting state which is the one two and one if this one has been populated or not if it is then that value is going to be our value otherwise it's going to be a zero okay so let's try to implement that one so the second implementation is a little bit long and so to store the uh the pot to store the has the process as a result i'm going to use like the uh a dictionary to store that and so the key will be what the key will be the mouse the cat and the turn okay and the value will be the uh basically will be the result right so the result either zero one or two since we have like a default dictionary the integer so if we didn't populate it if we don't populate it so the default value will be zero which is the draw right otherwise it's going to be either one or two so and then we can start with the known like ending states right and then i'm gonna use like the q to do the you can call the bfs search and so what are the known states that's gonna again can certainly telling uh guaranteeing that either like the mouse win or the cat will win so it's this two states and since we have another state which is a turn that's why we also need to do a for loop for that in range of one two three so that's the outer loop so for all the for both the mouse or the cat's turn we loop through from uh one to n so the reason we do a 1 to n is because the uh the cat cannot go to the 0 nodes so the first one is the mouse win right it's gonna be the results of the uh of zero i and t which is gonna be one so here i'm doing the uh so for all the uh so the winning state for the mouse is going to be at the zero right and then the cat could be an anywhere and the turn could be either the mouse turn or the cat's turn and then i'm going to add this one to the queue so that we can start uh the bfs search from the state backwards and so 0 int similar for the cat win right so for cat win it's going to be i t right so this means that you know cat and mouse they are on the same they're the same notes again right since we're doing from one to n we're guaranteeing that so mouse uh the cat will never go to the zero note and then we're gonna also append this one to the queue cool so now we have the starting uh state and we just need to do a while q right to do this basically you know for this one we have m sorry oh m dot c dot turn right it's going to be a q dot pop left so basically we try to uh from the current state we're trying to process the uh trying to deduce to populate update the next states or you can call the previous states and then in the end right we can just uh we simply just return the results of one two and one so here the reason i'm i use like one and two and zero is because we have a zero uh zero state for the draw game and uh so for the turn instead of the reason i use the uh one and the two to write to represent uh the mouse turn and the cat'ster instead of zero and one uh like the what we have from the top down dp solution is because by using one and two later on it's going to be easier for us to map that value into the final result i'll show you what i mean later soon so and now we have since we have this m c and t we can get the uh the results right for that for this kind of states first it's going to be a m dot c dot t okay so from the current state from the current node where the current state we need to get out the all the parents the parent state so it's going to be a m2.c2.t2 right so it's going to be a m2.c2.t2 right so it's going to be a m2.c2.t2 right in get 3 notes pre uh states right m dot c dot t right so from this state we can get the previously states from the current states by uh by using the uh the graph okay and um and then we have r2 equals to the results right the uh m2 c2 and r and the t2 so we can we need to do a check here basically if r2 is greater than zero which means that this state has already been uh processed before so that we just need to do a continue we simply skip that now let's populate right populate next previously state so the first one is what is the one i just showed you right the uh basically if and if the t t2 is equal to r so which means that you know uh or we can use this like i said you know we have like m dot c dot one that's the state if this if the result for the state is equal to two right then we okay so i think maybe we can use that so and if r is equal to the three minus t so that's why i uh like i said so for the turn instead of uh instead of using zero and one i use one basically you know if the turn and the result for the previous state they're different right so it means that you know for the cat for the mouse turn uh the cat will win and if it's a cat's turn the mouse will win so for this one for this case we can make sure that no this previous state is going it's going to be a guaranteed win right result is going to be a m2 c2 t2 it's going to be the same as r here and then since we already populate that one we also need to add this one to the queue so that we can use this state later on right to populate a more state okay so that's the that's that one and oh yeah so for the previously states method so let's implement that one real quick uh get pre states right so we have m dot c dot t so it's going to be the announcer of a list and basically if the t is equal to one right that means that you know the current state is t so sorry so the current state is its mouse so which means that the previous state is cut which means that we need to loop through the address the neighbors for the graph for like from the cat okay and so here's a small uh small things we need to be careful is that you know always remember any time we when we try to loop through the neighbors for a cat we have we need always to check right if the c2 is equal to zero we continue right otherwise we just dot append and that state is going to be an m dot uh c2 dot two right it's gonna be the previous previously state and similarly for the uh if the current turn is cat so which means we need to look through the mouse and neighbor maybe a hem then for the mouse there's no need to check the zero because mouse can go anywhere and so now we have like the mouse two c and one okay so that's going to be the uh the state the method here okay so what's next and let's see i think here we're only kind of in one of the scenarios here because this one will always can i mean can okay always win right so this case i already explained right so that's the case for example if the current uh state current turn is the mouse but the result is the cast wing that's how that's we can directly populate that what if the uh what if the current uh the current attorney is the mouse but it's the instead of the cat's win it's a mouse win similarly if for the m.c dot similarly if for the m.c dot similarly if for the m.c dot two equals to two right this these two are like very similar let's say for this one if the current if this current uh state a turn is the mouse turn but it's but for the current state the mouse will win then what's going to happen for the previously state which is going to be the cats the cat state right for example we have like m dot c2.2 c2.2 c2.2 right that this is going to be the one of the previous state we could have multiple states right but let's consider this one state so if that's the case since i mean from this state you know the cat would definitely not go in to this state because he knows that if he goes to this state then the master will win so what he will do here so the cat will try basically will try to explore another state right and when can we update the results for this state right i think that's going to be a similar is a game theory right if all the neighbor states from the states they're always giving like a one as a result then the cat at this state has no other options but to set to one so remember so for this for the current for the bottom up we're not considering draw uh draw cases we're only considering either moss will win what cat will win so that's why for the second for second one right we need to check and so basically since we already checked this one so which means that we already covered the first scenario so at this scenario at the second uh at this house if here it means that so it's either this case or this case which means that you know the result and the turn they are the same so if that's the case we just need to check if our next moves failed from the m2 c2 and t2 and then if that's the case like right if the current state if all the next move there is failed then we have to set the results for this kind of state to be the uh to be the 3 minus t t2 which means that you know the turn has to be basically if it's mou if it is the cat's turn right if it's a if some if it is the mouse turn then the uh the cat will win if it's a cat's turn then the mouse will win that's why we do a three minus t2 as a shortcut all right similarly we also need to add this one to the append same thing right so to the queue okay so and now let's try to implement that the last helper functions which is this one okay so we have a m.c okay so we have a m.c okay so we have a m.c dot t so for this one uh what we're trying to accomplish is that we want to know if all the uh if all the neighbors right if all the nate the neighbors are a losing state so which let's say if the if it is a t if it's a mouse turn um okay if it's a mouse turn then the uh so the next state right remember so here we are like uh going from the current state to the next state it's going to be uh since it's most turn so the next move is going to be the mouse right graph dot m and so if the results of the next state is going to be m2.c.2 state is going to be m2.c.2 state is going to be m2.c.2 right it's not equal to 2 then we return fast so this one's saying that you know the uh if the next state is not a cat's win then it then basically it's not all the next moves is failed right because if this one is it's true if all the if other the next moves are all going to be uh a winning a wins for cat then that's going to be the true otherwise we return false all right similarly for this one like we do a 4 c 2 in graph of c right again right don't forget to skip this zero note case and then if the results of this so for this one it's going to be the m.c2.1 right m.c2.1 right m.c2.1 right it's not equal does not equal to one then we also return false otherwise in the end we return true yeah um yeah i think that's it and that's the whole implementation i believe and let's try to run the code here none type like 90. oh i must have forgot some to return this answer here yeah okay let's see did i do anything around here okay so this because you can continue okay and c2 mc so this one looks good so we have m2 equals to that results m2's yes sorry this is a long implementation so it's going to be a little bit hard to debug here uh trying to check this thing what oh here two right cats win means to two okay submit all right great so it's accepted um yeah so the basically that's the second uh implementation you know the uh so for second one i believe the uh the time complexity uh are the same since the uh we have like uh we have a n square state right and for the n square state that's going to be the since the t is like a constant that's why the m times c is going to be n square and then the for each of the states here we are we're doing like a for loop here right we have a for loop for the uh for the previously states it's going to be another n here yeah and uh yeah so that's why it's going to be a cube and actually you know we have like uh another nested for loop here i believe here we're also having like another for loop right to check the uh the parents notes here or the next notes and so actually to be honest so this one's going to be an n to the power of 4. yeah in my opinion i mean even though i believe we can improve this part by uh by not always uh checking out all the uh all the neighbors we can just create a uh or degree or like at least that every time once we are processed one of the edges will decrease the degree for that so that's and so and here we can only do a o1 check so ideally you know if we do it that way we'll do it so this one the time compressor for second one should also be a an cube yeah but i didn't do it because this is the most uh intuitive way to show you guys the uh the idea here okay so just to recap real quick right so for the second bottom up solution we start by populating the known a winning state for both the mouse and the cat and then from there right we do a bfi search uh we try to uh populate the uh the next states and where which we have two scenarios the first one is the it's a direct win the second one is the uh it's a basically it's a indirect loose right to be able to lose effort for this the state you know all the neighbors has to be a loose and then we can set the current state to uh to a losing value and otherwise you know all the rights they should they're considered to be a draw state that's why you know in the end we simply return check the results for this state for the starting states uh cool i think this is going to be still this video is long enough and thank you for watching this video guys stay tuned see you guys soon bye
|
Cat and Mouse
|
random-flip-matrix
|
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.
During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a `graph`, and assuming both players play optimally, return
* `1` if the mouse wins the game,
* `2` if the cat wins the game, or
* `0` if the game is a draw.
**Example 1:**
**Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\]
**Output:** 1
**Constraints:**
* `3 <= graph.length <= 50`
* `1 <= graph[i].length < graph.length`
* `0 <= graph[i][j] < graph.length`
* `graph[i][j] != i`
* `graph[i]` is unique.
* The mouse and the cat can always move.
| null |
Hash Table,Math,Reservoir Sampling,Randomized
|
Medium
| null |
389 |
Hello Hi Friends Welcome Back Today We Are Going To Solve List Of Problems Create A Knife And Different Species Among The Frequently Asked Questions By Google So Let's Go Through The Description And We Will See How We Are Going To Solve This Question Solve Of A Person Like You Are You Want To Springs Such Team Sprint Is Generated For A Random Shopping String Gas And Toys One More Liter At Random Position Return That Was Added To TV 100 Days Have Given One Example So Let's Take One Example Clear 100 For Example Laika S U Can C Effective They Have Been Given Not Skin Gas And String T Shirt 100 String And Essence Ki Chuthi Can Be In 100 Words Have Shed Ism That Ashwin S E Should And Dinner Random Characters Addso In This Is A Hindi Teacher Per 10 Random Characters Add 30 180 Development Agency ABCD Both Are Common Year So Have Two Random Character And Have To Return With Random Character During Sir Ripe For Example Plastic Ka One Another Example From Clear Solid To Springs Posting Is A B C Lead And Shakers Spring Is For Being delayed 1 day ago that and sits for this is the second spring so what they are going to do to solve this problem as they are going to convert this very swings into there actions will convert this using data activated offspring class so I will Get away from both streams and they are going to short characters in the air tight suicide first string and first year in uber greater noida b c and e right after shooting for this is position 012 and three say right and you will solve this another way Are also after shooting with sharing will again good day ago a b c d e and t shirt and compositions 2002 a380 servi so after you have to deal with are hui vigor and it's through this string write for string from 0213 12023 and will always compare character Beach Character With Ashwin Gadar Character's History Chapter 1 Class Art Director So Let's You Started Complaining To Here Andher Wrongs Yaar Same To You Will Continue To Here Oil Go And You Will Find A Year After Year Also Define Beam When Will Continue To Find Senior Also Find C and Will Continue for Indie One Day It Happened Find Different So I Have Not for Daga You Know the New Characters and a Great Soul at This Time at This Point Our Aaye is Basically Equal to That Stree Right and What We Will Do Laughter End Villages return late evening this is it from it is called as air and disease called as sp are right to you will just returned the length of a plus quarter inch and link of a guy will return at that point 0123 chilli total length is for basically choice Update position will return after the newly added character of Disti are so you can see it before this character not added new ring and to you will return today or answer site and in case you find any difference one while comparing in the daytime videos Returns The Difference Directly this flower doesn't want and furious return the length of the most advanced stage of life inches of and the convenience of the thing this bluetooth follows to shoulder problem so let's look into the implementation of so 100 first to have created a say are by using to care A Method Of Him And Anti Are Giving Birth To Carry Forward His Team Of Teeth And You Have Adopted For The Receiver Right Sorting Will Be Years Old Things In Login Correct Time Complexity For Both In Login And They Are Going To Your Deeds Are 023 Length Off the string is right and will always be reduced compare the highest position of a good night position and behind good match when will just returned you position of the year of baroda to will be the new and new development of matters will not happen during the following any Time Witch Mince Laddu E Didn't Find The New Lead Character Added That You Have Seen On Its Side Yudh Finished With Destiny But Will Never Find Any Wool Character Idea Vikas Distic And Visting Same Subha In That Case Sebi Discussion Will Return Tlf S Dot Length Because The Character This Newly Added Must Be The Last And Character Of Disty Basically I'm So Glad That Will Come And Share Like He Will Return Show Latest Churna Couple Of Examples Were Just To Make Your Deeds Working 500 ABCD is the one that give one to ask So let's create one example whiteness depending the second yudhistar take the worst thing tattoo set bda pc ab dlc aa and lifted example this ailment se content and any other thing is wife that and will take another example days have given us like temple run clear dry ginger And It's Ranbir On The Example Of That Aaj Mitti To Have Five And Less Size Cut Six So That's What Happened To The Members Of Extra Character And Some Mistake Hai Marketing Correct Result That Should Submit Power Solution Now On A Solution Contact With 3863 Percentage Faster And Seventy Percent Battery Memory Usage Charges Different So Common The Time Complexity For This Solution Will Be Model Prominent Time Will Be Sorting Ritu Jain Login Bigg Boss-1 Is Going To Take Ka And Where Bigg Boss-1 Is Going To Take Ka And Where Bigg Boss-1 Is Going To Take Ka And Where Is Number Character Since Rings Monday Morning Se Dhoyee Time Complexity Will be a login for this algorithm and space complexities that are creating this year and tears from string is som dat will be like you know you can see the deficit in zinc characters 10th time on liberia will have in character suvety space tattoo is best shots of You Can Solve Find Different Species One of the Frequently Asked Questions Set Google Show Me Three Do Kishan Practice Solution of Human Winnowing - Open Create Lead Videos Human Winnowing - Open Create Lead Videos Human Winnowing - Open Create Lead Videos for Java j2ee Solutions Class Fifth Preparing for Java Interview JE Create Videos for Help Java Interview Notes Telephonic Interview And in person interview they rock play list iodine and on my channel please check that the discussion is not have different programming concepts like benefits dynamic programming as well as the data structures is light hai samay pre me first link please show here that you know during Lord of good example and please subscribe to the Channel Can Help Restore More People Like You Are Preparing for Interview Please subscribe to the Channel and Hit The Like Button Like This Video Thanks for watching a
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
289 |
hi everyone today we're going to talk about legal problem 289 game of life let's take a look at the problem first according to Wikipedia article the game of life also known as life is a cellular automation devised by a British mathematician John Tivoli bought with em by EM cells each cell has an initial state either live or that one means life zero means that each cell in acts with its eight neighbors remember its aid is not four directions as we usually see in difficult problems so it's horizontal vertical and diagonal using the four following rules any live cell with fewer than two live neighborhood dies second rule and in live cell with two or three live neighbours lives on to the next generation third rule any live rule with more than three live neighbours die and the final rule any dead cell with exactly three live neighbours becomes a live cell as if by a reproduction so now it's asking us to write a function to compute the next state after one update of the board given its current state the next state is created by applying the above rules the above four rules simultaneously to every cell in the current state where births and deaths occur simultaneously so one of the tricky part of this problem is then you cannot apply the cell's accumulatively meaning you can apply the update to one specific cell at this time and then use that updated cell to update its neighbors or add to update the rest of the board that's just a beating the purpose of this problem so a straightforward way would be we can initialize an extra 2d array to be a temporary board so that we can hold all of the newly calculated cell values to the new board while we can continue to iterate on the current the Giblin bought in the current states meaning we can keep the current ball all of the values in the current board to be as it is until we finish traversing the entire ball while obeying to these four rules that's the most straightforward solution there how we can implement that what we can do is that we can go through this entire 2d array if this is M by n cells so we're going to initialize an extra to the Iranian exactly the same size M by n that's going to be the temporary copy ball which is going to hold all of the final calculated value into this temporary board another thing to make this solution accepted is that you want to assign all of the temporary board into the final into the given input that's what they will be checking in the lead code how can we implement this so first we want to understand how we can go through all of its eight neighbors within a 2d array suppose this is the one cell that we're looking at it is at 0 and we'll find all of its 8 neighbors how can we denote its 8 neighbors in this 2d array so first well find its top one that means its array is minus 1 right so this index of the Anand the cell on top of it is going to be rail it's going to be the row index that decremented by 1 so it's minus 1 0 economy next doesn't change this is its top neighbor that it's knacks neighbor we go clockwise it's going to be minus 1 and 1 so the row is the same as this one but the economy ness is going to be incremented by 1 the same go clockwise will be here this one now this row index is incremented by 1 if we go from here but the economy next doesn't change we go the same way really max incremented by 1 economy next doesn't change here 1 0 and then 1 minus 1 right 1 minus 1 which we get it from here the economy next needs to be decremented by 1 next we have 0 minus 1 which is 0 minus 1 really next needs to be decremented by 1 and then the last one that we have is minus 1 in comparison to this one so these are the eight total neighbors that we need to go through now we can put this on into the actual code so first we're going to use two variables board length since well we'll be using this many times and basically is the height and n is the width so I'm just going to use a one character variable to simplify this to speed up my timing next well initialize a temporary array we'll just call it next the int size is m and n remember at this moment everything we initialize to is going to be 0 so by default now the next this board the next board is 0 everything is filled with 0 at this moment so next what we will do is we'll have into the array we just called directions to help us hold all of this new int here let's see what do we have so here is all of the aided directions that we just went through so these are the let's go stand from my minus 1 0 so minus 1 is 0 then next minus 1 we basically copied this all of these 8 neighbors coordinates into the actual code so all of these neighbors 1 2 3 4 5 6 7 8 all of these 8 neighbors that were going to traverse through for every single cell that we're going to visit till now we'll just get it through every single cell in the gift in the given board is smaller than M I plus purse now we do in int we have another variable J minus NJ plus pressed next what we will do is that we work will have live count because we want to keep track of how many live cells that we do have for the current cell that we are iterating on so we always will initialize a new variable for the current cell and then we'll go through all of its eight neighbors directions this one is to be a now we'll go through every single one so for every for all of its eight neighbors we are going to use ax and wine to be its coordinates so it's going to be the first one is going to be ax coordinate plus I this is pretty much a template code simple way to calculate the cell denoted by I and J so if we want to make sure that I and J am meaningful which means they are still winning the board if they are out of the boundary or if it's or if this cell is not in lifestyle we don't even need to count it right so if X is greater than or equal to 0 and X smaller than M it needs to be within the boundary of the height and Y is greater than or equal to 0 and Y is smaller than n which is the width of the board and bought x and y means to be a live cell only in this case what we will do is we'll increment live count by one at this point after we go through all of these eight neighbors this for me is this and then we can check what we need to do we need to follow all of these four rules the first let's go the death cell first so if vaud i J equals it is that is very straight for because there's only one rule with exactly three neighbors becomes alive cell so if live count equals to three then next I NJ becomes a live one remember again when we initialize this next temporary bought everything is default to be zero that's how Java works a bit of in most other languages too so then in the other case else F bought I and J and it is a live one so there are three rules that we need to consider so the first one is any live cell with fewer then two live neighbours dies so dies that means it's going to be next I and J is going to be zero which means we can safely ignore in this case right because by default when we initialize this one next ing is our already zero so we can just ignore this one so let's take a look at rule number two any live cell with two or three live neighbours lives on to the next generation that means we need to take care of this because next I and J needs to be one so let's see how we can do this live cell with two or three live neighbours that means count lives equals to 200 lives equals to three in either cases we should keep this one alive that means we changed the next from the default value zero to one that's what it means now let's take a look at the rule of three any cell that with more than three live neighbours what I okay we don't need to worry about that because default one next I and Jade is zero that's it then we're done with all of the phone rules now at the end what we need to do is that we need to copy over all of the value that we calculated for the next state for each cell from the next ball into the current board because that's how this problem money code is going to check your is going to validate your result now let's do that you can just quickly copy this last it nasty for loop now we'll do what we'll do is well assign memories the value in every cell in Max ball into bond that's it this is the in time algorithm now let's hit submit and see we got this cannot find symbol okay this is I don't know what I have in my mind completely wrong variable name okay let me hit submit again alright it's accepted custard I'm 100% crazy and this is the custard I'm 100% crazy and this is the custard I'm 100% crazy and this is the idea of the most straightforward solution or the algorithm to solve this problem game of life of course there are even more optimized solutions because in this problem the time complexity of this algorithm is o M times n because we have to visit every single cell but that's not the thing that we can optimize because in any algorithm for this problem we need to visit every single cell so the time complexity the lower bound of this time complexity is guaranteed to be Oh M times n but the space complexity of this problem is something that can be improved in witches Oh M by n in this case because we have initialized it completely the same size of temporary ball in the array right this is something that can be optimized but that's beyond the scope of this video in this video I just want to talk about the most straightforward solution to this problem to give people some idea of how this works basically a few problems you need to overcome in your mind which is all of the states change simultaneously you cannot calculate each cell at one time and then use the updated cell value to calculate the next cell and then and second one is that how do you go through all of its eight neighbors there multiple ways this is one easy way to do that the third one is that you assign all of the values that you calculated from the temporary board into the given input bar to make sure that the answer is correct if you're having any questions comments please drop me down in the comment section below and if you find this video helpful please do me a favor and hit the like button I'm doing an impression a lot and that's going to help have a lot with the YouTube algorithm as well and also don't forget to subscribe to my channel as we continue to go through a lot of interest in lico Danny and interview problems that's it for today's video I'll see you guys in the next one
|
Game of Life
|
game-of-life
|
According to [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. "
The board is made up of an `m x n` grid of cells, where each cell has an initial state: **live** (represented by a `1`) or **dead** (represented by a `0`). Each cell interacts with its [eight neighbors](https://en.wikipedia.org/wiki/Moore_neighborhood) (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return _the next state_.
**Example 1:**
**Input:** board = \[\[0,1,0\],\[0,0,1\],\[1,1,1\],\[0,0,0\]\]
**Output:** \[\[0,0,0\],\[1,0,1\],\[0,1,1\],\[0,1,0\]\]
**Example 2:**
**Input:** board = \[\[1,1\],\[1,0\]\]
**Output:** \[\[1,1\],\[1,1\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 25`
* `board[i][j]` is `0` or `1`.
**Follow up:**
* Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
* In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
| null |
Array,Matrix,Simulation
|
Medium
|
73
|
787 |
hello everyone welcome to algo simplified let's solve today's lead chord challenge that is cheapest flights Within k-stops cheapest flights Within k-stops cheapest flights Within k-stops in this problem there are ncts connected by some number of flights you are given an array flights where flights I is equal to from I to I comma price is I which indicates that there is a flight from City from I to SCT 2i with a cost price High it means this much cost will B there to move from a city from my to a city to I and we are given three integers Source destination and K which means we have to move from Source City to destination city with at most K stops and we have to return the cheapest price to move between the source and the destination city so let's start now the first algorithm which comes to my mind is dixtra since it's a graph problem so let's think about the graph algorithms DFS and BFS and DFS and Bellman Ford or let's take fluent warship you know Bellman Ford algorithm and Floyd virtual algorithm can calculate the result but we need to do some modification and also it is more it has more complexity than the diastras algorithm because they Bellman Ford is used to calculate the shortest distance between the source to Old other nodes when there is our negative weights and fluid washer is used when we have to calculate the minimum distance between every possible two nodes so we will rule this these two algorithms out now we just have three algorithms now let's talk about dijkstra's algorithm dykstra's algorithm is useful in case of weighted graphs whereas BFS is very helpful in unweighted graphs now since BFS and DFS and dijkstra's algorithm they all are can be used but now let's have an analysis about all these three algorithms in DFS algorithm what we will be doing is we will be going through every possible path within k cities like within K stops and we will check if we can reach the source City and if the source city is reached then we can say okay it's reached and we just have to like take the minimum now you would be saying okay we will do this in this by this way but if we do it using BFS then what we will be doing or diastras what's the difference between them because you need to identify those algorithms so basically using dijkstra algorithm it takes V plus um e log V complexity to solve the problem and BFS has basically we go V plus e and DFS has a complexity of Big O of V plus e now you would be wondering which one should we choose obviously we should choose the extras algorithm because over BFS or DFS like what's the difference how should we do this problem or what algorithm should we use in first so let's talk about dijkstra's algorithm in this problem we are given a constraint that we have k at most K cities in between what does this mean it means it changes the time complexity of these algorithms because these algorithms need some modification in them in order to become compatible with this problem so how we have to change the dijkstra's algorithm let's discuss about this thing the very first thing about this algorithm is that if we go to Every let's just say if we are not visiting like it like just say if we are visiting all the paths then since we are using a priority queue we will always visit up we will always visit a path having smallest price in this way it can be possible that there are some paths where like it can be possible that we visit some paths and that we keep on visiting notes having the smallest value within K stops but we never reach the destination node destination city or reach but not with the smallest path it may be possible that we reach but with not with the smallest path let's just think about it you will understand why and because we are always having a global optimization in the dijkstra's algorithm we might never explore through a particular node because we think if because due to the uh due to the length constraint like if we get a bigger price or bigger length if we just visit then we have a constraint to check that thing and we might never reach thus destination node with the smallest optimal price so we may not reach the node that is destination with the smallest optimal price now the second thing in order to reach we need to remove the global distance constraints on nodes which can give a stealy so this is these are the two things that we should consider first in the priority queue it may be possible that we never reach the node or we reach but due to the constraint this K this constraint K we due to this constraint end we like never reach the destination node and if we try if we can reach the destination node if it there is a possibility to reach it with some other path then it may be possible that due to the globalization we never end up there but in the second case if we remove the globalization then it may we may never reach like we may reach like we will definitely reach but it will give us a tle because we are not optimizing it and we are putting everything in our like priority queue and since practicum insertion and deletion takes n log n so it will give us tle now so we will rule this out so not preferred so this algorithm is not preferred now let's come to BFS and DFS in BFS we need to go to every possible like BFS we will be like going like in like level by level so it may be possible if we go level by level let's say in this example if we go level by level the first level is one and two and we see here in the first level we reach 2 here and 1 here but we assigned 500 to 2 and 100 to 1. now since we have visited two from one we cannot visit 2 but if we visit 2 from 1 then it we can say that okay the distance is 200 that is less than 500 so in this case due to constraint k we know we like do not need to check the visited nodes like we don't have if we check visited notes then we probably end up getting a wrong answer so in order to get a right answer we need to check the visited nodes like we don't need to check the visited nodes so this is a possible way to solve but the constraints will be modified to think of e into K because the edges we may like travel through every Edge due to not like we may visit the visited edges again and again so and since the maximum path length can be K so the time complexity will be big of V plus e into k now let's talk about DFS approach in the DFS approach it's kind of similar we have to check the similar way all the paths from one node to the another node but in this also we may go to like but if it was a normal BFS compared to DFS then this DFS would not be preferred since DFS has many more paths as you know in DFS we travel many we might travel through many more edges but in this case since in the BFS also we are not keep tracking of keeping track of the visited similarly in this also we are not keeping track of the minimum so with the constraint K the modified time complexity would be because of V plus e into k so you may consider any of the BFS or DFS approach you like so I can code it both for you but due to the limited constraint of time as the video will get longer so I would prefer to code it using BFS and do comment if you want a DFS code I will code it down and share it with you in the comment section or in the description so do comment if you want it so let's solve this problem in this problem we have to make a adjacency list let's do it now we have to fill the elements in the adjacency list that's how we will fill it foreign and in this queue we take a vector in q we will be putting the number of cities like number of stops that we can um like number of cities where the maximum stops and the source like the current node that we are at and the distance so we will take keep a price also in this way why we are taking this price thing we will keep track of the minimum distance of each node in this way if we find a node like let's say we again go to a node let's say if it's 2 and it has more distance like it is a simple optimization we are since we are not using the visited thing so we will be optimizing it in this way we the only optimization can be done by two things one is we don't visit more than we don't reach that source with more than k um stops in this way we are optimizing our time complexity and the second thing is we don't go to a node let's say two or so which we have already visited and visited with less price with a cheaper price if we have visited two with a price like let's say if this node this hundred doesn't go from one to two it goes from two to one so let's say if we reach one by hundred so why would we reach one again by 600 it would be totally redundant step and which we would never want because reaching one earlier with 100 and then again with 600 is of like doesn't make any sense so we just have to take prices so that we visit the node any particular node only when the price we have visited is larger and in priority queue if we do so we will always visit the nodes with the smaller number and we may end up with not visiting the node such that it leads us to a source node having the minimum possible price so you need to have some dry run in order to have a good understanding over the test cases so in the beginning I'll assign the price of the source as zero now we will push like the source the distance and K plus 1 because we have we can have at most K stops and we are including this The Source One also so just having K plus 1 so that we can deal it with it without any confusion let's say we can move at most in this example most one stop can be there so if we keep two here so when we reach this one it will be having one and when we reach this one it will be having zero it means we have traversed through at most one because when you start from this will also be counted because every time we will be reducing the number of stops that we have visited so keeping a value that is one larger than the given value will make us deal with that and we will be able to do it without any adding any other condition so this is the current node let's define it like this command distance comma current k equal to Q dot front Q Dot pop now iterating through all the adjacent nodes to this current and also next stop comma next distance that is the distance of this will be this next now if we have more than zero like stops in between means at least we have one stop in between here like we have this as one it means currently we are at a position where this is the last in between stop and now we have to move to the either this should be a destination or it should be a like node where after which we will not move ahead so this condition is just to check that maybe we should what should we do is if current K is equal to 0 then we just continue here because popping it like breaking it would take us out of this while loop or maybe there are more elements in the queue so we will remove this condition and if the price of the next stop that is this given stop is greater than distance plus next distance it means that yeah the distance is smaller then we just make the distance of this one as this and push the basically the next stop then the distance that we have traveled till now and minus 1 and in this way we will solve this but and we will return price of destination let's run the test cases I hope you got how what I did during this code maybe it does not support this thing or there is some issue let's not just use it just assign end current equal to Q dot front zero and distance equal to Q dot front one and two just remove this one and maybe this also gives us some kind of error so just to avoid it let's just remove this one also now let's run the test cases oh I didn't just I take some random values like sometimes I just use NXT and sometimes I just use any XD that's why one more thing I just need to take care of this thing if it's into max then I have to return negative 1 because it's never reachable as I have initialized it using uh what's the error with this maybe there is some problem K plus 1 okay we have this thing current K is equal to zero then continue because if I go in any one of these it's of no use otherwise if yeah this is the thing then go ahead yeah so if it's even less than or equal to zero Maybe we have somewhere kind of zero one and put 0 here sorry less than or equal to Z I think this is giving some kind of problem let's run it this way what's the problem with this code I don't understand let's debug this one okay inserting yeah you just see what I was doing was 0 1 2 should be there and I can keep this thing over here only and this should be two that's why I was getting an error now it should work yeah let's submit it wrong answer what's the problem yeah so just I just told you if it's equal to int Max then we should return negative 1 else price destination would be fine now it should run fine because if the distance is int max if it doesn't get changed while performing the BFS it means we never get to visit the destination node from the source so let's submit it happens sometimes like when you do things like yeah so that's all for this problem I hope you understood if you have any doubt please do comment please like this video subscribe to our Channel and do comment if you have any doubt thank you for watching I'll go simplified
|
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 |
329 |
Matrix containing positive integers including zero and from this Matrix we need to find out the longest strictly increasing path by moving in any four directions that is we can move up down left or right from each cell of this Matrix for example this path of length 7 is the longest strictly increasing path in this Matrix one interesting thing about this problem is that since we can move in any four directions there can be many paths from each cell of The Matrix and therefore there can be many overlapping paths as well for example take these two paths starting from the cell value 2. here we can see that this part of the path that is the path starting from cell containing value 6 is actually overlapping and therefore we are Computing it twice since in this problem there are overlapping and repeating sub problems this problem is a perfect candidate for dynamic programming so what we will do is for each cell in the given Matrix whenever we are finding out the longest increasing path for each cell in The Matrix we will store the result in the corresponding cell of a new Matrix for future use and we will call this new Matrix paths for example for the first cell five in order to form a strictly increasing path we can only choose one direction that is towards the right so now the longest path from Cell 5 is 1 plus the longest path from cell six we can only move in One Direction that is towards the right so the longest path from cell six is one plus the longest path from cell eight now also from cell 8 we can only move in One Direction that is towards the right so the longest path from cell 8 is 1 plus the longest path from cell nine from cell 9 we cannot create any more increasing path so we cannot move forward to any directions from here so the longest path we can have for cell nine is one let's update it in the paths Matrix accordingly now for cell 8 the longest path is one plus one equals two for cell six the longest path is one plus two equals three and for cell five the longest path is one plus three equals four now for cell 3 we can only move in One Direction that is upward Direction and we know that the longest path from cell 3 is 1 plus the longest path from cell five since we have already computed the longest path from cell five we can reuse it so the longest path from cell 3 is 1 plus 4 equal to 5. now for cell 2 we can move in two different directions a upward and towards left if you move upwards in that case the length of the path will be 1 plus the longest path from cell six that is 1 plus 3 equals four and if we move towards left in that case the length of the path will be 1 plus the longest path from cell tree that is one plus five equals 6. since we are looking for the longest Park from cell 2 we will choose the left Direction so the longest path from cell 2 is 6. now for cell 1 we can move in three different directions upward left and right if we move towards right then the length of the path for cell 1 is 1 plus the longest path from cell seven since we have not yet found out the longest path from cell 7 first we need to find that out from cell 7 we can only move in One Direction that is upward so the longest path from cell 7 is 1 plus the longest path from cell 9 which gives 1 plus 1 equals two and therefore now for cell one the length of the path taken through the right direction will be 1 plus 2 equals 3. if we have moved upward in that case then the length of the path for cell 1 will be 1 plus the longest path from cell 8 that is 1 plus 2 gives 3. and lastly if we have moved towards the left then the length of the path will be 1 plus the longest path from the cell 2 which is 1 plus 6 equals 7. among these three the longest path is seven so since we are looking for the longest path we will choose this one and by the end of the iterations we will have the longest path from each cell of the Matrix and we will choose the maximum among them and return it let's call the solution now we need to find out the longest path from The Matrix so we will have this variable initially set to zero and at last we will return it for traversing through the Matrix we need to know the number of rows and columns we will store it in these variables m and n for storing the longest increasing path from each cell of the given Matrix we need to create a new Matrix of the same size we will fill it with zeros initially since we are allowed to move in four different directions we can store these four directions in the form of arrays so whenever required we can simply add these to the cell indices now let's Traverse through the metrics we will find out the longest increasing path from the current cell and store it in this variable for finding the longest path we will write a separate function this function will take the current cell indices and the previous cell value but the previous cell value is required because we need an increasing path and therefore we need to check whether the previous value is less than the current value so when we are starting a new path from any cell of the Matrix we can pass minus 1 as the previous value because it's given in the question that the lowest number that can exist in the Matrix is zero so minus 1 is valid for creating an increasing path in this function we will find out the longest path and store it in the corresponding cell of the paths Matrix we know that the longest path is found out as 1 plus the maximum of paths we get from the four different directions and we will return the result now in the beginning of the function we need to put some checks if the cell indices are out of Matrix or if the previous cell value is not less than the current cell value in these cases we need to return 0. foreign also if we have already found out the longest increasing path for the current cell we can return the previously computed result so that we need not have to repeat the computation and during its iteration we can check whether we have found out the longest path and update it accordingly that's from the program and check foreign see you in the next video
|
Longest Increasing Path in a Matrix
|
longest-increasing-path-in-a-matrix
|
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`.
From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).
**Example 1:**
**Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[1, 2, 6, 9]`.
**Example 2:**
**Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.
**Example 3:**
**Input:** matrix = \[\[1\]\]
**Output:** 1
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `0 <= matrix[i][j] <= 231 - 1`
| null |
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
|
Hard
| null |
129 |
hey everybody this is Larry this is day 14 of the lead code daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's forum um is it like three week or something okay yeah uh anyway today's bottom is 129 some route to Leaf numbers hit the like button hit the Subscribe button join me on Discord let me know what you think I might have already said it but look I my excuse is that it's daylight savings and it's really wacking I don't know it's only an hour they say but I'm just like all confused all the time now uh at least for like another couple of days so please excuse me all right let's see you're given a root of a binary trick name containing digits from zero to nine each route to leave path in the tree represents a number we turn the tourism of our roof to leave numbers the test cases are generated so that it will fit in the dirty toolbit end so we don't have to worry about um though they didn't say side or unsigned but I mean I'm using five fund so you know if you're not using by Fun be a little bit careful okay so I mean I don't think there's anything tricky about this one I think this is just a regular you know that first search I think uh or that first or just recursion rather uh I think one thing that I would say is that um it's a good practice for my pencil uh it's a good practice for shift and add um calculation of a number and definitely something that comes to Handy a lot and competitive I don't know if it comes in to play damage on interviews but maybe I haven't done one in a while so don't hold me to that one but that said you know tree pumps are pretty standard pretty straight um like they come up a lot so definitely um yeah be familiar with them so okay so let's get let's Let's uh let's go to calculate right so I mean this one some uh I'm gonna be a little bit lazy uh do some maybe current and what I mean by that is that I'm just gonna have a global uh total say total is equal to zero and then if node is none then we return otherwise um if no dot left is none and no dot right is none that means that this is a leaf if this is a leaf then we just uh well we return and then we add to the total uh so current uh total we add current times 10 plus know that value right the shift and add um otherwise um we will just calculate no dot left right maybe we could do this right and now we don't have to do that and then yeah and then we calculate and then zero and maybe my base case is a little bit messy so we'll uh we'll see if we need to clean it up looks okay though uh do I have any weirdness like one node answer maybe we'll try the one note case right yeah it looks okay so let's give a submit and yep there you go uh 1078 streak um yeah this is gonna be linear time of age space where H is the height of the tree remember the implicit stack space um I don't know if I have anything to add to this one um definitely feel free to ask a question in the comments or on Discord uh just so that you know um yeah just because you know that I can anticipate more questions in the future and try to answer them as best as I can cool uh remember if you do have a struggle with this though uh remember to kind of look up Chef Annette but that's what I have for today though we'll call it an early night and beat some delicious Ramen or something uh but yeah let me know how daylight savings affecting you because clearly I'm a little bit I don't know but yeah stay good stay healthy it's a good mental health I'll see y'all later and take care bye
|
Sum Root to Leaf Numbers
|
sum-root-to-leaf-numbers
|
You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
112,124,1030
|
1,601 |
hello everyone welcome back here is when I'm saying today we will tackle a challenging problem that results around employee transfer so request among a set of buildings so now a problem goes like this we have and buildings each having some number of employees and some of these employees want to transfer from one building to another and our task is to maximize the number of requests we can accommodate under one condition so net change of employee in each building should remain zero so if one employee leaves a building another should enter so now the key to solving this problem lies in important observation so we can a track every change and using epic tracking uh validate the solution so if the change is different than zero we just continue and process another uh yeah a request so let's try to implement it so first self answer to store the answer it will be zero and in degree 0 times n and self Max request will be request in degree n 0. and now return self of answer and now we need to implement uh the max request function that will be called so let's implement it Max request will be south of request as a list in degree int and n as end index count in known so yeah I think we can so now you can see the code better so if index Len request then check if buildings have an in degree of zero so four high in range n if in degree I not zero so we know it's not zero we return and self answer will be Max of answer and our count so we return and considering this request increment and decrement for the buildings involved so now we will increment one building and decremental another so request index 0 will be -1 and in degree request -1 and in degree request -1 and in degree request index one will be plus one and then with reverse to another so move on to the next request and also increment the count of request so self will be Max request in degree and index plus one and count plus one as well so now we backtrack to the previous value to move back to the original start before the second recursion so we need to in degree request and then we reverse so zero will be plus one and one will be -1 so integral request index one will be -1 so integral request index one will be -1 so integral request index one will be -1 and ignore this request and move on to the next request without incrementing the count so self Max requests will be request in degree and index plus one and just account so uh this should Traverse uh yeah all possible solution so let's run our code and see if implementation works so yeah it's working for uh those basic cases provided here so what we did so we implemented it with a recursion and backtracking but also it's worth noting that we can solve it using a recursion or iteration so if we start with recursion approach in this scenario it request gives us two options so accept the request and transfer the employee or just ignore it and to track employee count in each building uh we can use alright and also at the responsibilities that what once we iterate over all their requests we check if each buildings net change is zero if it is we count the number of requests we consider and update the max request considered without populating the constraints so that's a recreative approach so next up is the iterative approach so here we are can explore the fact that total requests are at Max 16 and trying out uh all uh possibilities so both Solutions apply a similar principle however the iterative solution will avoid the recursion and it will be yeah implemented a bit differently so let's run our code to see if it's working for unsynthesis cases as well so I'm running it and hopefully it will pass and who will see how fast this implementation is so yeah this implementation uh beats 50 free percent in runtime and also 81 with respect to uh memory so it's quite efficient and that's it for today I hope this explanation help you understand how to solve a problem using uh recursion and if you have any doubts or question uh drop them in the comments section below and remember uh if it's cutting it's all about practicing and making progress so stay motivated happy coding and see you next time
|
Maximum Number of Achievable Transfer Requests
|
maximum-number-of-achievable-transfer-requests
|
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`.
**All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`.
Return _the maximum number of achievable requests_.
**Example 1:**
**Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\]
**Output:** 5
**Explantion:** Let's see the requests:
From building 0 we have employees x and y and both want to move to building 1.
From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
From building 2 we have employee z and they want to move to building 0.
From building 3 we have employee c and they want to move to building 4.
From building 4 we don't have any requests.
We can achieve the requests of users x and b by swapping their places.
We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.
**Example 2:**
**Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\]
**Output:** 3
**Explantion:** Let's see the requests:
From building 0 we have employee x and they want to stay in the same building 0.
From building 1 we have employee y and they want to move to building 2.
From building 2 we have employee z and they want to move to building 1.
We can achieve all the requests.
**Example 3:**
**Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 20`
* `1 <= requests.length <= 16`
* `requests[i].length == 2`
* `0 <= fromi, toi < n`
| null | null |
Hard
| null |
1,732 |
hey everyone today we are going to celebrate for the question finds the highest altitude so there is a vital going on a road trip the road trip consists of n plus one points at different altitude the biker starts his trip on point zero with altitude equals zero so you are given the integer array gain over links n where again I is a net gain in altitude between points I and I Plus 1. for all um 0 greater than equal I less than n so return the highest altitude of a point so let's see the example so you are given this input array output is one so yeah um this is a simple question just uh we um edit every single number and then um keep the um highest altitude at some point so in the case the highest is one okay so let's write the code um this is a very easy question so as I explained earlier all we have to do is um every time we add a current number and the keep highest altitude at some point so first of all um we initialize like a current um and uh this spica start zero and so current High test should be current so that means zero and then start looping for altitude in game and every time uh the altitude to current and then compare highest equal marks and the current highest buses current um total so yeah okay that's it and then the highest that's it so let me submit it so it looks good and the time complexity of this solution should be order of n where n is the length of input risk gain so this is because this solution called iterates through elements of gain list once in a for Loop so performing the constant amount of operation for each element so that's why order of n so space complexity is a 01 so we don't use actual data structure just a simple variable current and the highest so that's why space complexity should be order of one yeah so that's it I hope this video helps you understand this question well if you like it um please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Find the Highest Altitude
|
minimum-one-bit-operations-to-make-integers-zero
|
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100`
|
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
|
Dynamic Programming,Bit Manipulation,Memoization
|
Hard
|
2119
|
906 |
hello everyone welcome to coders camp so we are today at the eighth day of may lead code challenge and the problem we are going to cover is super palin ropes so the input given here is the two integer values left and right and we have to return the number of super palindromes within this range left and right that's inclusive so let's understand this problem with an example so here is our given input value where left starts from range 4 and right is up to thousand and the numbers are said to be super palindromes if they are palindromes and they are squares of another palindromes for example from the range four two thousand these are the list of fallen rooms which are perfect squares and if you see the numbers these are squares of these numbers that is 2 squares 4 3 square is 9 11 square is 121 and so on and if you see 2 3 11 22 or again palindromes in this case 22 is a palindrome and again 484 is a palindrome so 484 is said to be one super palindrome but here 26 is not a palindrome but 676 is a palindrome so in that case 26 cannot be considered as a super palindrome these are the list of super palindromes which has to be considered for our output so there are four super palindromes within the range 4 to 1000 so that is going to be your output this seems to be a very easy logic like we can iterate from the range starting from left index to right index and take each number and check whether it is a palindrome by passing on to a function is palindrome so if it returns true then we are going to check whether it's square is a palindrome that is 4 cross 4 is a palindrome and again five cross five it's a palindrome and so on till nine ninety nine is a palindrome or not so if it returns true then in that case we are going to increment the count and return the result so this logic seems to be so simple so if we code it the same way we considered that is for every possible number we are checking whether it is palindrome and it is square is palindrome or not if it returns true then we are going to update our result and finally return the result but this solution is time limit exceeded because the range of the string given here is 18 that is the length of the string is 18 and if we are trying to convert this to number then the range will become 10 power 18 which is what is making this problem hard so how are we going to approach this here as we know the range of our palindromes are going to be 1 to 10 power 8 we have two options to approach this problem the first option is check all palindromes and its squares whether they are palindrome or not if they are then increment the count and return the result that is what the solution we have seen and it time limit exceeded so how to approach this in an optimized way is create the palindrome ourselves and check whether they are squares also palindrome or not so what is creating fallen rooms are how do we create balance so if you consider a string or a number as palindrome they can either be an even length palindrome or odd length palindrome so for example here in this case any palindrome is going to be repeating its reverse so 1 2 is going to be repeated in reverse that is 1 2 so we are going to start from the number 1 and append its reverse to form palindrome for example 1 and 2 3 and so on same way if the number is 1 2 and we are going to create its reverse 2 1 till some range same way if it is odd length palindrome we are going to put a middle number starting from 0 to 9 between for example if 1 and 1 is reversed then we are going to append a middle number 1 0 1 2 1 three one so on to form odd length palindromes so we are going to construct the strings and its reverse in order to form even an odd link file in rooms and once we form the palindrome within the range we are going to check whether its square is also a palindrome in that case we are going to increment a result and return the result so here comes the range problem again up till what range we need to create this palindrome so here for our given range they have said the overall maximum length is going to be 10 power 18. if the squares are going to be in the range 10 power 18 then the actual numbers that the square root of those numbers are going to be in the range 10 power 9 so in our problem we are going to generate these numbers and check its squares are also palindrome if they are also palindrome then in that case we are going to increment our result so if the squares and the actual number are in the range 10 power 9 we are going to generate only half of the numbers and append the reverse in that case the number we are going to generate will be of range 10 power 5 so we are going to generate all possible numbers from the range 1 to 10 power 5 and with each number we are going to append its reverse for example if it is 1 5 we are going to append its reverse pi 1 to the number and once the number is generated it is obviously apparent row because we are generating it and we are going to find its square so that we gonna check whether its square is a palindrome or not if its square is also a palindrome then we are going to add that to our result so hope you understood the solution let's go to the code now so let me get back to the actual code so yes as the ranges isn't long we are going to have two variables long l is equal to result is going to count the number of super palindromes and finally return the result so first let us declare a list which is going to hold all the palindromic numbers so here this list is going to have all created palindromes so now we are going to add all single digit numbers because each single digit number is an individual palindrome now we are going to generate all even and odd length palindromes for that we are going to have our range starting from 1 to 10 power 5 inside that we are going to have our left part we converting that number to a string and right what right part would be the reverse of that string so yes now we have both left as well as right path so first we are going to add the even length palindromes for that i'm gonna add in my list left part plus right part so this will add all possible even length palindromes now time to add or length for that we are going to iterate through all our digits starting from 0 till nine so in the same thing we are going to append our j in between so that we could generate all odd length palindromes now our palindromes are generated within the range 1 to 10 power 5 so now we are going to check its squares so let us iterate our list and n is equal to its square so now n is having the square we are going to check whether it is within the range and n is greater than or equal to l and n is less than or equal to r and if it is a palindrome then we are going to iterate our result so yes this is it we have created our palindromes and we are checking whether its square is within the range and it is a palindrome or as well then we are going to iterate a result so we have to write our is palindrome function since we are passing this as a string we are going to have two pointers left and right and they are going to compare the characters at each end so yes this is done let's run and try let's submit yes a solution is accepted so thanks for watching the video if you like the video hit like subscribe and let me know in comments thank you
|
Super Palindromes
|
walking-robot-simulation
|
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`.
| null |
Array,Simulation
|
Medium
|
2178
|
284 |
everyone welcome to my channel so in this video i'm going to try to uh solve this problem do some left coding work at the same time i'm going to try to follow the general interview steps while trying to solve this problem so first of all let's read through this question and get a good understanding about it so design an iterator that supports a peak operation on a list in addition to the house next and next operation so implement the peaking iterator class we have the constructor what parameter is the input array initialize the object with the given input array nums but actually the given interface here is by passing an iterator so i think this question needs to be updated a bit then uh but it doesn't matter much let's say the next one is next returns the next element in the array and moves the pointer to the next element and the third one is has knight returns true if there is there are still elements in the array so peak returns the next element in the array without moving the pointer so this is a constraint uh so we have the input rate lines anywhere between one two or a thousand numbers are between one to a thousand as well so all the cost index and peak are valid and uh this is like the limitation about the next high snacks and peak so having said that um let's see how to solve this problem so this one i don't think there's too much of the room thing to think about algorithm but uh essentially what we are going to do is we are going to keep the iterator and the next integer so that's pretty much about the idea so not focusing on like the runtime space analysis uh because uh it's very uh it's like uh very trivial to do this kind of thing so but i do uh i'll define the private uh members as iterator of the integer operator and as i said i will go i'm going to have like an integer of next uh so the next is actually used by pick uh here so we call iterator so when we call the constructor we are going to have this dot either as either and if the entire down next is uh if eternal has next then we have next as equal to 83.next we have next as equal to 83.next we have next as equal to 83.next so that's pretty much it and when we call the hassnext next we just return um next not equal to a none pointer and you need to have the next house not here so when we call peak um we actually so return the next element in the iteration results once in the iterator so we are not advancing the iterator instead we are just returning the next so it doesn't say if next is none well we should return so i would just assume if it's none let me just return that so for next uh this one what we would do is uh we will proceed the iterator and also we will need to okay so i need to check the behavior originally so it's like here it's like uh next so if there's no elements then we are going to return this one which is called no such element exception so i'll just copy it here if um next is equal to another pointer then we are just going to throw uh the this kind of exception and then if it's not equal to none then we are going to have like a tamp integer that's equal to next because this is the thing you're going to return time here and in the middle uh it's going to be something like uh next is equal to oh so the thing is we still need to see whether we actually have something so if the ether dot has next then what we could do is we have either dot sorry next is equal to waiter dot next otherwise we have next as a num pointer so that's i think that's pretty much it uh let's see if he can run it please call throw no such elements exception uh so what is this one so no such uh so this one is something like you're going to import it i guess so you're going to import this select has next a3 dot has that says uh ater has next why uh let's see either dots has next to return 12 volts so if a3 dots has next then we are going to so draw none pointer exception here uh oh okay so this is called iterator sorry um uh iterator let's say this dot either this either all right so now we have fixed most of the things uh let's do some submission okay so i think that's pretty much it for this question uh if you have any question regarding this piece of code and uh or this uh this the solution feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
|
Peeking Iterator
|
peeking-iterator
|
Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations.
Implement the `PeekingIterator` class:
* `PeekingIterator(Iterator nums)` Initializes the object with the given integer iterator `iterator`.
* `int next()` Returns the next element in the array and moves the pointer to the next element.
* `boolean hasNext()` Returns `true` if there are still elements in the array.
* `int peek()` Returns the next element in the array **without** moving the pointer.
**Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions.
**Example 1:**
**Input**
\[ "PeekingIterator ", "next ", "peek ", "next ", "next ", "hasNext "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 2, 2, 3, false\]
**Explanation**
PeekingIterator peekingIterator = new PeekingIterator(\[1, 2, 3\]); // \[**1**,2,3\]
peekingIterator.next(); // return 1, the pointer moves to the next element \[1,**2**,3\].
peekingIterator.peek(); // return 2, the pointer does not move \[1,**2**,3\].
peekingIterator.next(); // return 2, the pointer moves to the next element \[1,2,**3**\]
peekingIterator.next(); // return 3, the pointer moves to the next element \[1,2,3\]
peekingIterator.hasNext(); // return False
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000`
* All the calls to `next` and `peek` are valid.
* At most `1000` calls will be made to `next`, `hasNext`, and `peek`.
**Follow up:** How would you extend your design to be generic and work with all types, not just integer?
|
Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code.
|
Array,Design,Iterator
|
Medium
|
173,251,281
|
1,696 |
hey everybody this is larry just me going with q3 of the weekly contest 220 on neat code jump game six uh hit the like button hit the subscribe button join me on lead code let me know what you think about this problem uh okay so during the so i stopped this problem during the contest i'm going over my thought process i feel free to kind of you know and as well as the solution obviously but during the contest i kind of recognized this problem uh and actually is one of my weak points of the jump game series i know that's some sort of greedy but i still have to kind of figure out how to read right um so for this one the tricky thing is um for me looking backwards or forwards um and as i was solving this problem during the contest i did just that i go okay can i look forward it's the way to go you know uh go k elements to the right and then you know do some kind of weird math or whatever and then figure out the best score right and the answer is yes maybe so this is actually um a dynamic programming problem or not this problem but uh just solu this proposed solution is a dynamic programming solution where you have a dynamic uh you know for each k you know you get the minimum score for a dag you know or max score on a dag or something like that longest path on the dag even though there's negative numbers but that's still okay because it's a tag um so however and i'm not gonna go with that too deeply because uh there's a lot of overlap with other problems and maybe if you do want to go over that um maybe check out other jump game earlier jump game videos but so i'm going to assume that you know that solution uh and the short answer that is that it's going to be too slow because if you do that dynamic programming it's going to be of n times k unfortunately if you look at constraint n is 10 to the fifth and also k is 10 to the fifth which is basically 10 to fifth square which is way too slow uh so then immediately so i was hoping a little bit and i look at the constraint i go okay well that's not going to be good enough let's kind of look for something that's similar to the other jumpmans to be honest and this is where practice comes in um you know some kind of looking greedy solution looking for it um i struggled that for a couple of minutes i couldn't figure out anything so then i start mentally thinking about okay you know so there's two ways to think about this right which is that at each cell uh each jump each index uh we can jump forward one two right um and you know and we'll figure out which one to jump on but another way to think about it which is similar to the dynamic programming because you can also do it in both directions as well which is that okay for each cell in the middle say um what is the best way to get there um meaning what is the max score coming to the cell right uh so and then another way to ask that is that okay for k is equal to two and this negative two well it doesn't even matter which the cell score is because you just added no matter what uh which is that on the left k elements what is the max element and for me once i am able to phrase the problem in terms of this question uh if render light bulb ring the light bulb that's not the right phrase right ring the bell or the light bulb whichever proverb you prefer um it's not given a problem but just saying but anyway yeah so now for each element you get the max element to the left side and what does this mean right um well i actually have a video describing mono queue and how to solve mono cues uh problem and to be honest the first half of that uh the two-part the first half of that uh the two-part the first half of that uh the two-part video and the first video doesn't even talk about mono queue it just talks about the invariant and the problem solving and how you solve this form the mono cube part or the monotonic part of that queue allows you to get it in linear time which is not necessary for this problem for me so i didn't solve it this way but looking back i could have solved it this way but again during contest speed i'm trying to solve it as fast as possible right and for me like it's not worth thinking over you know to optimize login unless i have to and i didn't have to so i'll go over that a little bit but that's basically the idea um and the monotonic part um is an emerging um property of the fact that you have basically essentially like a sliding window of sorts again you know i know that this is similar to q2 in that regards you have a sliding window max uh of the last k elements right so that's basically is that you know from negative two you go to four well we just shift from negative one to negative two and then from that um you could do a max q of length two and that's basically all you're looking for right and that would solve your problem exactly um so i'm not going to describe in this video that much about how to do that proof and stuff only because i'll put a link below on the mono queue video and because this is basically a cookie cutter mono cube problem once you understand mono cube well enough so if you go over that video let me know you have any questions but once you understand that video and how to construct the problem and the solution in that way um you'll understand this problem so i don't want to repeat myself too much um but yeah but that being said i'll go over my solution which is not the monocule solution even though it has the exact same property except for the time complexity but for me during a contest it is a few of things to prove and to verify rather uh even though you know it's trivial but for me it's just um you know every second matters on the contest right and on this uh in this contest if you look at my rank i actually finished one second behind the person ahead of me so you know that's my excuse um and i end up did spend about five minutes for this farm even though i um even though i thought i struggled a little bit more on this one to be honest but uh but yeah but once you're able to phrase the question in a good way then that's how it did and i think my solution even though oh it doesn't have to monocular and it doesn't it's not linear time as a result um i think it's more intuitive um to see and that's why i'm going to explain it so basically this is my code first n is equal to length of nums which is what it is uh i call this dp but it's really you could call it dp if you like but basically this just gives me the best score for a given cell um so that you know like when i'm at negative six um you know this is the best score including the negative six up to this point to get to negative six right so the so for example um yeah in this place the best score to get here is gonna be one here it's going to be uh negative four presumably starting from one this is going to be negative 19. i this is so weird because you're also coming from one where four is going to go from negative four which is so the best score is going to be zero and so forth right so that's basically what my dp dps and instead of using some sort of model q i keep a sorted list in c plus or java i think there's a multiset or something like that you can use properly and so that you can get the mineral element out or in this case the max element of that so basically that's what i did i go okay um so this is actually the most of the work on this problem even though it looks really simple as an if statement basically is the first element well then you just you know there's no prior element right you just take the first element um from the list and that's your score you know that's pretty straightforward otherwise your current score is just going to be this thing which gets you the max score of the window that we were talking about and we just care about window of size k and yeah and then this is also just the cell that we're stepping on so this is now the max the previous max score that of the k steps that we could be coming from plus the current score so this is now the best score right because you have to start at uh array zero so okay after that we set dp index as you go to best this is just for us to keep track of so that we can remove it later uh and then we add it to the list after we you know because this is now so we want to add it to the list so that the next element can use this element to jump from um and then here is if um if now this is just going if and maybe another way to write this is an alternate way is if length of s of list is greater than k then we remove this element these two are equivalent uh though this is what i wrote during the contest um they both just you could kind of um show why these are the same but basically this is okay now the sorted list has more than k elements so we have to shrink it by one element so that it remains k element uh so that's basically what i did and this is also why we have to keep track of the previous um scores so that we can remove it from the list when we're ready and that's pretty much it so once you do it for every element every array then now we just return it for the last element which is where you want to land and that's going to give you your score so let's go over complexity right uh for the sake of argument uh let's just say sorted list is log n i know that there's some new ones in that but let's just say it's login uh and nc plus and java these are gonna be login libraries so from that for every element in the array we have you know we do one add and maybe one we move so it's going to be log n number of operations and we've for so each loop takes log n time you have n of them it takes n log n time in total um yeah in terms of space this is going to be linear this is already linear so linear space uh and login time again if you really pay attention to this can be implemented uh as a mono cue so if you already have a mono queue um uh library you can actually even plug this in and call it i don't have one ready and i only like writing during the contest so i you know yeah let's say you have this right or max q maybe that's a better name i like that name better um if you have something like this code actually doesn't change so uh so this is that's the power of abstract adt or abstract att abstract data type and in this case if you have a max q uh you're gonna have linear time and linear space and again i'll put a link to the model q video below um and yeah uh that's all i have for this problem you can watch me solve it during the contest and just thinking through it a little bit uh let me know what you think now you know tata okay oh two people refinish people really fast okay sum of order that's hard baby don't remember how to do this it's one so basically we want the previous pass from here this is one and then we carry it okay so here we look at the last two elements here we so we get the max on the left is that right okay something like that yeah a little bit weird but it's what it continues okay so no that's not what we want to do i'm going to do is get the previous sliding window so here so tp index is equal to the max of sorted list so that's list of negative one let's just grab this numbers of index okay if index is equal to zero then plus is equal to just a number x minus k okay uh hey thanks for uh watching this video explaining the problem uh let me know what you think ask questions because then i can answer them preemptively or join the discord uh hit the like button the subscribe button as well that works and hopefully i'll see you again bye
|
Jump Game VI
|
strange-printer-ii
|
You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.
You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.
Return _the **maximum score** you can get_.
**Example 1:**
**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.
**Example 2:**
**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.
**Example 3:**
**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0
**Constraints:**
* `1 <= nums.length, k <= 105`
* `-104 <= nums[i] <= 104`
|
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
|
Array,Graph,Topological Sort,Matrix
|
Hard
|
664
|
319 |
Hello friends today I'm going to solve liquid problem number 319 bulb switcher in this problem we are given n pulps all of them are initially off and now in our first round we turn all the bulbs on and then in second round we turn off every single pulp and then in third round we toggle every third bulb and then in the eighth Round We toggle every eight bulb so finally in the end round we'll just toggle the last ball and we return the total number of balls that are turned on after n number of rounds so here we are given an example so in the first initially all of them are off in the first round we turn all of these on okay in the second round now we turn off the second Bob well basically we are toggling um this all the second bulb so now here since this is the second bulb it's on so we turn it off and then there is no other like the second bulb to this right so in the that's all about second round the third round we toggle the third bolt so the third bulb is this one which is which was on in second round so we turn it off in the third round so since we had three number of bulbs and we did all the three rounds so after that three rounds the number of bulbs that are turned on is equals to one right so that is our output here so uh this is the example for this problem now how could we solve this problem where we could approach this problem using mathematical um approach we should solve this in a constant time complexity this problem could be solved by using um like iterative approach but that would be of n Square time complexity so we are going to use the mathematical one that is constant time complexity so let's take some Bobs all right so we have a bulb one two three and four five six okay so we are just going to take six pops here now all of these are initially off okay so all of these are off um I'll represent off with a zero and on with the one so since all of these are zero these are all off now in our first round we are going to toggle all of these ball right uh so we toggle every first bulb so this is our first ball we toggle it so it's now turned on WE toggle this one so it's now turned on so basically in the first round we are just turning on all the bulbs because all of them are off now next in our second round um we are toggling all the second pops right so that means this would stay on this is the second bulb it will turn off and then this would stay on the second or this will turn off now again this would stay on and this would turn off right now in our third round we are going to toggle the third ball so this is the first bulb second bulb and this is the third bulb so we toggle this now this is the first one after third we just initial like begin our count again so this is the first one this is the second one and this is the third one so we toggle this right so we toggle this to bulb now the number of bulbs remaining on is to write in this case now let's move to our fourth round in fourth round we are just toggling the fourth bulb so all of the these will remain same the fourth ball will only be toggled so it is equals to one and these will be equals to one and one that is they are the same now in our fifth round we toggle the fifth pull-up so basically we toggle the fifth pull-up so basically we toggle the fifth pull-up so basically uh all the first four bulbs will remain as it is and the fifth bulb will change so this will be equals to zero and this one won't change now our sixth round only the sixth ball will change so all the other bulbs will remain the same the last one which is the sixth one will change right so this will change to zero so basically here all of these are the same except this one because this only this change right and so on so while we are toggling here uh the number of pulps that's turned on at the end is equals to 2 right so now let's see in our first round we toggled all of them on so there were one um for each that is each of the bulbs were toggled so every ball would toggle right so we switched all um once so uh operation was performed once on all of them in the second round we performed operations on only these one right so that meant that um the first bulb was toggled only once and then in these many rounds these were all toggled twice in the third round these two remain the same only these were toggled right in the fourth round the three of them remain the same as you could see here only three of these were total like not all of these were toggled but right the fourth starting from the fourth right so um in the fifth round we performed toggle we didn't change any of these in the sixth round only this was toggled so how many times was six toggled let's check so it was toggled once twice and then from here Thrice right so six was toggled three times how many times was five toggled it was toggled from um okay so this is actually Four because if we count from the round initial state to round one so that will be close to four and then for this case as well so we told once and then remain the same and then we are going toggle so two eyes so we toggle this twice only two times and now let's see this so we toggled it once and twice and then remain same three times so it was toggled three times and this was toggled once and then twice and then it was only toggled twice and this was also toggled twice and this was toggled only once right so um the number of toggles that are odd R1 for bulb one and for bolt number four this is the pot number four and this is the bulb number one so only these two were toggled um odd number of times so what happens if you toggle it odd number of times where it will remain turned on at the end right if you see like we are turning it on from an off State so from off to on it is one uh one toggle and it's turning it on right so for similarly for this it's three times which means that from off we are turning it on and then we turned it off again and then we turn it on again so at the last round it's on so only those um bulbs which were toggled odd number of times will be uh turned on at the end of the round all the rounds right so uh which are those one and four if we look at this carefully where more number of pulps then you would actually see that only those bulbs which are a square um which are perfect square are turned on so if they were uh like uh 15 bulbs then all the poles which are perfect square so what are perfect square one is a perfect square four is a perfect square nine is a perfect square and 16 is a perfect square 25 is a perfect square and so on so if you had 15 bulbs then Bob number one four and nine would be turned on at the end so that means there will be three bulbs that will be turned on all right so the result would actually be the total number of Pops 15 a square root of this value Y at the square root of 15 is equals to three point sum value right some value because we know square root of 16 is equals to 4 square root of 9 is equals to 3 so square root of 15 which lies between 9 and 16 is equals to 3 point something but we are taking just a floor value so we will actually get the value 3 which is the number of bulbs that will be remained on right so that is um our formula so our formula is just one line it's just the concept that we need to understand which takes time but the formula is just a single line that is we are just going to take this floor value of the square root of the total number of Pops that's it so let's just code our result very quick so that would be the floor of the square root of n that's it now let's run our code and see if it works fine awesome this works very real well let's submit this great so this was just an off one time complexity solution I also tried an iterative solution which is of N squared but I got a runtime error for this solution so you could just come and check my solution but yeah this one is of one time complexity solution hope you liked my solution let me know in the comments down below thank you
|
Bulb Switcher
|
bulb-switcher
|
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb.
Return _the number of bulbs that are on after `n` rounds_.
**Example 1:**
**Input:** n = 3
**Output:** 1
**Explanation:** At first, the three bulbs are \[off, off, off\].
After the first round, the three bulbs are \[on, on, on\].
After the second round, the three bulbs are \[on, off, on\].
After the third round, the three bulbs are \[on, off, off\].
So you should return 1 because there is only one bulb is on.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `0 <= n <= 109`
| null |
Math,Brainteaser
|
Medium
|
672,1037,1491
|
1,489 |
hey everybody this is Larry this is day 19. of the legal daily challenge what is this early access stuff I don't want to try it uh hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm uh 1489 find critical and pseudo critical edges in minimum spanning tree uh it's a hard problem so hopefully uh we'll get through it I've been having you know some struggles lately as people who's been watching my channel now uh so yeah I hope everyone's having a great weekend great day and everybody all your stuff man these days go by fast I need to kind of do more of my days but um all right let's get to it shall we all right so let's say we have uh or given I don't know if I'm reading it like this given a weighted and directed connected graph of Android disease from zero to n minus one what does this one mean I and weight oh it because it's an edgeless I see uh it's a way we're phrasing it but uh oh I guess is it because you can have the same oh no it's distinct it's a really weird way of drawing it maybe like the edges are I don't know maybe it's fine all right so find a critical and pseudo-critical edges in The and pseudo-critical edges in The and pseudo-critical edges in The Grooming Graphics what's a critical graph uh okay an MST Cruise deletion from gravity cost MST rate to increase it's called critical graph on the other hand a pseudo critical Edge is that which what is that which can appear in some msts for not at all note that you can return the indexes of the edges in any order uh okay I guess the index is used for returning which okay that's fine um wait is it what oh yeah okay no the input is fine I've been destroying this okay I guess that makes sense in the context in the output okay uh all right let me reread this okay so critical Edge is um okay so that means that I think the first thing I would try to do is kind of rephrase the problems in the way that I can understand it and to be honest right now I'm not you know I mean MST a minimum spanning tree is something that comes up a bit in uh algorithmic courses but to be honest like they come up here and there but not super often um even on lead code right or competitive um but they do come up enough that it is one of the fundamental things that people you know I think the reason why it just doesn't come up that much is not because it's not uh as interesting or critical as other things critical yeah as other things but it's just that there are not that many variations on things you can ask about and MST a minimum spanning tree um like maybe an hour of this is true but this is just a hypothesis it's just that um they're not that many variations of the prompt that you can ask is maybe what I would say uh but you know that aside um I think it's just me trying to say that like you know it's still important ish to know at some point or it's on some level but uh but it doesn't come up super often relatively um but the thing about MST uh I would say is that it is one of those kind of nautical greedy problems in which you know it is one of those things that you can build greedy um uh explanation but really proves uh firm so it definitely is one of those things that is good to learn if to just kind of get yourself into understanding why greedy is greedy um especially when you're starting out okay that being said okay so what happened so what is a critical Edge right so critical Edge is when you remove it the MST increase and that only happens when is that true because I was going to say something but I had to make sure that it is true uh when you remove an edge um sorry so given that MST if you remove that edge the MST rate increases right so let's say you already calculate the mrst and then you remove it how do you replace um then the only way that it doesn't improve if you will or not that it improves because it can't improve by definition MST you already have the uh the optimal tree um so the only way it doesn't uh increase so it stays the same is if uh I think I have to draw stuff here I think I've been trying to use a lot of vocabulary so give me a second let me take out my drawing pad make sure I put on screen I don't know if y'all know this but when I'm at home and not traveling I have like one of these drawing things I still don't make good use of them but you know at least I'm trying uh yeah okay so I think the idea here is that okay right you know let's say we have some you know notes in MST right and it's going to look something like you know whatever right you know I'm just gonna draw about it so right let's say this is MST and let's say this is the node that you're caring about right uh and um actually let me change my mind let's say this is the note that you care about right and that's I know that multiple things so let's say you remove uh you don't care about the node you care about the edge man I'm really not explaining this as well but let's say you're looking at this Edge right so what happens when you remove this Edge well when you remove this Edge that means that now you have two disconnected or you have two connected components that are disconnected from each other that used to be together right so that means that now that the only way that this is uh this is a critical Edge if there does not exist an edge where you know like it connects the two connects connect connects like English is hard connects to the two components because yeah basically you have this component now and then you have this component now right Mr dupus and then now that you have to try to find an other Edge that is either the same way if it's the same way then it is not critical and it was um if you cannot find one of the same weight then what was the other one again pseudo critical um I ordered I decided yeah I just focus on critical for now so that's the case right so okay so that's basically the idea that I'm thinking about but I have to think what uh okay so that's like a concept right but I don't know what to do with this yet is what I'm saying hmm because you get uh actually let me take a look at n always look at the constraints okay and it's actually only a hundred and actually only there are 200 edges that frees me up a little bit more because I to be honest I was thinking about I was constraining myself to um linear Solutions um but ofv Solutions uh um you know something like this uh but now we can definitely be a little bit more loose because n is only a hundred right we can even have n Cube uh Solutions if we can and the other thing is rate is less than a thousand down if that helps but and edges is only 200 so even if I don't know we have to figure out how to put all these things together but these are good observations and that allow us to be more Brute Force than that I mean that's not to say pure naive before us but allow us to be a little bit you know uh yeah because now we can say well I mean in theory even we can actually even calculate the edge right because we calculate so okay so let's see what actually let me yeah let me just calculate what is the most Brute Force thing we can do right the most first thing that we can do is that you know we have a Yi we have e edges oops caps lock e edges right and then for E for each Edge calculate new MST would that be fast enough well this one is all of G iterations and cutlate new MST lazily you know we can do you like which is going to be fast enough right because this is just at most e-square because this is just at most e-square because this is just at most e-square like e um and I'm just using Costco I mean you know you could also do the prims which is again yeah I guess so I guess Prim is now let's see for each one your update and then you get them in so that's re-square then you get them in so that's re-square then you get them in so that's re-square right so it's either you or we Square for prims um eulogy is from sorting The Edge edges from Cusco classical Cusco I don't know Cusco but in either case even right this is gonna be really like uh time C this is of course up to at most 200 so that's you know 40 000 times like for 200 which is what another Which is less than 10 right because 2 to the 10 is uh one thousand I know it's 10 24 but you know it's roughly a thousand so yeah so this is less than 10 so that should be even fast enough uh you know just back up the envelope right uh yeah and this is times 100 which is actually a little bit slower but and you know still fast ish oh no I did e-square I did e-square I did e-square um so this is actually you know so I mean it's not fast but it's not slow like this would probably be good enough if we just did naive for the critical and that type of thing and yeah I kind of Miss well I did not read the uh then with the constraints fat early enough so I think I would get I would do this for the critical Edge what is the um because that is easy to do but let's see what is a pseudo critical Edge uh let me reread it now that I think I have at least something knowing the constraints right uh pseudo Could It Go Edge it is which it can appear in some MST but not all what does that mean that's crazy I mean it just means that if you remove the edge it does not change the um change the MST right yeah I mean I think that's it but the poem I think in theory we have to do this twice maybe unless we're doing it lazily um because basically we have to uh see if this Edge is in the MST and the problem with trying to and this one I don't know if you can do it you know I think the naive my first thought the amount of is that naive is to you know calculate the MST and then for each Edge in the MST which now reduce this overd thing to or B thing um but then but that's not always true right because this MST doesn't have to be unique right and because this thing doesn't have to be unique I don't know how to you know versus just for each Edge um I mean this is still fast enough but it is not as fast as I would like I suppose right basically we're calculating two msts for each Edge and one MSD so that's like yeah that's a lot of msts we could save time on the Sorting but that doesn't change anything with it's not gonna be fine I think I'm still trying to think a little bit whether that is fast enough um yeah I mean okay let's give it a go I think the math makes sense I don't know if there's like a Slicker algorithm at least off my head um if we need it and then we'll see if we can optimize some parts of it but for now we'll just do it that way then yeah okay so I'm going to try to use I'm not going to go over all the um uh um what I was gonna say I'm gonna go over the minimum spanning true algorithm though it is uh like I said a very good algorithm to kind of read up and make sure you really understand but at the core of it is greedy and I don't know that I would say I remember it other uh other than remembering that is greedy and because it because of that because um because I do know that is greedy the implementation is actually wave straightforward to redrive right like I don't have I don't memorize temperature code or whatever it's just that I know the thing to know is just that you solder the edges by the weight and then just go add them one by one until you have a full graph okay so yeah um let's just say we have a MST algorithm um what am I doing footage MST I'm trying to figure out how to generalize these things in a good way without like creating the entire graph again obviously this is what why I'm trying to keep thinking a little bit uh but clearly you know we have to do it in some ways so basically okay so we have to let's just say we have some index for the edge um and then we have to calculate two msts one assuming that this Edge is in MST and then calculated and then calculate and if that's true then calculate whether the new um and then calculate MST without it right so this one I guess we just we can do something like uh use let's use a code word keyword yeah okay basically we always skip index and then we just see if we start with using this right so okay so maybe I just call it store it then um okay and this assumes that we already sorted the edges because I guess we have to go in this case anyway um okay yeah let me just remove this so I could have more realistic uh what am I doing again okay oh yes sorting sorry so yeah let's just say the edges you got to sort it um we have to keep track of the index right because that's where we're returning okay yeah um edges so we want to sort this by what we sorting by we want to sort it by what is the weight is the third thing uh but this is now so it's X of one of three maybe yeah or two oops one because of the enumerate so that we get the index in this as well so yeah um okay and here we do you know for uh we do need a much more quiet what do we need um a union fine is what I was gonna say hey I'm a little bit slow and off today but yeah um also I'm not gonna go over uniform but I actually okay fine uh yeah I guess I'll put this in a class to make it slightly easier so we have and then we have find and this is just standard Union fine things I'm not gonna go over it in this video because uh I don't know that could be a big thing in itself so uh but yeah what and then okay so then now we uh we have n items right let's put this big hand all right and then if start so if this is true then we add um what do we do then uh studies start Weight I suppose is equal to edges of index and then you find dot Union s u s v that's the total rate we assume that they're not connected because this is the first Edge right otherwise so we always skip index because either we use it to start or we don't use it at all so then here for index u v w and edges right if this index is terrible but uh um current index maybe that's slightly better I don't know let me fix this heart but if index is equal to current index then we continue we skip this no matter what otherwise if at the fine of U is not equal you have to find and if we Union them and I guess we can also early terminate but um let's do it if count is equal to n minus 1 then we break and then we just return total I think this is roughly right from MST and is it Union fine and yeah okay now we just have to do it for every Edge as we said so yeah for I actually have a big G I suppose here's a good length of edges before I in range of E um uh yeah I think um what do I need first actually I need to do the standard minimum spanning tree so let's just say Bass MST is equal to MST of a current index to the true and force we're not skipping anything should be fine or we don't start with and we don't skip anything I think that should be fine hopefully it's as if it's not that'll be a little bit sad otherwise uh yeah so if MST of hi uh let's say we start this if this is you go to base MST that means that this Edge is part of at least one MST then and then it is at least pseudo critical if MST of I force is not decode to base MST then this is critical right let's actually also put the answer so critical basically so if this is not that means that this is critical uh and then we get a pen I if it is the same then it is pseudo critical because it's apparently uh yeah it doesn't have to be in the thing and I think that's it ah I think that's it maybe that is my understanding of it hopefully uh is that true oh this is G not edges I make that mistake actually comment so that's a little bit unfortunate uh oh yeah I always call it you fine because sometimes I do it in line uh okay am I confident about this enough to submit I mean because that was the first test other than I guess I have some you know typo about the name but so is that good enough for me to submit uh all right let's just YOLO let's see yeah that was good very slow what did I do three years ago that was fast I got a wrong answer was that doing a contest probably uh oh I did it another way last time maybe well yeah wow I mean I did it much faster that time I mean this is good it is very slow oh no it's 60 but apparently I did it like really ridiculously last time uh but yeah the compressor let me just go over this complexity first and then maybe I'll take a look at my previous code as we said this is the algorithm that we did so and we did the you lucky one so this is going to be all of these uh yeah for each year we do another u-log user use uh use e Square another u-log user use uh use e Square another u-log user use uh use e Square log e um keeping in mind that you know years constrained in this way and that is your time uh of course space is going to be over me for uh you know a copy of the sorted away and yeah distorted away a lot of Union fine stuff uh you can find stuff which is linear uh on N so this is actually really space at least uh I guess that technically if you want to be precise that's the time because you have to you know well for the time uh just I mean this is all of we no matter what because you have to at least spend the time to allocate the space right but uh I think the thing that I noticed last time and I did notice this here was that the rates are up to a thousand but I didn't really oh I didn't get to the point where I was thinking about it but it seems like here in the past I did do something like this uh psycho man it seems like I'm doing some really complicated things here there is something about you uh Union fine so I don't remember what I did here my guess is that um we're doing Cusco all together um based on the weight because and this is just like a counting sword I don't know why I did it this way but um but it's fine maybe yeah I mean this is just a counting sword this is a weird way of putting it but it seems like I did do something smarter because you can think about this as all of you anyway in terms of edge and I don't know this gets psychos too past Larry has some funky crazy things oh this is um hmm I mean this is a cycle counting bag edges I guess the idea here is that man what is past Larry is ridiculous but okay so basically this means that the minimum spanning tree changed um and when we're done and we'd have to consider all the edges and basically the idea here is that when you process all the edges at the same time all the edges of the same rate at the same time um then the thing is okay you every step of the way you try to figure out all together whether that causes a new MST and if it if a new MST emerges now then what that means is that all the edges together but they're only two kinds right that means that all the edges that we process this step are important in that those edges are the step or those edges are the edges that we that are in the answer right and those edges are either uh critical or pseudo-critical or pseudo-critical or pseudo-critical because in those cases um yeah in those cases they're either critical or pseudo critical um because by definition it means that all the that is an interesting observation is that all the critical and pseudo-critical edges all have the same pseudo-critical edges all have the same pseudo-critical edges all have the same rate because there's only one instincts in instance instant yeah one instant in time in which everything becomes a becomes connected and then the only they're only a couple of cases I guess huh man past Larry current Larry is not as smart maybe but um okay and these variable names oh these are the edge weights of the current Edge rate right what is p oh I think I just keep oh I see wow this past Larry is writing some really dubious looking code but basically what he was doing is he's keeping track of two trees and then basically just checking to see if this is done then it's just finding looking up on the previous tree and whether this Edge was processed or this actually created uh what was needed because this is the previous tree and then we're doing comparisons and if they're not the same then we well we just have to consider them um and then for these edges we try to determine if there's a cycle in just those edges and then if which determines all these things the recyclers finish matter I don't even know what I do here I guess I do let's see get psychos oh I say yeah so basically we're looking at the back edges and seeing whether if there's a uh if there's a back Edge we should consider it wow but basically it just gets all the edges that are part of a cycle also ridiculous code don't know if I can do it right today uh yeah so if it is part of a cycle then it has to exist because they oh I don't know if I understand this one task lab is meticulous this is actually a ridiculous code uh let's take a look at editorial then I mean this is basically what I did right uh yeah this is what I did I guess wait why is it only we Square did I messed up okay my sweetness oh I want you here I am one of the complexity my bad um because this is over this is actually now all of you because we already did the Sorting that's why oh yeah man I think I was just focused on the other thing and I got distracted my four friends uh but yeah because of because we already did the Sorting so um for you so we can do all this so yeah so this is all of D not risk I mean I guess v-square is technical also mean I guess v-square is technical also mean I guess v-square is technical also true but we because of this is actually only e-square um I mean technically plus you'd like you if you want to add it back in for the Sorting for initial sorting but we don't have to sort every time we removed an edge this which is why you're able to get rid of it I forgot about that actually uh whoops yeah I mean they don't even go with my other solution I suppose uh which is because it's ridiculously complicated in the way that I did it uh yeah everyone seems to do it that way and not with the cycle calculating uh way hmm I'm gonna go watch my own video and see what I did here because this is actually I mean and you can see that um I mean you can see that this is much faster I don't know if it's still true or just like a sample case thing but I mean the reason why it is faster is just because it doesn't have I mean there is this sorting on the edges kind of um yeah I guess it's actually certainly well not strictly but it's probably on average faster than distorting but um but basically we don't want the weights together and everything is like the psycho finding is linear so it didn't mean that this is e and this is V times e at most versus e Square which maybe for a certain input is much better um I don't know anyway that's all I have for today let me know what you think I have to go for a jog and then food so yeah stay good stay healthy to get mental health I'll see y'all later and take care bye
|
Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
|
pizza-with-3n-slices
|
Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**.
|
By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it.
|
Array,Dynamic Programming,Greedy,Heap (Priority Queue)
|
Hard
| null |
189 |
hello everyone so today we will be solving lead code problem 189 rotate array so we are given an integer array nums and we have to rotate the array to the right by K steps where K is non-negative so let's head over to our non-negative so let's head over to our non-negative so let's head over to our drawing explanation and see how we can code this we have to rotate the array to the right by K steps where K is non-negative so what we can do is first non-negative so what we can do is first non-negative so what we can do is first we will find the actual number of steps that is k equals to K modulo or length of the array and we do that we do the modulo operation just because suppose our k K value is greater than the length of the array so that is the reason why we find the modular operation and we find the actual number of steps that are to be taken so that is our first part now the second part is what we can do is we will just we will just reverse our array so when we will reverse our array it will look something like this 4 3 2 1 after that what we will do is we will reverse the part until okay so that would make it something like this five six seven four three two one then viewed reverse the other part so that would be five six seven one two three four so now we have got our array rotated to the right by k number of steps so let's move over to lead code and write the code for this we will first find our actual number of steps that needs to be taken so we will use our modular operator then we will reverse our array so that would be nums of minus 1 then we will reverse the array from K till end of the array and then we will reverse telke so that would be yeah so that would be it now let's run it yeah so our test cases got passed so yes this is how we would write our code for the rotation of our array so I'll see you in the next video thank you for watching
|
Rotate Array
|
rotate-array
|
Given an integer array `nums`, rotate the array to the right by `k` steps, where `k` is non-negative.
**Example 1:**
**Input:** nums = \[1,2,3,4,5,6,7\], k = 3
**Output:** \[5,6,7,1,2,3,4\]
**Explanation:**
rotate 1 steps to the right: \[7,1,2,3,4,5,6\]
rotate 2 steps to the right: \[6,7,1,2,3,4,5\]
rotate 3 steps to the right: \[5,6,7,1,2,3,4\]
**Example 2:**
**Input:** nums = \[-1,-100,3,99\], k = 2
**Output:** \[3,99,-1,-100\]
**Explanation:**
rotate 1 steps to the right: \[99,-1,-100,3\]
rotate 2 steps to the right: \[3,99,-1,-100\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
* `0 <= k <= 105`
**Follow up:**
* Try to come up with as many solutions as you can. There are at least **three** different ways to solve this problem.
* Could you do it in-place with `O(1)` extra space?
|
The easiest solution would use additional memory and that is perfectly fine. The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays. One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example. The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on cyclic-dependencies between elements.
|
Array,Math,Two Pointers
|
Medium
|
61,186
|
1,071 |
hello today I am solving lead code problem number one zero seven one greatest common divisor of strings um so now let's look at the question um for two strings s and t we say t divides as if and only if s can be represent s can be represented in some form of T that is T is conc concatenated with itself one or more times so for given two strings string 1 and string two we have to return the largest string X is that the string divides both string 1 and string two now let's look at the example uh we have a string one a b c and string two uh ABC so we have uh six character in first string and three characters in the second string so 6 is divisible by 3 so it is possible that the entire string s Street string 2 can divide string 1 so if we consider a b c to be a unit say a and if we if you want to represent the string 2 as a then what would be uh let me remove this one so if we are considering this to be a unit a then the string 1 becomes two a so that means we represented first string and some form of string two now let's look at the second example we have a b so we have four character here four characters and we have six characters in a string one so six is not exactly divisible by 4 so it is not possible that the entire string 2 can divide the string one so here um we compute the greatest common divisor of the two six and four which is two so uh now if we consider a b um a b to be a unit say a then we can represent string two as to a then similarly we can also represent string 1 as we have we'll have three a so we represented um both um this string 2 as 2A and the string one as three is so yes um so here the largest string would be uh a which means the a b now let's look at the third example um so we have uh Delete and code so first if we look at the first character so these do not match so it's clear that we don't have like string uh that could divide both the string one and string two so um so if the string can be divisible if a string can divide the another string so first thing that we need to look into is like so here we have um 2A and we have a so if we concatenate this together the first string with the second we will have the three a or if we concatenate the string two with string 1 which with a plus two a the result would be same similarly um here so if we add the string this uh the string one with string two um it would be by way and if we add the string 2 with string one again it would be uh five ways so to begin our solution so we must check whether it is possible to find out the largest string in the given to string or not okay now um we can begin our coding um so first thing we need to do is um like if the first string first character of a string does not match then we don't have um the largest string so string or dot character add zero um this is not equal to string two dot character add then we will return empty then second thing we need to look is that um so we need to check okay uh we don't have to do this because since we are returning here right away so okay if um so we need to check whether we can combine both string and the resulted string is same or not so um so now we need to compare string one plus string two dot equals string two with a string one or a knot so it is not equal then we can return empty so now so if this condition um does not match then we need to compute the greatest common divisor so let's okay all right let's do here um so now let's create a function that calculates the greatest common divisor okay so we're going to use the gleading algorithm here to compute greatest common divisor um so we will return if b equals to zero then we're going to return a otherwise we will recursively compute the greatest common divisor so okay so here um we will return um okay so after Computing the greatest common divisor we can just uh obtain the largest string using the substring method so substring will start from this start of the string and we have to compute the greatest common divisor between the length of first Ram the first string and length of us okay left off second string now let's see the result okay um okay now let's submit okay we're done
|
Greatest Common Divisor of Strings
|
binary-prefix-divisible-by-5
|
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters.
|
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
|
Array
|
Easy
| null |
915 |
hello friends in this video we are going to solve a problem where we have an array and we have to partition it into two halves so this is the left half this is the right half and the condition is that all the elements in the left half of this partition should be less than or equal to all the elements in the right hand side for example in this case uh this is the array the original array was three two one six five three we are not allowed to change the order so we have to just find the partition and it's given that you will always find a non-empty partition this is the non-empty partition this is the non-empty partition this is the condition that is given so you don't have to worry about some corner cases like if it's empty can it be empty or not so there will always be at least one element in the left side and right side so these are non-empty and right side so these are non-empty and right side so these are non-empty and the left side should also be the smallest as small as possible so for example this was the original array if we partition here are all the elements in the left side less than all the elements in the right side no you can see that right side had one and this is smaller than three so this will not work so we will extend it now we partition here now we have three and two so are all elements less no again 3 is more than 1 now we will try here now we have 3 2 1 on this side and 6 5 3 on other side now we see that 3 is less than all the elements less than or equal to 2 is less than or equal to all elements 1 is less than equal to r elements so this satisfies the condition so we have to just return the length of the left one that is 3. we cannot extend it further let's say if three was this side instead of here three was here in the original array then if we include this three also still it satisfies but still in that case also we would have taken just these three the goal is to find the smallest possible left partition with that condition now let's take a formal example so we have another example so again finding the partition we have to consider all the possibilities so first partition can be here because it is guaranteed that it will be non-empty non-empty non-empty so first second third and so on till here so what we are checking that all the elements so this is left half and this is right half this l and r i have multiple elements so all the elements here should be less than all elements in the right that means if the maximum in this part maximum in this l is less than all the elements should be less means maximum should also be less so this is true for all elements but if we pick the maximum and just compare the maximum and if maximum is less than equal to all the elements in r then all the smaller elements will also be smaller because the maximum itself is smaller than other elements have to be smaller and we are also interested in all the elements in the right side so if we find the minimum here in the right part and all the elements in this side or precisely if the maximum on this side is less than equal to the minimum on right hand side so let's say right hand side has 5 7 20 and this side has 1 0 1 2 3 so we are just picking the maximum if maximum is less than all of these all these smaller elements will be automatically similarly in this side we pick the minimum if the minimum itself is larger than the maximum on this side then the larger values on the side will also be larger because minimum itself is larger so in the right side we are interested in minimum in the left side we are interested in maximum so now we have to try all the possibilities so if we do some uh brute force let's start with a brute force so first we will try here and we have one here we will keep track of maximum so when we are iterating from left to right we can keep track of what is the maximum till here because whatever is the maximum till here this is the partition that will represent the whole group so we will keep the running maximum and compare that with all the elements on the right side so first iteration it will take n minus one time and minus and one elements are there next time we come here so we compare if this is more than maximum then update the maximum otherwise the earlier maximum will remain maximum again compare that with remaining n minus two elements and so on so it will be n square but just like we kept track of maximum from here to here can we keep track of minimum from this side other side of the array so in order to do that we can do the pre-processing so let's keep pre-processing so let's keep pre-processing so let's keep two arrays of the same size so let me rewrite 1 0 6 10 so from left side it should be maximum left to right and minimum will be from right to left so maximum till here is 1 maximum till this point is compare just this one with the existing previous maximum so one and one maximum is one till here it's one now if we come here we found a new maximum so maximum till here is six and if we come here further maximum till here is 10 similarly minimum we start from right minimum till this point is 10 itself and we will use these as the initialization condition also for maximum we can initialize the first index with one this will be the minimum and maximum we can initialize with last element the minimum sorry till here minimum is minimum of current element and the next element ten and six so minimum is six now we come here minimum of zero and six is zero minimum of zero and one is zero till here also 0 so here we are coming in right to left and maximum left to right now we have all the ingredients now we are ready to solve it so we partition here first point this is the first partition so what we need to check is that maximum till this point maximum before this should be less than minimum from right and till here one element next so maximum till here is this value 1 and minimum here is 0. so is this max less than min or equal to no 1 is not less than equal to 0 so we did not find a partition let's extend it we will come here the next partition now again maximum till here is 1 and minimum in this part is 0 till this point so again the same condition not satisfied we move next again we compare 1 and this 0 so if this value is i this index is i then this value is i plus 1 so what we are comparing maxis so this is max you can also write max arr max array of i should be less than equal to mins i plus 1 when this condition is satisfied we stop there again not satisfied we try a new partition now it's 1 and 6 now 1 is less than 6 so this is now valid so we stop here this is our final partition so now we have to just return the length of this so what is the i here where it was satisfied 0 1 2 3 so it we will return i plus 1 because index starts from 0 and we are including till i so i plus 1 so now what should be the time complexity here so for creating this max array it takes end time for creating this min it also takes n time and then we try for different values of i and stop somewhere before the end so again maybe worst case n so some constant time in or of o of n similarly space required is we are keeping these auxiliary arrays of the same size so time is often space is often it's very simple now let's write the code for this in c plus first java and python so you can go through this question partition array into disjoint intervals so i have already discussed this so we will be using this size multiple times so better to keep it in a separate variable min should be of same size n and min we are starting from right so we can initialize it with all the values with n minus 1. similarly you can keep a better name mean arr would be better let's make it and this is from left to right so we can initialize with nums 0 and now let's fill the remaining elements so 0 is already filled and the last one is already filled so there are you can do it as per your convenience you can run two separate loops one starting from right and one starting from left but you can do it at once also you need to just do a little bit of january here max arr of i so this max error we are filling from left to right so the index will remain i the previous minimum so while calculating the uh maximum for this l index we compare with the previous what was the previous maximum or that the previous uh the max at the previous index is the latest maximum so we compare that value with nums i so that's why i am writing max error i minus 1 one previous value and the current number now we can do within this loop itself although we are we have to fill it from right to left we can manipulate the index n minus 1 is the last index so if here we are 1 denotes second value so n minus 1 minus i will denote second last value if you are not finding it comfortable better to do it in two separate loops uh min err n minus i minus 1 this thing so same way if we are calculating maximum till uh let's say this index then we will compare this nums at this index and max at one previous index because we are coming from right to left so the same way we have added one here if you add one to it this one will go away this was minus one and nums i minus 1 sorry the same index whatever is here so n minus 1 minus i so now we have both these areas filled so we have done the major part of our work now we just need one loop and we are done so max till i is less than equal to min from i plus 1 till last index then we return there itself we break on or we return i plus 1 because still i we are including an index starts from 0 so there are i plus 1 elements and here also you need to return some value although it will not reach here since they are saying that it's guaranteed that these will be non-empty guaranteed that these will be non-empty guaranteed that these will be non-empty but since the return type is end you have to return some value so we will return 0 although this will never be hit now let's run this so this is correct let's try this example the second one both answers are correct so we can submit and the solution got accepted so i hope you understood it now we will write the same thing in java and converting it should be trivial this should be length and this will become math dot max and math dot min rest should be fine let's see zero so okay some typo okay same thing i heard now it's correct so submit java solution is also accepted and now we will finally write in python again trivial to convert you and the python solution is also accepted
|
Partition Array into Disjoint Intervals
|
generate-random-point-in-a-circle
|
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that:
* Every element in `left` is less than or equal to every element in `right`.
* `left` and `right` are non-empty.
* `left` has the smallest possible size.
Return _the length of_ `left` _after such a partitioning_.
Test cases are generated such that partitioning exists.
**Example 1:**
**Input:** nums = \[5,0,3,8,6\]
**Output:** 3
**Explanation:** left = \[5,0,3\], right = \[8,6\]
**Example 2:**
**Input:** nums = \[1,1,1,0,6,12\]
**Output:** 4
**Explanation:** left = \[1,1,1,0\], right = \[6,12\]
**Constraints:**
* `2 <= nums.length <= 105`
* `0 <= nums[i] <= 106`
* There is at least one valid answer for the given input.
| null |
Math,Geometry,Rejection Sampling,Randomized
|
Medium
|
914
|
1,941 |
Hello Gas, in today's lecture I am going to solve the questions, check if the character which is equal is given, now a string has to be told whether it is a good string or not, now how to identify a good string if the frequency of each letter in it is If A is coming from A then it is a good string. If A is not coming with the frequency of every letter then it is a bad string. That is, we have been given a string. How many times is A coming here? Twice B, Twice C, Twice A. If so then it will return True Mains This is a good string Good string And if we look at this example, is this a good string in this No This is not a good string Okay, now this is the question once in the question. Let's see the statement string s written true if today n good string we told and false adverb and string it is n good if character date is upper in s have se number of n e what we did se number of a e should be se number of Number of currents by frequency: It has been A twice, B Number of currents by frequency: It has been A twice, B Number of currents by frequency: It has been A twice, B twice, C twice, the same now like this example, A three times also twice, so this is not a good string, so let's see its code. Now we have created that order map, we will study in it. Created an order map in it, passed a character in it, main is this character which is given and integer, so what is the frequency, okay, now we have run the loop, okay as far as the size is given and each letter is started from zero and each letter is increased. We will keep checking each and every frequency, okay, it is not from zero, what is he doing here, hey, we will keep moving the character, we will keep checking further, from zero to one, how much are you going to increase and started the loop automatically, auto word tomorrow. We had already discussed that auto is okay, now what did we do, what condition did we check if a dot second is the second character we are getting, if it is not equal to the count, then we will do the letter if it is not equal to the count. Is not equal to if like A is A, how many times has A been ours, three now is B, how many times has A been ours in this, two times is that three and you are not equal to both the counts, then what will we do, we will make water, otherwise. What will we do to the string? We will return it to True. Do you understand what I mean by saying that if as we have made the second one by doing a dot second, if it is not equal to the count is what is given. If you are not able to find its equivalent, isn't it, if there is only one character, three, B, character, you, what is happening, then make it redder, else you have to return it is true, processing is going on, it has been accepted with good complexity and this See, this is a very good concept, so this was today's question. If you liked this video, then like, share and subscribe so that I get motivation and peace by uploading videos daily. Thank you so much.
|
Check if All Characters Have Equal Number of Occurrences
|
minimum-number-of-operations-to-make-string-sorted
|
Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_.
A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency).
**Example 1:**
**Input:** s = "abacbc "
**Output:** true
**Explanation:** The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
**Example 2:**
**Input:** s = "aaabb "
**Output:** false
**Explanation:** The characters that appear in s are 'a' and 'b'.
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
|
Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately
|
Math,String,Combinatorics
|
Hard
| null |
880 |
hey everybody this is Larry this is day 27 from delico day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm uh decode decoded string at index ah 880. uh before I get started I'm gonna give a heads up because I feel like the last couple of time I did this uh and I'll say over the next couple of days but the last couple of times I did this apparently people were surprised and I kind of missed out on a couple of people in uh Uzbekistan and uh Kazakhstan so I don't know so just a little heads up I'm probably gonna be uh swing by Taiwan for a little bit uh and parts of Japan so if you're in the next two three months or something like this uh so if you haven't already come to the Discord and let me know if you're from those areas or maybe different parts of Asia and we'll see if uh you know grab some food or something like this I don't know uh just don't kill me please anyway uh today's problem is 880 decoded string at index uh yeah you're given an encoded string s to decode the string uh to a table the encoded string is red one count at a time and the following steps are taken if the character reader said letters that letters went to the tape if the character red is a digital the entire current tape is repeated when D minus one more times in total given an energy K we tend to go okay so this could be very big I didn't multip um okay so there's only one digit uh what I mean by that is that um haha is actually this is times two twice versus times 22. so the sub problem is uh kind of you know okay let's see I mean this is kind of an interesting part but I mean I think it's just about doing the math if I have to guess what uh yeah um what is the clean way to do it I'm thinking right but I think just doing a one character at a time should be okay wait uh entire tape okay I actually was curious if that was like the last delimited or something like that um so code would be just code times three but then this is actually lead code times three or something okay so that's that should be actually easier foreign yeah I mean we might I mean I think this is what I would call a bookkeeping problem uh and bookkeeping is just making sure that you keep track of the book If you will but keep track of certain things in a very consistent way every step of the way and I there's like a little bit of math but everybody isn't that much math from what I can understand um other than like modification or something um so it should joke and like maybe mod but should be okay so let's get started and then kind of see right so um how do I want to write it right maybe I'm wrong with them I mean it's just very easy to be annoying um so I just say maybe um grabbing oh God I see do I know hmm I mean I guess the other way is just doing recursively uh and or like doing not necessarily recursively but um taking advantage of that the stack uh the length of the characters or the string is only up to 100 uh should be okay I suppose yeah I think I'm just trying to be very careful about thinking through the edge cases I think these kind of problems is just very easy conceptually to have a lot of edge cases but um like but of course your Educators depend on how you implement the problem and it's way easy to kind of like get a little bit lazy as I would say with the thinking and then like adding an if statement but then this if statement doesn't actually include all the things and just like a subset of what you think um might handle right so I think that's kind of the tricky part um um so how do we think about this maybe I'm just like being a little bit slow today uh but I think okay I forgot again I get confused on this particular one because you have to do the number actually wants the entire string and not just the thing so that's why I'm I don't know if I have trouble understanding that or like uh remembering it uh because then now it should be okay so now let's say we have a stack but um and then now for C and S um f c is digit then we do some stuff um let's pass for now if it's a character then we just a pen to character but then now foreign and then now what happens when we see a digit so now um and I think this is because it's a thing then we can return something like C I think this only goes in this case anyway because this case has to handle it a little bit differently um we'll see okay and then now if it is a digit then um okay so what happened what happens right so then now we take the length conceptually the length not the actual length kind of thinking about this pretty poorly to you to be frank so let's say we have two and then we up to corners for this okay maybe we just have a current I don't know about this thing yet to be honest but uh yeah let's just say um maybe C is equal to zero and this is like you know increment by one right if this is digit then um scene we times it by C maybe right now well it can only go up to nine times so maybe we can I think this should be okay in any case um what happens if it's one oh it's D minus one more so okay uh so actually technically I guess it's no I guess this is fine but can digit be one uh only two to nine okay because that I mean that's fine it's just very weird in that case right and now what we want to see is um okay if or maybe the current Loop the current step is equal to end of C minus one times scene something like this so this is the thing right so if the current step is greater than k then this is um then we have to do some math otherwise then K we subtract current step but we have to do some something so that uh we keep track of it right man I'm not am I'm just wondering whether I'm thinking about this really like I'm thinking it's probably like a stack thing but I am not thinking very well about it so basically you have like because you can think about them as parentheses right like every time you see a number you just put around on the previous thing right so and this is actually before this happens of course um but then when you need to because at some point this is what this step is for right um we do need to go back to kind of figure out where it is right so that means that uh we want to see hmm like the Cave thing here so okay maybe let me think about this a little bit I think I watched it a little bit and I'm I think I'm not gonna lie I underestimated um maybe I underestimated because uh because this is a medium or maybe I'm just having a rough day it happens uh okay all right I think I'm just trying it too hard to do everything in one Loop to be honest as well so maybe we can just see a length physical to something like length is equal to zero for C and S if C is digit then length increment by one right so then now we're trying to get um this pencil and then now we try to get Decay Maybe and then the K of here and that's just gonna be like uh so we want to Stack it's okay so increment by one means that foreign let's say you want to the cave number here and I think I want something like this is so hard to find a right data structure for um okay so basically I want to do something like lead two so okay so let's say we want the 10th um attempt character here right what do we want so this three what does this mean uh going backwards on the stack so 3 means that well this three doesn't mean anything so now let's expand it out so the two lead code and then this times three right and now this can be written as this times three um and then what this is saying is that we have a k that's 10 then but this length mod mud this link which is 12. so 12 wait what yeah 10 by 12 is going to be 10 so then we could just get rid up to three uh and then now um I guess going backwards this is going to be and then it's gonna be an oh okay but what if we want a three right well if we want a three this is ten nine eight seven and then now we see a number um and this is four times two so then now it's going to be mod 4. well it notes that this is eight so then and then when it sees the two then it might still okay so something like this maybe um how do I actually implement it uh okay I think I see it but wow have I subbed I have saw this before why am I struggling today I don't know some days you're just a little bit off uh okay but um how would I write this in graphic I guess I don't need a stack I can just toss the string one by one but um if C is it is digit then now the cycle is or the yeah it's going to be length my uh Delta by into C so this is the length of the previous thing um and this cannot be the end so then now okay we might this and actually I guess we can just actually divide it and then my all right and else we Inc we document by one and then if K is equal to zero we return C and maybe a third Force not possible maybe huh I guess it is possible uh print K Maybe um hmm oh wait this has to be here but um what happens if it is perfect maybe I'm off by one let's see right so let's say the okay so this is 12 if this mod is if K is 12 then it'll be here but then this mod would be zero so do we have to add one back on am I off by one maybe not I don't know why is it that way for the first one though uh okay let's see what the length is should be let's see 30 uh yeah 36 right okay yep so that's why 36 we divided by three yeah we divided by three so that's 12 K is 10. I mean it doesn't work without it so I don't know all right okay fine let's print everything so okay right 63 minus 10 okay 9. d uh yeah seven six right I miss this it's the 10th character in this thing in the remaining strain that did I get something wrong I guess so uh okay so you won this the 10th character here and then the uh this is nine to nine character I think I'm doing it wrong because I thought I was counting it backwards but obviously uh that's not quite the way to go what I want is given that this is 10 is it seems weird I do the math uh okay e is gonna be eleven and then D is 12. get the temp character in here foreign how can length be zero okay so this is this number we see a nine and then we already mess something up that way I see a nine let's do a length if you see a two you see a length of one yeah okay and then you want the silver character um I don't know this is I'm being really weird on this one even uh okay we do one okay we move to e so that's one uh it's gonna be 12. um that's just the last letter of this why am I off by one maybe this I'm not confident about it though it's very yucky even if this happens to fit this particular case um or anything else let's try more cases nope what did I miss uh cooking random things right uh oh I'm missing k I mean these are oh did I delete it I guess uh okay so I guess this feels very yucky though that's what I mean by like Edge case earlier I'm still not convinced the length of you because it's zero frame it's needed that's why I didn't do it okay um oops all right now it looks a little bit cleaner that's why like I wasn't confident about it but I still might miss something I find 1275 is a streak this was kind of a mess to be honest uh I did this kind of trick I don't know I think today I'm just having a rough day I don't really have any excuse um but yeah but I think the way to actually think about it is I mean I reversed to the string but to be more accurate I think this is more of um I think that's the trouble that I had just because I uh I don't know if this is gonna be humble bag but there's just like I think I know too much for this problem um because I was thinking about like stuff relating to uh and I kind of alluded to this with the parentheses but basically like a sort of a request of descent and try to think about this as a natural language with respect to a character and a digit but um and of course this is a way um is it is that true no uh um I was going to say this is an FSA but um and you're just trying to figure it out but maybe I'm wrong with that one the final state of the terminal uh I'm way off today so maybe everything I say as well but uh but yeah um the idea is just kind of keep on going uh I mean I think I vote in a weird way but I think the idea the cleaner way to think about it is as I said is a using a stack and I think that's where I also got a little bit mixed up in my head with um a sort of recursive design because The Descent of is um you know it's implemented using recursion but of course part of that recursion is uh an implicit stack right and in this case because it's only you know it's about reading uh things off the top of the stack if you kind of put think about it that way even though it's um I think the reason why we didn't need an explicit stack is because all the operator all the operations operate on the entire string versus like a subset or something like this I was thinking about how to implement that part cleanly um within the context of uh language you know acceptance but to be frank uh maybe I'm just out of shape or maybe like I just wasn't able I mean I think I was able I could have done it but I think it was like too annoying to do um maybe that's not a great excuse though um because what I could have done is I mean I could have just packed all this into like a Taco uh but this is a little bit cleaner uh only because we required a lot more thinking for it through all the cases and kind of yeah the length of the remaining digits that's a little bit tricky to do so I don't know how do you think in the comments let me know if you struggle with it let me know if you have any questions um I always say you know uh if you have questions then I can actually enter it because you know explain better it's not a question that's all I have for today that's what I have for now uh I'll go one quick is that this is linear time linear space because well the way that I wrote this backwards but you didn't need to do it like this so then you kept at it in constant time um depending how you say it because yeah maybe you're not good that length is technically uh um is linear space because it always grows to the uh it could grow to the number of uh the length of s it's just that you know there's an additional constraint that is 2363 but I guess we really want to build your pedantic this is uh linear space as a result um yeah that's all I have with this one let me know what you think stay good stay healthy to go Mental Health I'll see y'all later then take care bye
|
Decoded String at Index
|
rectangle-area-ii
|
You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
* If the character read is a letter, that letter is written onto the tape.
* If the character read is a digit `d`, the entire current tape is repeatedly written `d - 1` more times in total.
Given an integer `k`, return _the_ `kth` _letter (**1-indexed)** in the decoded string_.
**Example 1:**
**Input:** s = "leet2code3 ", k = 10
**Output:** "o "
**Explanation:** The decoded string is "leetleetcodeleetleetcodeleetleetcode ".
The 10th letter in the string is "o ".
**Example 2:**
**Input:** s = "ha22 ", k = 5
**Output:** "h "
**Explanation:** The decoded string is "hahahaha ".
The 5th letter is "h ".
**Example 3:**
**Input:** s = "a2345678999999999999999 ", k = 1
**Output:** "a "
**Explanation:** The decoded string is "a " repeated 8301530446056247680 times.
The 1st letter is "a ".
**Constraints:**
* `2 <= s.length <= 100`
* `s` consists of lowercase English letters and digits `2` through `9`.
* `s` starts with a letter.
* `1 <= k <= 109`
* It is guaranteed that `k` is less than or equal to the length of the decoded string.
* The decoded string is guaranteed to have less than `263` letters.
| null |
Array,Segment Tree,Line Sweep,Ordered Set
|
Hard
| null |
799 |
hello everyone welcome to our channel cody with sunny and in this video we will be talking about the problem champion tavo you can see its index is 799 and it is the medium problem of the lead code okay so yeah before moving on let us talk about the prerequisites required to solve this problem efficiently so basically we are going to use the concept of dynamic programming like how we are going to use the already pre-computed values to use the already pre-computed values to use the already pre-computed values to reach to find out the values at the current state okay so yeah also i would strictly recommend you guys to read this problem at least once uh because i'm not going to read all those along the statements rather than i am going to explain through the diagrammatically how this problem is going to state and how we are going to find out the solutions efficiently right okay so let's begin so you can see we are going to have the glasses placed over there and when we pour some x glass of water or you can see we are going to pour some champagne so but now let's say we are going to pour some x class of water so when x is 1 so it means that we are going to fill this complete like that okay so when x is 2 right now when x is to you can see when you try to fill water over to this glass that is present at the layer one some water will overflow and that overflow water will be going down over here okay so the main idea is like how to estimate how much amount of water will the word flow you can see the glasses are placed like equivalently like when you pour some extra one glass of water exactly one by two glass of water will be going over here and one by two glass of water will be going over here right and that is at the step x equal to two this will be completely filled and this will be half filled and this will be again half filled now when x is three you can see again one by two amount of water will go over here so this will be completely filled and this will be completely filled right so this is the sequence of steps we are going to use okay now when again x is four now this is quite tricky so when you pour this uh exactly one extra glass of water right over here so you can see a one by 2 amount of water will come over here and 1 by 2 amount of water will come over here and that would be an extra amount of water so that will also work flow so 1 by 4 amount of water will go over this position and one by four amount of water will go over this position and again one by four amount of water will go over this position and one by four amount of water will go over this position so this is the exact trick to understand how much water will flow to the adjacent glasses to the layer below the current layer okay so how to find that in this problem we need to find how much the glass is filled with water uh like yeah how much the glass is filled with water when x amount of water is poured to the very top glass how much water is filled with uh wait a minute how much the glass is filled with water when x amount of water is poured note that this glass is actually talking about any random glass that is present in let's say that is present in ith row and the jth column sorry jth glass that is let's say we are going to pour x equal to some let's say 150 amounts of water at the top of this class and we need to find how much the glass is filled at the position let's say fourth row and third glass so it means that this is the very first row this is the second row third row fourth row and the third glasses this class so we need to find how much water is filled in this glass how much the glass is filled with water in this glass right okay so how we need to find so the basic idea is to perform uh you can see uh breadth first search you can also see breadth first search with a little dp little dpdp is nothing but we need to store the values okay so when you are at this first glass of water let's say x amount of water is poured okay so we will subtract x minus 1 because this is completely filled so this x amount minus one water will be going to the this glass and again this class will also contain x minus one upon two okay so again this remaining glass will go x minus 1 upon 2 which is 4 and this also x minus 1 upon 4 and this we are going to have x minus 1 upon 2 sorry x minus 1 upon 4 and again in the sequence of steps the water will go like that where x is the amount that is being filled at the uh you can see at the top of this glass now there is uh one more missed the one mistake that i have done and what is that mistake like if you haven't noticed when x amount of water is poured to this position then you can see the remaining water is x minus 1 because this is filled and then x minus one by two amount will go over here x minus one by two the amount will go over here now when this glass is filled when this is filled then only this water will overflow okay so what you are going to do is you will just find out this value x minus 1 upon 2 let's say the value is coming out to be 50 let's say for an instance so when it is coming out to be 50 then you will subtract 1 because this is filled so it becomes 49 so 49 by 2 will go over here and 49 by 2 will go over here right so again here also 49 by 2. so that x minus 1 by 4 is quite wrong so you're not going to write this one okay so what you're going to do is you are going to find out the sequence of steps first then they will subtract one if the glass is filled and then you will pour the extra amount of water to the glasses that is present in the below layer okay so let us understand by taking an example let's say x is five okay so what you are going to do is so five amount of water is going to be at this position so one glass of water will take to completely fill this one so we have extra four amount so two amount will go over this position two amount and two amount will go over to this position so one amount will take to completely fill this one and one amount will take to completely fill this one so extra left over is one and left over here is one okay so you can see so 1 by 2 will go over here and again 1 by 2 will go over here so extra is 1 so 1 by 2 will go over here and 1 by 2 will go right so you if you are asked what is the amount of water how much the glass is filled so you can see one by two plus one by two is one so it is completely filled completely you need to actually return the ratio right i will tell you how we are going to do that and here it is of half build and here it is also half filled right so let us understand the code how we are going to do that okay so your time complexity would be o of r into c and space will be of r into c because we are considering every glass and we have our amount of layers in maximum and we are going to use the matrix to store the data how much amount of water is filled so i have a vectored matrix of double type okay and size will be query row plus 1 and query row plus 1 that is n cross and type of matrix where n is query row so i will start with a queue containing two indexes like we are filling out the values layer by layer okay so the very first layer will contain zero comma zero that is the you can see actually it is saying that we are having in the zeroth row and glass number is zero the glass number note that everything is based on zero based indexing right so dp of zero is exactly equal to board and yes we are going to do layer by layer so we are going to iterate up to this amount of time you can see i 0 less than query row so take the query size sorry queue size and work on every glass right so extract the glass number like row number of this class column number of this class pop it out now uh you can see this data is this dpf xy which is actually you can see the amount of water that is present over here now it if it is less than 1.0 you can easily see the is less than 1.0 you can easily see the is less than 1.0 you can easily see the glass is not filled or let's say it is 1.0 so glass is completely filled so no 1.0 so glass is completely filled so no 1.0 so glass is completely filled so no none of the water is going to be overflowed so in that case we are going to use the continue we are not going to move further otherwise extract like subtract data minus equal to 1.0 because it will take minus equal to 1.0 because it will take minus equal to 1.0 because it will take exactly one glass of water to fill it okay so now we have some remaining values okay the data will contain the remaining values of extra water that is being overflowed so it will be overflowed in the equal direction to the both of the glasses that are present to the layer below it so i will check it out if dp of x plus one with that is the glass present in the next layer and the y it means that the same glass corresponding to that so if you're not visualizing it so let me just explain so you can see uh it is zero comma zero and it is zero comma sorry it will be one comma zero and it will be one comma one and it will be 2 comma 0 it will be 2 comma 1 it will be 2 comma 2 like that so i will check it out dp of x plus 1 y exactly equal to 1 point minus 1.0 okay so yeah so minus 1.0 minus 1.0 okay so yeah so minus 1.0 minus 1.0 okay so yeah so minus 1.0 denotes that the glass is empty right so yeah if dp of x plus 1 y is minus 1.0 so yeah if dp of x plus 1 y is minus 1.0 so yeah if dp of x plus 1 y is minus 1.0 it says that this is empty so we are going to fill this value with data divided by 2.0 because the divided by 2.0 because the divided by 2.0 because the glasses that are present directly below the current glass and the layer below it will be filled with equivalent like equal amount of water that are being overflowed so data is contains the water being overflowed data divided by 2.0 will be the water data divided by 2.0 will be the water data divided by 2.0 will be the water going to the left glass to the layer below it and again this one is also going to do the same thing data divided by 2.0 now yes if the thing data divided by 2.0 now yes if the thing data divided by 2.0 now yes if the this value is still not processed that is the glass uh is not having the water so you are going to push it the into the queue the glass number x plus 1 comma y and also initialize with data divided by 2.0 and initialize with data divided by 2.0 and initialize with data divided by 2.0 and yes if it is already being having some water you need to increment the water present in that glass that is dpf x plus 1 y plus equal to data divided by 2.0 okay plus equal to data divided by 2.0 okay plus equal to data divided by 2.0 okay so basically it is doing nothing suppose so you are at this glass and you are going to pour the water over to this one now this entry is not in the queue and it is unfilled so you will first fill it okay so when you come to this glass you can see this is already filled that is this is already filled so you will add some more water to it so this is what we are going to do and again this is for the x plus one y plus one okay now when this all goes well for all the layers you can see i less than query row if dp of query row and query glass is greater than one point zero right so it is greater than 1.0 it means right so it is greater than 1.0 it means right so it is greater than 1.0 it means that the glass is completely filled so you need to return how much the water is filled it is actually the ratio so you will return you will assign this value as one point otherwise also it is like unfilled you can see so you need to return 0.0 can see so you need to return 0.0 can see so you need to return 0.0 according to the problem statement otherwise you will return the ratio so what you're going to do is like you will divide by 1.0 you will divide by 1.0 you will divide by 1.0 okay so it is nothing but today it remains the same so if you uh either remove it doesn't matter and finally you need to return this value tp of query row and dpf query class right so this will give you all test cases passed so if you guys have still any doubts do reach out to us to the comment section of the video and thank you for watching this video
|
Champagne Tower
|
minimum-distance-between-bst-nodes
|
We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)
For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.
Now after pouring some non-negative integer cups of champagne, return how full the `jth` glass in the `ith` row is (both `i` and `j` are 0-indexed.)
**Example 1:**
**Input:** poured = 1, query\_row = 1, query\_glass = 1
**Output:** 0.00000
**Explanation:** We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.
**Example 2:**
**Input:** poured = 2, query\_row = 1, query\_glass = 1
**Output:** 0.50000
**Explanation:** We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.
**Example 3:**
**Input:** poured = 100000009, query\_row = 33, query\_glass = 17
**Output:** 1.00000
**Constraints:**
* `0 <= poured <= 109`
* `0 <= query_glass <= query_row < 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
94
|
1,727 |
hello everyone this is anne fijo sando welcome to the series for preparation for coding interview today i'm going through a little code 1727 logic sub metrics with rearrangement if you like these videos you can support me by subscribing my channel or click likes buttons in video below you can find the complete video list in video description below let's look at the problem description first so we're given a 2d matrix then we can randomly uh not running but we can free to swept the whole columns with all the columns then we also return the area of the largest sum matrix which every element of the sub matrix 1. so in the first example the best solution is to swap the column 3 with column 2 then this is what we get and the logic some metrics including one is the uh board matrix here so in this example the largest area is one two three four is four then the in the second examples we're given a 1d uh matrix then basically we can swap this blue one with the yellow one and then swap this purple one with this one it's coming to this matrix then the largest area is three next let's go to the solution i call this solution it's doing some greedy idea or maybe um it seems like this method also use some like kind of simulation how we swept the columns um here is a solution we going to iterate uh row by row then we evaluate the matrix from the initial row to the current row for example if we uh start with road index zero so this zero we only looking for this part of matrix uh we have helper right here to record um how many ones for these cells and its upper cells then for example if we have looking the first row of metrics we will have this array which means for this cells it has zero ones and for these cells have only one cells because in the operator it doesn't have any elements therefore this one is zero as well then what we're going to do is we do the sort um from the highest value to the lowest value for this array then we obtain 1 0. basically what it means we always want to swap the largest columns with the largest ones into the first elements and the second largest second then next we are going to evaluate so basically uh if we do the one zero which means uh is equally it's like for the first uh 1d matrix we sort which means we swept the second column to the one so it's we get it's one zero matrix then for this case of course the largest area is one so we will update the maxi area um variable and for the seconds columns because itself is zero there's no way to get the sum matrix from including these cells so we cannot get any valid answer the same for the third columns then we come into the next row basically we are looking the sum metrics in this area so again we record the helper array so for these cells um it is one but these above elements is there's no continuous one so you still have only one then the different step for these cells though these cells itself is one and its operator is one as well so it's coming at two then the same for these elements same for the first one it's still one so now we sort again you got two one then basically after we sort it means like for these 2d matrix we swap the second row with first row it's coming one zero one then we evaluate um the subtracts column by column the fourth columns we only use uh these cells and this upper one so of course this area is two then when we come into the second cell basically we're looking the area is including the first column in the second column but its opera is zero so the only sub matrix we obtain is these two so the area is still two in for this sum matrix then when we go to the third cell um we're looking all the whole to the this 2d match but because it's upper and the second column opera is also zero so the only sub matrix we can obtain to include these cells is this one so now this area is the current largest one is three so we obtain the max area three here so finally we come into the last row again we will formulate our help array so for these cells itself is one and it operates one so it's two and for this cell um these upper cells have two ones so it's three then this cell is kind of special even so his opera is one but because itself is zero so we will put it zero because there's no way to formulate the sum matrix which including zero cells right then after we obtain two three zero we sort again to have three uh which means we swap this column with this column so we got one at left most and the zero one the other one have in the second columns then we evaluate column by column again from these cells we just build a sum matrix including its cells and it's upper one uh it doesn't have any left corner so the maximum we can obtain is three and uh we want counting all the cells in the matrix basically we just use this one as its height right so then multiply is this so this is one then for the two for these cells we are looking uh some matrix uh for this area since this one is zero so we only get these two then the way to calculate that is it's the same use its height to multiply the width is these two right so it's four which is the our final answer then for the uh letter zero sub since there's no way to build a submatrix including zero so we just keep it so yeah so that's how we come the most areas for so next let's look into the code um so into my implementations i get a low number um total corner number i build in the help array as a vending matrix column by column so using the corner number and we have global max area to call them the max the largest area then first for loop we iterate by row then we build in the helper array by iterating all the columns first if it's one so we adding one um into the helper array so one thing to be noticed that the helper array here also recruit the previous once so you we don't need to look into the say the upper row again we're just directly adding one here if it's go to one otherwise reset to zero so then i just saw this array to get a new array i will use it for next for loop the next for loop is how we evaluate column by columns and the calculates area right so if the current cell height us is greater than zero basis which means the current sales is not equal to zero so we got the max area of max of the mass area and uh it's area right the x area is basically it's a column index plus one is then this is the width and the multiply the height then eventually uh we got the maxwell area so the way i'm saying here using greedy idea is because we're also trying to utilize the height most in the left then once uh we evaluate more later columns basically we're trying to maximum the base this is why we want to solve the helper right here in terms of the computation complexity we had the one for loop outside so we have big of n here multiply how many operations in the next loop then here j loop we have m operation this is m as well but this here is the most costly is called m log n so we take the mass one so in general it's like b of n multiplied m log n in terms of the space complexity uh we create the help array here the speaker of m of course there is a way to reduce the uh space complexity which is to adjust the directly right into the matrix as using help array value but here i just for more readabilities i'm choosing to have a helper right here okay that's all about today if you like my videos please comment and uh let me know any problems you want me to explain further and see you next video
|
Largest Submatrix With Rearrangements
|
cat-and-mouse-ii
|
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`.
|
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
|
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
|
Hard
|
805,949
|
1,687 |
hey what's up guys this is john here so today let's take a look uh it's called problem 1687 delivering boxes from storage to ports so i mean this is a really difficult problem okay so let's take a look at the problem description so you have a the task of delivering some boxes from storage to their ports and you only have one ship and the ship has a limit of the number of boxes that can carry and also the total weight as well and then you're given like an array of boxes right where the each box has two properties right so the first property is the ports the box will go to and second one is the weight of the box right and then you have then you're given like three integers so the first one is the it's a ports count the total ports count i'm not sure if this is really useful or not but we'll see and second one is the max of basically the limit of the boxes the ship can take and the last one is the maximum weight all right and then here's the here's this how here's how the ship will deliver those boxes so each of the boxes you know let's say we have like bunch of boxes right and each boxes has to be delivered in order so which means that let's say if this the first one is going to port one and second one go into the port two and three two and one right so let's see i'm ignoring the weight for now if there if this the number represents the port the box needs to go to so even though we are like let's say we're assuming we are loading all five boxes into the ship and then the first time the port will of course it will go to the port one right and then because it needs to deliver port one first before delivering the uh it needs to deliver the box one first before delivering the box two here that's why the shipper needs to go to port one first and then unload this box one and then it will go from port one it needs to go to port two and then it will unload this box and then it will go to port three right to unload box three and then it has to go back to port two to unload box two download this box because even though there are like two boxes there are two boxes that belong uh needs to go to port 2 but since they need to be unload in the other in the same other that's why that's go to port 3 and then come back to port 2 and in the end it will come back to port go back to port 1 to deliver the last box and this is how the ship will deliver the boxes right and each time uh when the ship from port one to port to ships between different ports it will do a one trip and also from the storage to the first chip to start from storage for to the first port and from the last port back to the storage right basically this the ship will from storage it will at the beginning it will go to the port one and in the end whichever the ports is ending it's ended it will come back to storage that's why in this kind of trip here we have one two three four five and six so we have in total six of trips we need to make right and then the question is asking you to find the minimum of number of trips the ships need to make to deliver all the boxes to their respective ports and that's the description it's a pretty long description and you have a lot of parameters and here's our just some examples right and i'm not going to go through all the examples but and then the in the end here are the constraints basically the constraint is like 10 to the power of 5 so which means we can either use o n or unlogan solution right and this is make what's making this problem a hard one all right so to get the minimum number of chips right we have a bunch of options i mean we should try to think about what kind of like solutions we can try right i mean the first one is what is it the bfs right so but i don't think we have you know bfs solution here because there's no clear starting and ending state here and then we have like what the next one is of course you know the dp right we can always do the dp and this problem is actually a dp problem with a little bit with optimization on top of that so why is that because you know the uh so the dp right so a very naive dp uh like definition is for dpi right so dpi means that to deliver the first icebox what's going to be the minimum trips right the minimum trips we need to make and the definition is actually correct but you know a naive implementation for this one is the uh let's say we have like this kind of boxes right so let's say we are at like this dpi here right that's gonna be the r i here so what's gonna happen is that you know from here go to go back right since we're going to get some state transition right from dp like and dpi equals to some dp dpk let's say dpk plus the trips right so this is going to be our state transition right from we basically we pick the k location and then plus the trips right between the k to i so let's say we have a we have k here right so basically so this one it means that you know we're going to deliver the boxes from k to i within one trip okay and then whatever before k will be the what will be the remaining and the trips delivered from k to i will be the current the cost the trips where we need to make right and then so the trips will basically well of course depending on how many distinct uh ports we have in this range here right and then we're gonna that's gonna be the trip of course we have to also consider the storage right so store reach sorry to coming back to the storage and go and to pick the boxes and then we go back to the first port that will be a another two chips right but that's going to be the minor thing we need to worry about here and we will basically will try of course we have to make sure this from k to i uh it's within the limits it a compliance with the constraints first one is the max boxes it's not exceeding the total number of boxes and the second one is total number of weight right that's going to be the two constraints we need to follow and then and after following those kind of two constraints basically we try each of the k locations from 0 to i assuming we can pick any of them right assuming we can pick any of the boxes from k from 0 to i and that of course obviously is a o n square time complexity right assuming we can get calculated strips uh using one time but still it's going to be a o n square and with the o n square time complexity and with this kind of 10 to the power of 5 constraints it will most likely tle so and that's the difficulty part for this problem and we have to somehow and improve it and the way actually it's improved is uh we're using like a greedy approach right plus sliding window approach basically it's the sliding window it's just help us to calculate the cut the trips more efficiently and then help us to find the uh the best k we need for the current i that's our greedy approach so to remove this the intersect the nested loop for finding the k here like i said we use a greedy approach to find the best k for the current i and how can we find it so a general approach to f to do a greedy is i mean it's kind of makes sense right i mean we want to make we want to load as many boxes as possible within one trip not i'm sorry not within one trip but within the one yeah trip from the storage that's gonna be our uh general gritty idea here but we have to quickly tweak it a little bit because and we don't want to like let's say for example we have like uh some ports here let's say we have one two and two right and then we have three one and one so let's see we have this kind of ports right assuming we can pick any of the those boxes right within the uh let's see this max box this is pretty big right and we can pick any boxes as we want so let's say we are at like this i here right and then let's see the total the max weight we have here is that you know let's see each of them the weight is like is one okay let's see the max weight we can pick is four right so which means that you know if we're using our initial gradient approach it means that we want to pick as many boxes as possible right so that's from the current i here we see that okay we can pick uh four boxes that's why we're okay with okay now the k is here right and then but are we going to try to pick from two three one prop probably not why is that because you know you guys can see here if you pick two here we have the next one is three and then we have one and one it means that we have to make uh we have to make two moves two trips to pick to deliver all boxes because we have three different boxes but if we leave the two to the previously delivery that which means that let's move k once one way closer to this place let's say we move the k from there to here assuming this these two can be delivered within the previously previous delivery now the trips we need to deliver all three boxes will become to one so that's going to be the uh our a little bit of improvement of our naive greedy approach so which means that you know so the greedy approach is of course is this so we try and we try to deliver as many boxes as possible but with one exception which is the uh if the current one can be delivered uh can be delivered with the previous one and we're not adding the we're also add not adding the uh we're not also not making the previous one needs more chips then we will like move the cursor to the right so how do we check that remember we have a dpi in here right so if the dp let's say even the dpk that's the dpk if dpk is equal to the dp k plus 1. so if the dpk equals to dp k plus 1 then what so what does it mean it means that uh to deliver from to deliver one two to three well actually yeah so i'm assuming okay so to deliver one to two and also to deliver one two three they're having they will they requires the same uh trips right so which means that you know that's actually yeah actually this is not a good example here maybe the two is it should be here i think the case should be here this is a better example here so let's say the k is here and if the dp right if the dpk equals the dpk plus k plus 1 and it means that you know actually the next one has to be the same as the previous one otherwise you know otherwise if we are not if these two are different you know the dp k plus one it will has to be a has to be one more than dpk why is that because if this one is different if that's different i mean to deliver from this uh port to this port it will make one more trip but we are anyway we're using this one to check if we can move the cursor forward to here because if the dp is the same it means that you know the k the from to deliver from one to deliver from zero to k and to deliver from zero to k plus one requires the same trip right and of course that means that we should since we're using a grady approach that means that we should leave the k plus one to the previously to the previous uh deliver delivery and that's why we have to move the cursor to here which means that in this case our best approach is to deliver three one instead of two three one okay and so that's gonna be our basic approach you know to do the greedy plus dp and i'll just try to start coding here you know so the first thing we have lines of boxes and the dp right so dp we have a system.max system.max system.max size right and then m plus one so at the beginning right we have dp zero equals to zero right and then we have a weight is zero well weight equals to zero and then we have a trips equals to two so because the two means that we have to uh for each of the trips we have to go come back to the uh to the storage to pick some boxes and then go back to the first port that's it's going to be a additional two chips here so and so the way we're doing this kind of like greedy approach is that we're going to use a like sliding window approach so we're gonna have a left and equal to zero and then we have like a four right so this is the one the way we're doing the sliding window it means that you know where with the current is the corner right here and from the corner right it means that we are trying to deliver from the corner right here we're trying to deliver the right one uh we're trying to include the right this box and with some other boxes before us and we're going to make that one delivery so with the current right cursors we're going to increase the boxes right with the right cursor and then one right because the boxes has two parameters and we're using the weight here and so with the current one and we're trying to see if the current and what how what's going to be the trips for this so the way we're calculating the trips efficiently is the if the box is ready for the boxes right if the current boxes is different than the previous one okay and it means that you know the uh we need to make one more trip to deliver the current box from the previous previously approved port all right so that's why we have a box minus one then zero because we're comparing the port right then we're doing like chips plus one but uh since we're starting from zero right and we are we cannot go back to zero minus one that's why we have to uh do a right to a check if the right is greater than zero right then and off and then we can do a right minus one so that's that right i mean if the current box is different than previous one right need to make one more trip and i know and now what the uh the next one is the sliding window one right we have to maintain the sliding window right so basically the wow the first one is this right so if the sliding window the length is it's not great it's not exceeding the max of boxes that's going to be the uh our first limits here and second one is the weight it's not this current weight right so in this case we're going to do a what we're going to shrink the sliding window right so here i'm going to try i'm implementing the very basic gradient approach which means that we're trying to take as many boxes as possible right so now the weight will be what the weight will be boxes left one right so that's gonna how we decrease the weight and we're also gonna try to decrease the uh the trips so the trip is like this right so if the box is same similar as how we increase the trips and if the box is of left and zero it's not equal to the boxes of the left plus one zero so why is that because the we're trying to take out the boxes from the current sliding window right because we have this is our sliding window and this is the box boxes we're trying to deliver right and that's why we have to do a left plus one check because we're comparing the current one we're trying to remove from the ones uh still in the sliding window right so if they are different then we can decrease the trips by one right so and then in the end after we have sliding window here you know the way we're updating our dp is like this so with the current one we are delivering the current one so which means that since the definition for the uh for dp is the uh and to deliver everything that's starting from and let's see and actually since we're using like the uh the zero base here because it's easier for us to find the uh the boxes not the one base in for the dp sorry i think i forgot a equal sign here you know usually we do what we do a dp right do we do a dp from what one to uh one to m plus one right and that and then we can simply use the dpi here but since here we're using like the uh the left and right pointer just to make just to be too easy uh make it easier for us to look through this one or we can do this you know or we can do a we can make this one like a dp here but ins then we can but when we find the boxes we have to do a right minus one that'll be a little confusing that's why i'm using we're using like a left and right with zero base but then since the dp is one based right so we have to do what we have to uh write plus one right and then equals oops equals to a dp left right so we're basically we're saying that so this left is our basic is our best approach to pick and then we have a trips so any and in the end we return the uh the dp minus one right so which means that we to store to deliver all the boxes how many chip chips uh trips we need but like i said this is just a like a great like a naive grady approach right and we have to make a little bit modification like i said you know we have to check we need to keep moving the left forward or left is smaller than right and the dp left is equal to the dp of left plot a plus one so this one means that you know if the current if the left if the uh the left one the current cursor one can be uh or where or it's kind of always be alive or the left class one can be uh where the next one can be include within the previous one please previous delivery we have to move we have to make sure that one is included in the into the previous delivery that's why we also need to move this left cursor forward if this dp is the same otherwise if we don't do this our current trips might be bigger than we anticipated and that's the uh the whole implementation if i run the code i think oh there's a oh there's like the uh colon here accept it boxes okay view typo here yeah so and to the time complexity i mean it's o of n right because the left always moving forward even though we have a while loop here and each element will only be visited twice that's why the time complexity for this is often yeah i'm i mean just to just for a quick recap right so the basic idea for this problem is the is a dp where the dpi means that you know the uh to deliver the first ice boxes what are the minimum trips we need but since we have a pretty big constraint we cannot use the naive o of n square dp solutions and we have to find a better approach and the way we are doing it is we are like doing like a gradient approach so which means that from the current position which is right we're trying to load as many boxes as possible while maintaining some conditions which means that we are not going to include anything that has that can belong to the previously delivered and so here's how we maintain the box it the sliding window and then this is how we imple uh maintain the uh make sure we can give as many boxes as possible to the previously previous delivery because the dpa left is equal to the dp left plus 1 it means that by giving this one box the previous delivery it will not increase our final it will not hurt our dp value instead it will help us to reduce the trips by maintaining the first part so actually there are it's kind of a too greedy concept here yeah and that's how we uh solve this problem and it is pretty hard so okay let me know what you guys think and thank you so much for watching this video and stay tuned see you guys soon bye
|
Delivering Boxes from Storage to Ports
|
the-most-similar-path-in-a-graph
|
You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a **limit** on the **number of boxes** and the **total weight** that it can carry.
You are given an array `boxes`, where `boxes[i] = [portsi, weighti]`, and three integers `portsCount`, `maxBoxes`, and `maxWeight`.
* `portsi` is the port where you need to deliver the `ith` box and `weightsi` is the weight of the `ith` box.
* `portsCount` is the number of ports.
* `maxBoxes` and `maxWeight` are the respective box and weight limits of the ship.
The boxes need to be delivered **in the order they are given**. The ship will follow these steps:
* The ship will take some number of boxes from the `boxes` queue, not violating the `maxBoxes` and `maxWeight` constraints.
* For each loaded box **in order**, the ship will make a **trip** to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no **trip** is needed, and the box can immediately be delivered.
* The ship then makes a return **trip** to storage to take more boxes from the queue.
The ship must end at storage after all the boxes have been delivered.
Return _the **minimum** number of **trips** the ship needs to make to deliver all boxes to their respective ports._
**Example 1:**
**Input:** boxes = \[\[1,1\],\[2,1\],\[1,1\]\], portsCount = 2, maxBoxes = 3, maxWeight = 3
**Output:** 4
**Explanation:** The optimal strategy is as follows:
- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.
So the total number of trips is 4.
Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).
**Example 2:**
**Input:** boxes = \[\[1,2\],\[3,3\],\[3,1\],\[3,1\],\[2,4\]\], portsCount = 3, maxBoxes = 3, maxWeight = 6
**Output:** 6
**Explanation:** The optimal strategy is as follows:
- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.
- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.
- The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips.
So the total number of trips is 2 + 2 + 2 = 6.
**Example 3:**
**Input:** boxes = \[\[1,4\],\[1,2\],\[2,1\],\[2,1\],\[3,2\],\[3,4\]\], portsCount = 3, maxBoxes = 6, maxWeight = 7
**Output:** 6
**Explanation:** The optimal strategy is as follows:
- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.
- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.
- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.
So the total number of trips is 2 + 2 + 2 = 6.
**Constraints:**
* `1 <= boxes.length <= 105`
* `1 <= portsCount, maxBoxes, maxWeight <= 105`
* `1 <= portsi <= portsCount`
* `1 <= weightsi <= maxWeight`
|
Create an array dp where dp[i][j] is the min edit distance for the path starting at node i and compared to index j of the targetPath. Traverse the dp array to obtain a valid answer.
|
Dynamic Programming,Graph
|
Hard
| null |
1,572 |
Hello hello everyone welcome to my channel it's all the best problem metric join them for giving on that metric ton in directions only in 10 of all elements of obscurism do subscribe my channel like 102 and finally Bigg Boss ko security fiber se 10 - 151 - 1090 for security fiber se 10 - 151 - 1090 for security fiber se 10 - 151 - 1090 for boys and the key and minus one should be forced to have to time maaf mein daal denge is of matrix size half element which is the to do subscribe my channel like this and accordingly a code simple subscribe to that and let's some business live from zero Do in its processes and a that I lashes and half inch plus land simply prosperous more plus seat matrix of - unmarried com The Video then subscribe - unmarried com The Video then subscribe - unmarried com The Video then subscribe to the Page if you liked The Video then subscribe to I Saudi Tips or Cutting Prosperity Code that and accepted for The Time Complexity of Dissolution Enjoy Jasbir Topics and Space Complexities and Sorry Flagmarch Solid Vidmate Channel thanks for watching
|
Matrix Diagonal Sum
|
subrectangle-queries
|
Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
\[**7**,8,**9**\]\]
**Output:** 25
**Explanation:** Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat\[1\]\[1\] = 5 is counted only once.
**Example 2:**
**Input:** mat = \[\[**1**,1,1,**1**\],
\[1,**1**,**1**,1\],
\[1,**1**,**1**,1\],
\[**1**,1,1,**1**\]\]
**Output:** 8
**Example 3:**
**Input:** mat = \[\[**5**\]\]
**Output:** 5
**Constraints:**
* `n == mat.length == mat[i].length`
* `1 <= n <= 100`
* `1 <= mat[i][j] <= 100`
|
Use brute force to update a rectangle and, response to the queries in O(1).
|
Array,Design,Matrix
|
Medium
| null |
1,519 |
Hello friends, the name of the problem which we are going to solve today is Number of Notes Hindi Sub Tree with the Same Level as a Possible. If we first understand the problem statement, then in this problem statement we have been told that a tree has been given to you with And it's number from CO2 end minus one Okay so from late if I have any end given fetch were before I'm almost the first thing is that we are told that it is the tree not two binary tree so this junction So don't keep that brother it will be a binary tree ok then if there is some ink 125 in the support then I make a career of fine oats so let's mine is something like this Ateam it is not necessary that it is a binary tree oh 2012 3.55 One number of the note was made and the other 2012 3.55 One number of the note was made and the other 2012 3.55 One number of the note was made and the other number is 024, okay, now there is a condition in this, what they have said is that whatever will be your route note, whatever number will be there, it will always be there, so we will definitely give it, okay, rest then you do whatever. I am worried about how you can number the notes. From one, I made it one, made it two, okay, make it three, not three, I fix it, then fold it, then the rest of the notes can be numbered in any way, but which There is a root, it will definitely always be there, okay, so we have been given a tree like this apart from this note number, every note also has a level on its side and where does the value of that level come from, I will tell you that apart from 100 history, we have extreme Its name is also given under the labels and its length is And the number of notes is as difficult as the question is given in the solar charger this BBC Earth is well developed length Amazing so if I induce it through this I want this third on earth because Every chapter, note number, subscribe to it and similarly, the character artist on the first index, no one came into being, then per Jagna and it will be completed. So, in this way, every note of ours has a level side also. Okay friends, we would have talked till now, we have been given in the prostate, now we have been asked to talk in the prostate, now with the problem, they have been asked that what should you do, record every note in such a rude manner, so what. Do you mean by the apps If I consider zero as root then this is all my experiments ok If I consider them as root then this is all my experiments So I have just told them that you must subscribe to every note and tell the value of how many notes every week. This problem has been asked. If the Queen of Clear will not be clear, then I extend this example. So, first of all, if If you have this note then I can also become all these things that I can make every note a root owner then my answer which will be the glue now we are here and five so subscribe to our channel 1234 The value of the accused element is Now he is saying how many of these notes are there whose value is equal to the root level. If I am assuming that here is the value of the level, then how many such notes are there in history whose value is equal to the root level? If the value of level is then how many will be 123 but if this side suyas08 is considered male root, then in that chapter, from such notes whose level value is equal to light weight for the root note, okay, on that side, the value of wave element is number one. So now I have got all this done then how many notes are worth out of these so that and this are the answer to this okay you now I am note number two if here then in this note means how many of the school notes are worth So for similar and this will populate from the flight and this is to return to us in the morning this Bluetooth solution I want to pay attention to one thing when I said that you have been given a job so that too we have appointed such a node in which that There will be 108 numbers and we have been given a lot of skin, so if I subscribe to this channel, then he said that by subscribing, the team inside from Amazon is the same from Amla before 0240 4 and 108 you give us tree basically in this list a gift. It is given and one thing to notice is that if we write it here as directed, then it does not make any difference and it is not necessary that if you go to any other place and in this way we subscribe. Subscribe Hello friends, first of all, as I told you a little while ago, we have been given ready-made training, we have been given bus and ready-made training, we have been given bus and ready-made training, we have been given bus and notes and apps, we have been given dry and possible how to create a representation, so with this information, how can we You can represent the connected days from the side, then definitely subscribe, while maintaining the list, all those notes can be included in the list like we have given the example, if I subscribe, I will make 25 place 302 34 points, this every note is an addition list in the district. If I tell you, if I see the Gurjars, then which notes are the addresses for zero? 1234, then I will add Vansh two and plate in the list. Okay, now which other two legs do I have in the admission list for one. Do you understand the meaning of which notes? Actually 180 is also stone, so I will maintain 043 like this, otherwise I will do 2010, guest revenue and 110, again in this way, I will maintain every appointed list, subscribed and ticket, this is our adjacency list representation done, Monday of the tree, we and actually The situation was, one thing to notice in the list is that there is a little bit of date here if you look, it is that if I because of this, passengers and appointed, then this information for 20 through the union means for the solution for both the maintenance If appointed then it is important to keep in mind that you maintain the list that there is information in the war. The house has understood that the information of notes and the quizzes given which can represent agency list. Now after this we actually solve the problem which is We have been asked a question, I am on your show, now I have taken this slightly increased example so that things are more clear. 100 What are these, we have to do this answer base plate, weight and this element, Hare limit, if I subscribe, whatever number. One is, what is formed by considering it as root, how many notes are there in that root note, how many notes are subscribed in that root note, that is, how many notes are subscribed in the war, then it means the value of each element, in this way, my volume is the first solution to this problem, which involves thinking too much. It doesn't matter what I will do but more so I will keep an oil tanker on this and subscribe from here so how can I do that if we talk about it then I subscribe here subscribe so I like this so I have given this here two good Okay, there is some controlled here, there is nothing here, then there are so in the west, so we know that if I did one and a half possible on zero and it will let you know whose value is given by Tehseen note, then I write through here. Now if we talk about the possible up index, then I have given the value of one note, so then I this from here I subscribe for this so this is this and here and subscribe for this then this is nothing else 1460 so in this way I can rate my answer as one plate and add ginger in it. This is a very simple solution. You do n't have to think much, it is a perfect solution. Okay, so let's add this solution. So, I will add more to the solution. We are doing one difficulty on each note. So if it is difficult, it has time complexity. If we have one for us, then if subscribe and subscirbe, I am on every note, subscribe and refill, we can subscribe and so our time is getting better. Okay, so now this is the solution. If I code this solution in an inquiry tone and submit it, then I am going to exceed the time limit, so it means that my solution is correct but it is not optimized for this. We are better than this. If we can do something, then we will see how we can set this to our solution. If I close the channel subscribe to my solution, then we can note this. Okay, so I want to do the first plate of the index, so I click here and subscribe. Then Loot Subscribe, here we subscribe this channel and other subscribe, I am coming out but different information. It is the same thing that you have to make tea and you go to the shopkeeper, first he brings the far away. You come home from there and then you remember that there are tea leaves left, you plant the tea leaves, then you come back home and then you remember that there is sugar left and it will be torn, so how much time will it take for you to make tea, so you go to a shopkeeper and get milk. If you want tea leaves and subscribe, then how quickly they can be applied in our body also. Every note that labeling may be different, we will add and here whatever language Jaipur one character, we will tell how many accounts of that Remix each character. And anyway, there are 26 alphabets in English, so this is not such a big value, so I take an example in the sense of time basis, but I will call only one birthday wish, it is fine from the root, so I made it difficult here, I ask them. Brother, tell me how many 'A' characters are there in my left and right subri and what are the how many 'A' characters are there in my left and right subri and what are the how many 'A' characters are there in my left and right subri and what are the comments? Okay, if you have any difficulty on this at home, then zero will ask this in your life, tell me brother, how much is the account of each character, so it is 151. Kayan will say, wait, I ask my face, then he will ask his fans first, then this one will ask, tell me how many characters are there in each account, then this one will say, okay, I hope so, but if it has a channel, then first of all Will your own first plate okay so if this if I will update off an inaugrate very index that will be the same delivery on a software consider ugly tu four index after which it told your feet look this is which is 2030 just a One and a half 23 billion that your referee is going to give you a dime, he told it to his feet, then he would say, okay, I want my rights tight, if I say this, then he would ask his ride traveler to tell me his salary, this is also the Rights Act. If there is only one note then first of all leave your value in the guide and then he will see how many such notes in this week Sachin's value is also 19 please so we will set the tax then rest your feet I do n't know how you can use your Jio I felt that the information would be available soon and I would like to get as much as I can in this week so that I can get the loot of Rs 250 plus the information above and will be given to my parents as well, no matter whose parents I asked. It was said that one is coming from here, this mandi bolte or and he also has one of his own best from here, it will be two also, so he told his parents that brother, this is your life, you are going to get one D and two also. So you will definitely get OK, now if I ask about your ride again, then if you ask about your life, then it will say that I, my uncle, we, then it will come to its left first, then it will be a chapter of the same note due to similar idea, so it will come to its left first. There is only one note which can increase the rate of closing the inductive potato, so it was closed and then he told his feet, look brother, you will get this one, your life is like this, whatever he asks from his right channel, then this He will say, look brother, first I will break mine, there is only one such note, given its value, leave this minute in this week, after that I told my feet that brother, you will get meat in one lead, now how many do you want? There are such notes which have this after the level of Jin, so here even an inch was baked from here, which kind of nodal is it itself, then it will keep the value in seconds, Vansh, now it will tell its parents that it is a in your right subri. It is only one given and one egg white is also sure nodal this kiss momentum this is just treatment restaurant so this is subscribe for me and one more so this week the value of three notes is ours in this way we saw the welcome of Andre on If you go, earlier I was making difficulty on each note to update this answer, know the benefits, but now I am updating only one birthday wish call, survey here, so this seems to be a quite optimized solution to me, compare to What I had seen earlier, so if our solution is satisfied, then quickly let Suraj see this work. First of all, we will use the list of apps given to us by Amazon in the factory, so first of all we will represent our entries in the list. subscribe this need to focus, if we want to wish a birthday then we click then subscribe for the subscribe number and second one, so now we make school subscribe our feet and its length will be 126 because in English 2605 is like this then Now this is done, so what are they doing, this intern is speaking to them in his own way, so for this, on which it is welcome to make a face call, so they are, therefore, whatever account this is, that is also of the festival character, that is our We will add on the account that we will add this is going to send the account back up, so right now I am just setting the account plus equal to two, this is a festival, these are the benefits of addressing at comedy, it has leveled back up, it has just noted each of its additions. Now I have to add the account of the character myself, first of all, let's take out that character, let's take out those five and what will be the labels and the character of that note, which is therefore the number of the bus stand. Whatever is there, I have taken it and we will add it to this account. The account was the most S-character one plus campaign. was the most S-character one plus campaign. was the most S-character one plus campaign. Why did we do this? Sale is 241 tractor, I want it, so if we subscribe in this way, then subscribe, this is the note. Later when all this is done, now he has to return this entire account to his parents, so we return this account, so in this way we have done this is our code, this is our solution. Okay, if it's clear then we can do anything with it quickly and in the morning, this is our problem statement, these are some examples, so explain the problem statement and here we have to code, so we as we discussed. We have been given a notice, disturbance has been given and labels have been given, so first of all, I will chart my one answer 'M', after answer 'M', after answer 'M', after declaring it, I will return it, okay, so what will be its size, which I have given, okay you now Because the list has been sent to us, I will use the adjacency list for its representation, so I declare a Adjacency List, Uber List, Houzz List of Anti, under that, I take its name as Adjacency School List of, hence its size also. Why will it happen to Om N because for every turn I add an edition C list maintainer from this note to the size of N mobile and I add it so that I don't have to deal with taps so it's like Why am I a list daughter, I have set it, now we update it, so that the list will be plate from there when we do our stomach, so let's tree to great point, well, I am representing such a thing, so here we Every joint will do and adjacency list dot get that chief 0 that daughter and chief hot one and by the way we will have a rumor of get in a pencil list and add or 10 the subject matter I am saying that if back baby then I am the same I take out the agency country and cut B in it and take out BK Jain and put a weight in it. Okay, in this way our adjacency list is up and our representation is done. Now we have an account in the form of adjacency list. What we have to do is now we have to call device which I discussed so what we will call whatever is the route which is 10 and we will pass these labels to it okay soil before I want to the implementation of defiance one after or common very important Have to keep in mind that like what is there in Edison list, if we find it easy then in the existence there are BA and BCom in the Apps NC list, in the agency list there are some difficulties in Lets and SSB, then we do not have to go back from the middle right. If this is related, then to share it, we keep another set which will come, which note solitaire I have told, we do not have to go back, okay, so I have made this visit and clear, I believe here. I am retreaded full to new is set a teacher Jai Hind ok and rate now we give this face increment so this is first of all refer time anti going to return because it basically tells what is the amount of each character So the edifice is done, this is the number of the note, this is the parameter and serial level, okay, the first thing I will do is add it to the widget, I have deleted this note, okay, now what will I do, I will add it to the widget. The account is right, who will tell the electricity of every character, so this is done, you went 126, okay, now I will tell on every adjacency and note, I will do traditional in the morning, how will you get Edison feel list dot get note, so all the Edison and suspended of this note. And if it is not visited then it means that visit dot hour from this life existence note we do not visit first that this note is put Andhra keep in mind then we will do this thing that what we will do that we will make difficulty on this then in tiffin we will get one again. The account of adjustment note will come, hey, who will tell every character, now remain so here, I call madif this, fat like here and the labels are back, I do this, and whatever we have got, we should put it on our account. To add right, I want to say z10 S6 plus the count of high i plus equal to hand whose cent of account will come, so in this way we have created the account of all the recent notes of ours, here we have this in the last Now we have added that own note, sometimes there is an account, we have to bread it, right show that, I look at the character first, which character is there, then those labels, don't care reduce, whatever is the number of this note, it will depend on the same index. Labels Patience Note Okay and then we will add this plus character of CH- in our account, so add this plus character of CH- in our account, so add this plus character of CH- in our account, so whatever is the value of this note, label adware, its account, we have increased it by one and the same, whatever is its account, that is in our answer. If you want to point also then answer of no renewal to account of serious - This festival of character was updated, - This festival of character was updated, - This festival of character was updated, after that we had to give whatever account we have to the parents so that they can glass it, then I return from the In this way, we solved our deficit. Treatment is done, now that one birthday wish has been completed, whatever answer we have has been completed, so all we have to do is return it. If the return is furniture, then yes, it is complete. By the way, let's run it and see whose example test. What happened with OK some compilation is lost OK spelling mistake is visited that let's have a plate so I Answer Expected Answer OK I am feeling semi let's submit let's see who will be this of our solution in the morning Accepted Now ok then let's go now Let us discuss the time complexity of our solution, so we are making the adjacency list of pan size. Fennel is fine and one thing is important to keep in mind that if we have been given Android country then there will be administrators of the office, then this race Whatever is given to us is ₹10 off this race Whatever is given to us is ₹10 off this race Whatever is given to us is ₹10 off and it is fine, when I am updating the agency list, its time complexity is maximum movie of N rate, then the next operation is difficult, when we do the difficulty on the first note, its time complexity is That's n so it's off sum and even though we have a for loop inside it but it follows up a constant for loop of 826 characters so this enemy is 11.62 and expert 911 If we this enemy is 11.62 and expert 911 If we this enemy is 11.62 and expert 911 If we look at the time complexity of our solution then we would have written it open. Now let's see its space complexity. Okay, so first of all, I have made this adjacency list, so if I look, there will be two entries for each H, right if it is between then Anode 's. BK entry in the adjacency list, if there 's. BK entry in the adjacency list, if there 's. BK entry in the adjacency list, if there is a B note which will have one entry on the list then it will be raw to one, our size will be the adjacency, its sir, it is first off India, it does not know its program, so it is us, we want two individuals were gone over for the pendency list. After that we called on these given faces, then on these given faces, our maximum date can go till the end and on every date, we are making the interior like this: and on every date, we are making the interior like this: and on every date, we are making the interior like this: Off Side Twenty-20 Expert Off Side Twenty-20 Expert Off Side Twenty-20 Expert Constant Value 100 If I go to this piece If I see then it will be now we will be off enter device so similar to time pass complexity also off my solution that is going to be I will write something that n tomorrow morning Desh Sadhvi Complaint and this video if I am successful in explaining this solution to you If yes then please like this video, comment and if you have not subscribed yet, then see you in the next video with a new problem, till then bye.
|
Number of Nodes in the Sub-Tree With the Same Label
|
minimum-subsequence-in-non-increasing-order
|
You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node with the number `i` has the label `labels[i]`).
The `edges` array is given on the form `edges[i] = [ai, bi]`, which means there is an edge between nodes `ai` and `bi` in the tree.
Return _an array of size `n`_ where `ans[i]` is the number of nodes in the subtree of the `ith` node which have the same label as node `i`.
A subtree of a tree `T` is the tree consisting of a node in `T` and all of its descendant nodes.
**Example 1:**
**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], labels = "abaedcd "
**Output:** \[2,1,1,1,1,1,1\]
**Explanation:** Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).
**Example 2:**
**Input:** n = 4, edges = \[\[0,1\],\[1,2\],\[0,3\]\], labels = "bbbb "
**Output:** \[4,2,1,1\]
**Explanation:** The sub-tree of node 2 contains only node 2, so the answer is 1.
The sub-tree of node 3 contains only node 3, so the answer is 1.
The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.
**Example 3:**
**Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[1,3\],\[0,4\]\], labels = "aabab "
**Output:** \[3,2,1,1,1\]
**Constraints:**
* `1 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* `labels.length == n`
* `labels` is consisting of only of lowercase English letters.
|
Sort elements and take each element from the largest until accomplish the conditions.
|
Array,Greedy,Sorting
|
Easy
|
2316
|
1,832 |
See, we are going to question in this video, check IF D sentence of 1832 code, this 10 gram pen gram is this sentence in which all the letters of English alphabets i.e. of English alphabets i.e. of English alphabets i.e. from A B C D to S are present in this sentence. Okay, so what is it? It is very good in pen graph. Now as this beautiful word is written in front of you, I have to check whether all the letters from A to C are A. Now I have checked that it is A, so what does it mean? Is it true? Have to return? Tell me the second sentence as well. Here is the lead code written in front of me. Is it true that all the letters are not coming in it obviously? Then it is a very simple question to return water. When we start, we put a loop, isn't it a loop as soon as we start? Let's put it, okay, I am writing, I don't know what I am doing, okay, take care Karan, make it equal, you are doing this, I have written the loop till now, I am looking at each and every character in this sentence, okay now. Can I do one less, we can do it, let's take a set, okay, let's take the set and we will put each letter in the set, now we know what we do in the set, there are unique values lying in the set, when Puri's When the entire values lying in the set, when Puri's When the entire values lying in the set, when Puri's When the entire string is traversed, we will check whether its set length is 26. What is the meaning of 26 length means that all the letters in it have been hung. Why from 26 because mother, take this string, this is my A Okay then B C D I F till C Okay now I look at all these i.e. what is A here, all the i.e. what is A here, all the i.e. what is A here, all the letters are A. If I look from here from A B C D I F to S all the letters are A. There are 26 of 26 but here the extras are still coming but when I will traverse it and what is the property of the set in the set, what is the unique value, then obviously it will be thrown once and then it will not be thrown the second time because in it If it does Exist Already, then finally what will be its size? It will be 26. We can define the set by declaring it and write its name. Set is equal to the new one. Set is fine and what else will we do? Nothing to do, nothing to do. Set. I will keep adding it's fine just like you add it to the list, keep adding it, you don't have to do anything else, then finally check whether its length is 26, if it is 26, it means it is very good, true, return it, I will return it. Dot size sorry set dot size equal 26 what does it mean that if it is 26 what is its size what does it mean pan gram also means return true let's run it is accepted submit everything will be soil also no problem No, ok, now let's see what will be its size, what is space complexity, Big of 26 or say Big of 1, which stand is space complexity and what is the time complexity is Big of N, this is done with the help of set, we can make one more We can reduce it to one 26 length, okay, there will be water everywhere in the beginning, then we will iterate, okay, we will run the loop on S and S, okay and on every value, I will tell you the value of 26 length, I will show it once. This was from you that 26 length cake, take it, in which there are water falls everywhere, there is zero, take some mother, okay, zero mother, let's take 260, it is in front of my eyes, okay brother, now I have some string, mother, take it. A B C is okay, I will do a loop on this A B C. Okay, what does A mean, index zero, B means index 1, C means next, you are okay and if we take mother, here comes P S, A B C S. What is the meaning of 'S' last i.e. 25? Okay What is the meaning of 'S' last i.e. 25? Okay What is the meaning of 'S' last i.e. 25? Okay then what will I do. As soon as 'A' appears at zero then what will I do. As soon as 'A' appears at zero then what will I do. As soon as 'A' appears at zero position, 'One' also appears at the first position, 'S' appears at position, 'One' also appears at the first position, 'S' appears at position, 'One' also appears at the first position, 'S' appears at this position, 'S' this position, 'S' this position, 'S' appears in this question, then again there is a loop in the gesture. I will check that brother, all the ones are there, so I can do it or whatever you return, okay, one is set, now let's do it, okay, let's give an example of the set statement, okay, let's give an example of this, we have to write it here, okay. Hey care, I am coming - A - A, I will tell you care, I am coming - A - A, I will tell you care, I am coming - A - A, I will tell you what it means, it is equal, you are true, let's copy it, what does it mean, let's take mother, S, which is my A B C, okay, what will it mean, let's take s.k carat zero mother, what will it mean, let's take s.k carat zero mother, what will it mean, let's take s.k carat zero mother, that is. Har is written A - A is ok, that is. Har is written A - A is ok, that is. Har is written A - A is ok, we have heard it brother 2 - 3 had heard 3 - 1 had heard we have heard it brother 2 - 3 had heard 3 - 1 had heard we have heard it brother 2 - 3 had heard 3 - 1 had heard what is this character - character what does it what is this character - character what does it what is this character - character what does it mean its Eski - its ok its mean its Eski - its ok its mean its Eski - its ok its today's 97 - 97 = 0 i.e. 0 induction It is written today's 97 - 97 = 0 i.e. 0 induction It is written today's 97 - 97 = 0 i.e. 0 induction It is written here i.e. and off zero is here i.e. and off zero is here i.e. and off zero is equal, you are doing the same, this is what I was shouting brother, will the corresponding index of A be kept at zero or one or true, okay brother A, I understand. Gaya, there is no problem, now let's see the second character, okay, take this mother, I have written True here, I have written True A on True A, and everyone is covered in water. Okay, very good, then A will go here on the beat, brother B - A. B's 97 98 - 97 kitna bhai a brother B - A. B's 97 98 - 97 kitna bhai a brother B - A. B's 97 98 - 97 kitna bhai a very nice maja a gaye ok i.e. is very nice maja a gaye ok i.e. is very nice maja a gaye ok i.e. is A R of one is equal to you i.e. the second A R of one is equal to you i.e. the second A R of one is equal to you i.e. the second position will go true A. Okay, so whatever string is there, we will make it true here for all the cactus. We will check at the end, now see, like here, ABC is there, only three were hit, the remaining falls are 26 - 3, the remaining 23 are 26 - 3, the remaining 23 are 26 - 3, the remaining 23 are water, so obviously our answer here will be water. It will come because this is not a beautiful string, it is not 10 grams, okay, let's go, it is very good, okay, this has reduced, ours is very beautiful, it has reduced, again, take one loop and will run the loop, in what will we run now, I will run it, friend, we are taking current mother. The name of the current variable is 4:5 in ARR. Ok, if the story is also 4:5 in ARR. Ok, if the story is also 4:5 in ARR. Ok, if the story is also messed up, that is, if any part gets burnt, then return it. It is a simple thing, ok, finally 26 likes. We are looking at it, we are running the look in it, if any part of it was too much, please return true, okay brother, let's see, it is making noise, it is going on, let's submit, let's see, it has gone very beautifully, please accept. The video has ended, it is very good, the time complexity is big and the space is also constant, what is there in it is a little lighter, it has reduced, hey, we are taking the set, we are not taking it, okay brother, you can find the link of the next video here. Thank you very much for watching your video, ok and you will find the discord link in the description, very nice thank you
|
Check if the Sentence Is Pangram
|
minimum-operations-to-make-a-subsequence
|
A **pangram** is a sentence where every letter of the English alphabet appears at least once.
Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._
**Example 1:**
**Input:** sentence = "thequickbrownfoxjumpsoverthelazydog "
**Output:** true
**Explanation:** sentence contains at least one of every letter of the English alphabet.
**Example 2:**
**Input:** sentence = "leetcode "
**Output:** false
**Constraints:**
* `1 <= sentence.length <= 1000`
* `sentence` consists of lowercase English letters.
|
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
|
Array,Hash Table,Binary Search,Greedy
|
Hard
| null |
310 |
in this problem we have a graph which is also a tree and we have to find minimum height trees so let's say you are given this graph or this tree so what is the property of tree all the nodes are connected and there is no cycle so between any two nodes there will be a unique path and also if it has n nodes it will have n minus one edges for example if we have just one node it's a tree you add one more edge and one more node so these together come so when you add an edge one node also needs to be added so now it has two nodes one edge again you can add one edge and one node it's still a tree so three nodes two edges and so on you can keep adding in pairs one edge and one vertex or node provided you don't form any cycle so when you form cycle clearly you will have more number of edges if you add one more edge you will have more number of edges so if you maintain this and the graph is connected then it will automatically be a tree so uh in this problem if we have n nodes it will have level from 0 to n minus 1 the level of vertices for example in this case we have 0 1 2 3 so 4 nodes are there now we do not know uh from where which would be the root node among these four such that its height is minimum so height of a tree is so there is a notion of root in a tree and there are different nodes this is not a binary it's a generic tree so a tree can be like this so if this is the root the height of this tree is one two three the farthest leaves there are many leaves but the leaf that is farthest is this one and it's at a distance of one two three we count the number of edges so the height of this complete tree will be three the maximum the farthest leaf so these are the four node this is the graph given to us not the tree we have to find the tree such that the height is minimal so if we start make this 0 as the root its height will be 1 2 if we make 1 as the root so let's say this is one and these are the remaining three nodes so if this is the root these all are at distance of one these three leaves so height in this case is one and there can be in this case there is just one node for which the height is minimum but in general there can be multiple nodes with ah minimum height for example in this case let us say this is 0 1 2 now if you make 0 as the root it will be 0 1 2 3 so its height will be 3 so for 0 it's 3 if you make 1 as the root then we have 0 on this side 2 and 3 on this side so height is 2 for 2 also it's a symmetric case again height is 2 for 3 it's 3. so in this case 1 and 2 both can be roots such that the height is minimum and in fact you will either have one node or two nodes so let's see why is the case so first of all when we are trying to find the nodes from where the leaves are closest so what will be those nodes those will be the nodes uh which are within this tree so if we have a big graph some nodes will be in the on the edges some nodes will be in the center so if we pick the nodes in the center the tree will be more balanced there will be the different branches will be somewhat balanced because we have picked some central nodes but let's say you pick one extreme node which is which has just one connection so this will ultimately be a leaf node if you start if you make any other node as the root this will be a leaf only case when this will not be a leaf will be when you make this as the root in all other cases it will be leaf because it's connected to just one of them one of the other nodes so if you start traversal from these kind of nodes or if you make these nodes at the root then height will be large but if you pick some of the central nodes it will be more balanced so this is the idea of this problem in fact a naive solution would be that you do a dfs from all the nodes you can also do bfs but let's say we do dfs so make this node as the root and start dfs from there when we start dfs from here the height is initialized to 0 and when you travel this neighbor you make height one when now its height is one and for all its immediate neighbors it will be two and next it's three so you see bfs also can do the job but writing code for dfs may might be slightly easier you will pass additional parameter height and for all the nodes adjacent to u we do dfs so we already know the height of for this one here we will pass h and here we will do h plus 1 in all the nodes so just passing one extra parameter in the standard dfs will do the job and we can do this dfs n times so we have n vertices so n dfs and each dfs takes of the order of v plus c v is the number of nodes is the number of edges in this case is nothing but v minus one so overall for one dfs it's o of n for ndfs it will be o of n square so this will work but you see it's o of n square and it may not pass all the test cases so this is a valid solution but not that efficient so that's why we will uh modify uh this knife solution and we are trying to develop the intuition behind what we want to do so if we have a large graph like this if you start if you make root as one of these extreme nodes or the leaf nodes then the height will be larger so we are trying to find the inner nodes so let's say we have just one node in this case this will be an answer if we have two nodes both of them will serve as roots of minimum height trees if we have three nodes then this one is the root node similarly if we have four nodes like in this case we have multiple trees with four nodes so in this case we have two roots in this case we have one root so you can keep trying and you will always find that either we have one root or two root let's see why is the case so now uh let's see uh if we have a tree like this let's take a bigger tree so let's say this is our tree and we are interested in finding the central nodes so these are all leaf nodes so our answer will be one of these some of these central nodes and not the leaf nodes definitely because we if we make these as the root the height of the tree will be more so these all are leaf nodes these will always come as leaf nodes if we pick some of the central nodes as the root this 0 2 9 4 6 these all have a degree of 1 just connected to 1. so if you draw the adjacency list of these 0 1 2 3 4 5 6 and others for 0 it will be just 1 for 1 it will be 2 0 3 7 for 2 it will be just one and so on so you can create this adjacency list representation of the graph and you will see that the nodes which are connected to just one other node will be leaf nodes so if we remove all the leaf nodes let's see we have a generic tree like this we are we have been looking at trees in this manner where root is at the top and we have leaves at the bottom so let's say this is our tree and the height of tree is h and why is that let's say this leaf is at height of h1 this leaf is at a height of h2 this at h3 and this at h4 h5 h6 so if the height of the tree is in this case a max of h1 h2 h3 h4 h5 and h6 so uh these are the different leaves now let's say we remove all these leaves so we remove this one so still the height will be one less all leaves are now gone so the next leaves will be one level closure so all the leaves are gone so now it will be h one minus one h two minus one and overall height will be whatever was earlier height minus one so uh if you make this as the root or this as the root in all the cases this will be these will be leaves so we are not making leaves as the root so if for this node the height was minimum after removing this leaves again this will be for this node the height will be minimum because uh earlier height was let's say 1 2 3 for this node in this case it will be 1 2 3 for this node and if you make this as the root it will be one in this case it will be one two three four for this it will be four and for leaves it will be even more you can write that so now when we remove these leaves for this one what will be the height it will be one two three so from four to it will three from three it will become two from three it will become true so by removing the leaves still these two nodes will be the nodes with minimum heights so removing the leaves does not change our answer so let us run through this example so we have leaves which are these nodes so if we remove 6 9 4 2 and 1 0 still the answer will be same so let's get rid of them now we have a smaller tree what is that is 1 3 5 and we have 7 and eight so the answer for this tree and this tree the answer is same the centroids now against five and eight are leaves so we will never start we will never make them as the root so we get rid of them so let's say we remove these 5 and 8 now we have a smaller tree now it's 1 3 7 and now 3 and 7 are root so we remove them and we are left with 1 so 1 is the root in this case 1 is the answer so either will be left with one node or two nodes so when we reach less than equal to two we stop so how we will solve it we will create the adjacency list representation in this question we are given the edge list and then we check for all the nodes whichever degree is 1 we remove them so we remove them from the graph how we remove them it's list we make it empty and we remove it from all the adjacent nodes and we keep removing until the size of this becomes 2 or less if it's 2 both are the answer if it's 1 that one is the answer so let's see how we can write the code for this so in this case what will be the time complexity so what we will be doing here so first we will scan through this adjacency list and whatever degree is 1 for those nodes we can store them in a queue just like we do for the case of bfs so we store all these 1 2 3 4 5 nodes in the queue and then we pop them from the queue and uh for each of their neighbors in fact all of them will have just one neighbor that's why they got pushed into this queue so for example when we let's say six is the beginning so we pop six we look at what is the neighbor of six it will be just five so in the list of five we will remove six so for all of these five leaves we will remove them themselves from the adjacency list of their neighbors so from 5 6 is gone so effectively this edge is gone similarly uh from the list of three four will be gone so these are broken and additionally when we pop them and we remove them from the corresponding at our neighbors list we check them what is their size of never list after removal if it's one we pop them back we push them back into the queue and we keep doing it until the size of q is two or less so we are removing from edges so these are removed first then five seven and three are removed and so on five and eight are removed then three and seven so what time it will take first of all the leaves are removed are inserted in the queue and removed then we have those many less let's say n1 leaves were there now we have n minus n1 nodes again we have now let's say n2 nodes and two leaves so now it will have n1 minus n2 so we will never process any node multiple time only once so it will take off and time so this will be efficient than doing dfs from all the nodes which was o of n square so let's write the code for this so i will be writing in c plus for java and python i think lead code has already provided the solution you can check there so n is the number of nodes so if it's 1 then its level will be 0. so we return that now we will make the adjacency list so we are keeping an ordered set for the list of neighbors you can also keep list but this set will be more efficient in searching so we are given the list of edges and its undirected graph so both are numbers of each other e0 and even now this list is done now we will create the queue do so whatever has just one never or those are leaf nodes we push them into the queue so while we have more than two nodes we keep processing we keep them keep removing them so we had inserted let's say five nodes into the queue that means there were five leaf nodes so now we will remove them all of them one by one so new length will become n minus l e n l n is length of q or what we can do so we will remove it from the adjacency list of a we will remove this node so a dz then it will be a from the list of neighbors of this node that is a we erase the node itself and then we check what is the number of neighbors for this a so if a dj a dot psi is equal to 1 then we insert into the queue next time they will be removed and we stop when n is two or less and then this loop will end when we have two or less nodes and which are the solution uh so line number 13. and our solution is accepted and if we look at the time we are right here in the middle we can try a few times maybe it shifts a bit so we are still here but we are in the major part of this distribution it can easily shift left or right so i hope you understood the intuition behind why the nodes which are connected to more number of nodes more number of branches those are the nodes that we want to make them as root and for those cases the tree will be more balanced will be more branched and if we make any leaf nodes which are which have just one connection in from those nodes if we make them as root the height of tree will be more and it will be unbalanced tree
|
Minimum Height Trees
|
minimum-height-trees
|
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree.
Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between the two nodes `ai` and `bi` in the tree, you can choose any node of the tree as the root. When you select a node `x` as the root, the result tree has height `h`. Among all possible rooted trees, those with minimum height (i.e. `min(h)`) are called **minimum height trees** (MHTs).
Return _a list of all **MHTs'** root labels_. You can return the answer in **any order**.
The **height** of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
**Example 1:**
**Input:** n = 4, edges = \[\[1,0\],\[1,2\],\[1,3\]\]
**Output:** \[1\]
**Explanation:** As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
**Example 2:**
**Input:** n = 6, edges = \[\[3,0\],\[3,1\],\[3,2\],\[3,4\],\[5,4\]\]
**Output:** \[3,4\]
**Constraints:**
* `1 <= n <= 2 * 104`
* `edges.length == n - 1`
* `0 <= ai, bi < n`
* `ai != bi`
* All the pairs `(ai, bi)` are distinct.
* The given input is **guaranteed** to be a tree and there will be **no repeated** edges.
|
How many MHTs can a graph have at most?
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
207,210
|
17 |
in this video we're going to take a look at a legal problem called letter combinations of a phone number so we're given a string containing digits from two to nine uh return all possible letter combinations that the number could represent so return the answer in any order a mapping of digits uh digit two letters just like telephone buttons is given below so know that one does not map into any letters you can see it's just uh it's just a sign right it's not any represent any letters but you can see 2 represents a b and c right 3 represents d e f 4 and so on and so forth and you can see that 0 is not representing anything right and then the those symbols does not represent any letters as well so we pretty much just have two to nine uh for our combinations right so in this case you can see here we're given a digit in the string so in this case we have 23 this is our digits and basically we're just going to generate uh all the combinations that we can come up with right so you can see here this example we have 23 right 2. in this case 2 has a has b has c 3 has d has e has f so basically we want to generate all the combinations so we're going to have a d a e a f b e uh b d b e b f c d c e and c f right so you can see that we have total of uh six or sorry nine combinations right and we wanna return that in a list of the string okay so and you can also see that we can have a empty in this case if i have a digit in this case the length of the string is empty then pretty much we're going to have an empty list and you can also see that if we have a situation where uh where our current string right is only one digit then we want to make sure that we get them all uh all those digits that are all those letters that are related to this digit uh added on to our list right so how can we solve this problem so this is a backtracking problem and uh if you're interested to do more backtracking problems i do have a playlist uh on my channel where i specifically talk about backtracking and uh basically to solve this problem what we're gonna do is we're gonna use backtracking and basically uh we're going to start at the root level we pretty much for let's say we have a uh let's say we have a string right in this case a b is 2 and this is 27 i believe so yeah 27 and basically let's say we have those let's say this is our digits right and what we're gonna do is we're gonna use backtracking right to uh do a dfs iterating all those decisions that we have right and then do a dfs once we get our combination we're gonna backtrack and then we're going to traverse to another uh path right so you can see here we're starting at the root level and you notice that on the root level we have nothing on our um on our string right and on our combination so far we have nothing so we're gonna do is that because the first character or the first letter or the sorry the first digit is two right so in this case two has two options in this case a and b right and there's also a c there but i didn't do that so in this case we also have a c right there should be a c and something right okay so basically let's focus on this example right so if i have a here in this case two have a so in this case we have we can go down this path right we can also go down this path but we're going to do a dfs to go down this path first in this case if i have uh digit two i have a b c right and then if and then when i when we move on to the next digit we have digit seven and digit seven has also has four options in this case we have p we have q we have r we have s right so we're gonna do is that we're gonna iterate those options and then we're gonna do a dfs in this case currently our combination is a we're going to do a dfs uh down this path right so now we have ap in this case if we have ap right this is one combination and in this case we're going to see if there's any other digits in this case there's none because we're on the digit seven we're on the last digit you can see two seven we're on the last digit so what we're gonna do is we're going to um add the current combination onto a list in this case we're going to have a list a result list to keep track of all the combination so we're going to add this combination onto our list right and then what we're going to do is we're going to backtrack so when we backtrack we basically want to uh we want to reset we kind of want to delete the uh the action or yeah delete the last action that we took in this case the last action that we took was to add this character in this case p right so now we're gonna do is we're gonna remove that character off of the uh off of our um combination and now we have back to a right now you can see we have arrow back to a and a we can go down this path in this case we have a cube right in this case we add q onto our combination so we have aq and now because we're on the last uh digit and there's no more digits left to for us to traverse we're going to add the current combination onto our combination list right and then we're going to backtrack again resolve or restore or delete the last action that we took was to add q onto our combination right so now we removed here off of our combination and then we can go down this path so we have a r right we add our append r onto our combination and then we know that there's no more digits left so we're going to add a r onto our combination right so we have a r we added on to our combination and then we backtrack we restore the last action that we took right so to backtrack we have to restore the last action we took and then we're now back to a and then we're going to add the next character in this case s right so now we add s onto our combination a s we're going to add a s onto our string right sorry our combination list and now we're going to restore the previous uh the previous action that we took was to add s and now we're back to the root and then once we're done traversing all the options we're going to also restore the last option that we took and now we're back to empty and then we're going to go back go down to this path right here right and at the end you can see we're basically traversing doing dfs to all the uh all the path and if and then to backtrack we have to restore the last action that we took and then at the end we're going back to the root right so now you know how we can do this let's take a look at how we can do this in code so to do this in code basically what i did here is i have a table um a character right a digit that has corresponds to a couple letters right in this case two digit two corresponds to abc uh digit three correspond to def right so in this case what we're also gonna do is we're also gonna have an array right this character array is equal to digits dot character array and then we also have a result list that basically keep track of all the combinations that we have so what we're going to do is you can also use a string builder you don't have to use a stack but in this case to use a stream builder right uh in this case if i want to delete the last character it's pretty much a linear time complexity but if we use a stack we can be able to pop the top element off of the stack and this will give us a constant time complexity right so what we're going to do here is we're going to pass this stack into this helper function right and this stack is going to keep track of our current combination so we're basically going to start at index zero right just like here we're going to traversing all the options for this current index for this current digit so when we pass it down to this helper function we're going to have a uh check to see if the current index is out of bound or if we have no more uh digits left to traverse right in this case if that's the case then we're just going to add the current combination onto our result right onto our result list and you can see here we have a function that basically convert the stack to a string and then what we're going to do then is we're going to do it dfs right so if we're not uh if we still have uh if this index is still within the boundary then we're going to do a dfs for all the decisions right in this case we're going to have a current string in this case this current string is basically corresponding to the current digit right we iterate the current string and then we're going to first add this character onto our stack right so and then we're going to do a dfs then we're going to restore the previous action that we took so that for the next iteration we can add a new character the other character right in this case just like here i add a p in this case and then do a dfs down to this path and then when i come back i want to remove p so that i can go down this path and then doing the same thing over and over again until i uh getting all the characters uh that we have in our string right and then at the end we're gonna back to the root level right because uh in this case we're going to keep traversing all the options once we're done we back to the root level and then we're going to return the result right in this case the result is the list that we're going to uh that keeps the caps all the combinations that we have right and this is basically how we solve the problem
|
Letter Combinations of a Phone Number
|
letter-combinations-of-a-phone-number
|
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
**Example 1:**
**Input:** digits = "23 "
**Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\]
**Example 2:**
**Input:** digits = " "
**Output:** \[\]
**Example 3:**
**Input:** digits = "2 "
**Output:** \[ "a ", "b ", "c "\]
**Constraints:**
* `0 <= digits.length <= 4`
* `digits[i]` is a digit in the range `['2', '9']`.
| null |
Hash Table,String,Backtracking
|
Medium
|
22,39,401
|
834 |
reference today that's the sum of distance entry province an underactive that connected a tree with a North labeled zero to a minus one and amongst one ages are given the ice age connects no two edges either and ages I want gather we needed to return least her answer we're also I is a sum of the distance between node I and all other nodes so let's see this example and equal to six and their ages are given that means no the zero is connected that you know the one now the zero is connected to node 2 so on so forth and we return that array let's see the first value how to we get that value that means other distance between there makes the sound the distance between node 0 to all the other nodes then we first a carrot isn't between no there's you know the one there is equal to one and the distance between node 0 to not you this is also one about the node 0 to node 3 we know there will be Q so on so forth we will return 8 so we will care to OC other there you by this way well the booth loss solution will be pickle and square term complexity and I referred this solution and then you may refer to this discussion - okay let's see how do this discussion - okay let's see how do this discussion - okay let's see how do i how do we solve this problem first so we are given the ages usually we will use agency these two to represent a graph the reading is that we came quickly know their neighbor notes by a given node this graph means no the zero is to Connecticut you know the one in to write know that U is connected to know the zero three four five so the first step is to change the graph representation then we'll get the agency sister of this graph there we know it needed to return distance array that means the sum of the distance between I and all other nodes so the size of the distance array should also be an account and that means the size of each subtree which in other way is the total number of the notes in each subtree in this solution we will do twice their first search the first that first search it post older why because when we do post older we can return a value for its for a root node so we can feel the couch array by this way also we can feel the distance array in some way that means we can catch them in each sub tree we can get the sum of distance from each sub tree to the root a node because we can always return a value to its parent so this is the second step the third step is to do a pre order to finally feel that this array in this therefore search we need we can feel all the notes in their tree not only root note so when we finish the post odor we can get to the couch away in the distance this is a given example it's the graph we can represent a graph like this then cause they're mean equal to 6 that means there are 6 nodes in this tree and count one you caught you what that means we only have one node in the tree how to chill you cause 2 4 that means 4 nodes in this tree so on suppose so we can get the size of each subtree and sisters we know that we can get older some through it's a subtree to the current root node so that means after this post older we can get the real value for the 0 node because for the node 0 the Sun from the sub tree you can choose a sound from all the other nodes through yourself so we get an 8 and for this one as it does not have any sub tree so the very 0 the for another 2 in has 3 children so we return 3 and the photos 3 4 5 they do not have any sub tree so the this is currently you go to 0 okay let's see how do I get how do we get a decent 0 we should accumulate other sub tree the distance of this sub tree we accumulate for example accumulate distance 2 plus culture why because the children of this Chu they have the distance to the truth but compared the children know the zero they have one mode these tips for example like the notice tree it's this intruder Chu is one but it's distance between itself to 0 is true so we need to add this culture of it is true that means all the notes in this subtree have he that you are the one mole that's an important part and do not forget when we chew when we try to get a culture I need at you culture root increment by 1 because itself cut one more note okay this is a post odor how about the pre-order you should notice about the pre-order you should notice about the pre-order you should notice that after poster order we get the distance of zero which is 8 then we will try to calculate its neighbors so if we try to calculate distance 1 we know that older notes in this purple area has its distance between 1 and this node is 1 more than the distance between the node 0 to all of these nodes just means if for example is not you it's decent between 0 its 1 palace distance between 1 is 2 so in that you add the culture of color of this purple area so we add the distance root that mean older oh they're notes cuter as the distance to the root then we add as a touch of this purple area because all the notes in the purple area have one less o1 distance less than killed another one so we should add the cut of this purple area and you should notice that the cut of this red area plus this code of power error youcan't um so how do we get the area we use a minus cutter the red area which is code next then all the other notes in the red area should have one less than error then to the zero so we should a - error then to the zero so we should a - error then to the zero so we should a - circle next so that we get the final result okay so now let's write the code in order first we need a graph we use a private ELISA integer all right and there will be distance in the private there will be distance in the couch so first do some initiation initialization so this is where you go to new intern an account equal to new intern therefore every understand and address first so grass I will equal to new array at least okay then we change your presentation of this graph so for every edges graph zero at one because this is undirected graph so II what ad zero then we do first order and their preorder final return this distance so let's write post order we know the route as we do not want you gets a stack overflow in either to quit at some point and we do not want you calculate one edge twice so we need to record the previous node so when we get this next node grass root we are first to compare the next end of the priest if next equal to the preak that means we have a circle so just to continue otherwise because it's a post order so we will try to do that their first ever first suppose odor currently route to note is the next and the previous no that is a route then the distance you see this is distance route we accumulate distance next plus a car next so decent route well accumulated distance next classic up next and cut next sorry this is route should accumulate the cut of the next I finally do not forget sir increment by one because it is self account so let's write so pre-ordered root three the same write so pre-ordered root three the same write so pre-ordered root three the same thing falls every next note draft root if yes you got your proof we continue there is a pre-order so we will first there is a pre-order so we will first there is a pre-order so we will first calculate the distance next will equal chooser you see this hair will be distance root plus a cut of the power area which is a - cut necks and - area which is a - cut necks and - area which is a - cut necks and - toccata next so there will be distance root plus there were an equal to graph dollars - how - next - Scout next again dollars - how - next - Scout next again dollars - how - next - Scout next again then do the pre-order okay so we feel then do the pre-order okay so we feel then do the pre-order okay so we feel this power will be zero and the first of the trip will be negative okay thank you for sure see you next time
|
Sum of Distances in Tree
|
ambiguous-coordinates
|
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\]
**Output:** \[8,12,6,10,10,10\]
**Explanation:** The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer\[0\] = 8, and so on.
**Example 2:**
**Input:** n = 1, edges = \[\]
**Output:** \[0\]
**Example 3:**
**Input:** n = 2, edges = \[\[1,0\]\]
**Output:** \[1,1\]
**Constraints:**
* `1 <= n <= 3 * 104`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* The given input represents a valid tree.
| null |
String,Backtracking
|
Medium
| null |
897 |
That them guys welcome back to my channel english video where go into small increasing order search tree to what is given statement here biography root of binary search tree and tree in order to deal left no dea is now the root of the tree and every now have Not left side and only right side, what is the problem? Kallu has given a binary search tree and what we have to do is to make it one and a half inch, this trick and we will increase the stream by inch. What will be the root note of the nutrition in it ? By doing a binary search tree, the left ? By doing a binary search tree, the left ? By doing a binary search tree, the left most note i.e. the smallest note will be found and most note i.e. the smallest note will be found and most note i.e. the smallest note will be found and one more thing is given in it that now there will not be any left child, if the family light is on then you are looking at the example here, no one has any left child. Only if it is right style then which will be the root note? Set a reminder. Tomorrow then which is the left most of the binary search tree. One is any small. This note is the youngest. Then what is its right chain? It is just greater element descendant. Twitter Element is on side two is tu here piece and child which is two to just better element is just great element capture 383's right child is three color add is just development which is four is here ancestor Lifestyle which will be it just Get Elements Which is the congested element there is 525 white color guide channel which will be there just battery maintenance sir so this is the pattern here i.e. it is in ascending order when will pattern here i.e. it is in ascending order when will pattern here i.e. it is in ascending order when will you get the elements in ascending order in binary search tree when you If you do in order traversal, then you get - in history - team. If we - in history - team. If we - in history - team. If we do inorder traversal here, then these elements in ascending order, we will get the style like this. Okay, so this problem, we will use inorder traversal to solve this problem. Okay, here what we will do is first do inorder traversal and how will we use it. Look, if you do inorder traversal then you print that note while travelling. So here what we will do is not print the note, we will use the value of the note. We will use here, okay, inorder traversal, first let's see how we do inorder traversal, first you hit the left note, okay, then note after note, we print it, then right note, okay, i.e. When you delete any note at scan okay, i.e. When you delete any note at scan okay, i.e. When you delete any note at scan time, your inorder will come under traversal, first time visit will come under this, third time visit will come under this, what will come under postorder, ok so let's see by doing these hotels, it comes in technical form. If it is a binary search tree, it will come. What will we do first? We will fill the file, five, complain, then we will visit 10 out of 573, we are visiting for the first time, then we will visit 30 *, we are visiting for the time, then we will visit 30 *, we are visiting for the time, then we will visit 30 *, we are visiting for the first time, we will visit China. What is this? We are doing percentage, we will visit the press club which is tap, okay so after visiting this, what will we do again, visit this note, right one, if we want to set the first second time, then in one here, let's do this. We print in the note in Robertson 2019 day okay first novel is what we will visit right side but what is the channel in lifestyle so tap is you will go back up again from here to two are doing second remedy left You have already visited it from the side, you have visited it for the first time, then what will happen if you visit it for the second time, it will be printed here or you will digitize your lifestyle book, but if it is a colonel, then it will come back, then it is back on the other side. Okay, remember to visit for free. We will visit on Shivratri. Okay, after visiting, what will we do here? We will visit on the right side. What is complete on the right side is four. Then we will do t-shirt like on the left. will do t-shirt like on the left. will do t-shirt like on the left. This is for the first time. Set it to take a picture on your left and then go back. You are setting the present time. Here there will be four free on your right side. A special kind or the kind of this is back. Tap this, it will go back. Then where will it go and the time will be visiting for. Back here, this also set the time to three, then five, what is happening here, scan time withdrawal, so we will write to the umpire here, only you will fill it, will come here and on the right side, this belt on the right side. Then it will go towards Ka or right, the last one towards your left, okay, then it is the second final of Le Vijay. This mist this tap will come back here to visit this stuff will print here okay it would be second-hander first time here tap second-hander first time here tap second-hander first time here tap besan time here this is with thyroid what is this tap is tap so then back while shifting this One has hey guys and has to visit don't print here okay then here this note will visit then ne will go to its target this is tap so back look at this then will visit then here that we na niko na Will you paint your diet book, what is this channel, what is this, what will all this be visiting here, back, so it is already done that you are seeing what is ours, whatever value is found here, this is in this order in ascending order. What am I getting in the ascending order and we are also looking at the new tree, so whatever notes are there, all these are in the cadets in the hotel, so what will we do here, when we are placing these orders, then here we will print a book containing 12345 rupees. If there is a guide, what will we do here, if we do not print it then we will use it on the value of this note, then how will you use it here, first you will take a temporary note, okay, we will note the temperature and what will we do with it, will we take Delhi-110, okay? This is take Delhi-110, okay? This is take Delhi-110, okay? This is taken chapter note is anything sea give any name here and give result ok here is its value - one result ok here is its value - one result ok here is its value - one is ok then what will we do when we beat then in the last when we have visited the style Then when we visit again, we will get that, then what will we do with the one value, create another new note or create a new note and what will we do with the channel that we did cricket result, we will start it as its right child. On the right end we will sign on it that whatever you do on the right side of this result, it is ok, it will be 151, world news will come, then what will we do with all, we will remove it here, this has come here, it is ok then we What will we do, then we will visit the inverter, then what will we do, what should you do, we will make one on the right side, we will not create luck here, we will make two as its title, then what will we do with the result, we will take it back here, we will light it next. Like current, then we will get three, we will get free k in the inverter in this order, what will you do to the woman, take the right side of it, then what will we do, move the result, come to the right and then force for notes, what will we do, create a value, create notes Then what to do, we will sign the note in its night, signed it, then what to do is to free this water here and then what to do here with face value, we will make a note and the rights of its result will be signed to me that the light will be switched on. Who will do its result, will we free it further, then six, what will we do, will we make a new note, what will the trainees do here, will we sign on the right side of it, will we move the pimples forward like on the right side, okay then we will get seven, in the inverter, there will always be money in these wards. Then we will get its right, we will create a mixer guide channel, then what will we do, then we will move towards this right, we will get it towards this right, friends, now what will you do in this night, child predators, people, from the value of pain, from one note, then what should I do here to free it? You will do it on the right side, what will you tell humorously, the right side of the right side, then what should I do about the result, you will do it here, your result is here, but we need it from here, what will we do? Another note, when the result is coming, we will do it. So what will we do, another node, let's take any answer, we will cut it and keep the reference of the result in it, okay - MNREGA friend, but hmm, okay - MNREGA friend, but hmm, okay - MNREGA friend, but hmm, when we return, we will write it down, so that what building, if we want this balance from here, then it is returned. The answer will be, I will get it, okay, so what will we do here, what will we do for these orders, if we use declaration, then what happens in the rehearsal, not ours here, what will happen in a vacation, what will be the base condition that whenever the route note What will happen is route, whatever we are calling, we will call this round, who did not, what is null, then that thread will go back to its previous note. Okay, so what will happen here, how will the code be, move this to your left channel. Will call, you will call first on this route, what will it do on this route, will it turn on its left, will it make a call, after opening it, you are free to turn on your lights, call me to call or what will you do, will it call your lifestyle, will it also call one? Said that you have turned on the light, if the call is done then it will come back to this, then we will get this will get a value, using this cat, we will create a new note, after creating a new note, write the result like this, then we will turn to this and then We will go to the right side of it. Light is null, so back here, it will go back to two. Okay, so it will get the note value in. Then we will use the mode value, make a note, move the light result here, once again what to do with this. Call the light and don't cry in and what has to be done here, you will see that bus two will come here, then it will go back to three, then use the note, he will do such meditation, okay, so let's see how to code this problem. If we give here then what will you do here first do one here take one immediately result presentations Pimple 9 - 1m - 1m So now what will you do here that one we take wheat without mold Motu Patlu Film Industry I am not If star route to tap is ok then we will return it in that condition, we will deposit it, we will enter here, we will use this note of first child school, ok, we will subscribe, we will create 21 a new note, nutri note, what to do in it, which glass will we use? The value of the root which we are calling is the value of the note. Using this, we will create a new note so that I can sign it and then we will free the result further. Result first to retail price. Okay, I have done this here, I will do this. Given this, what will we do after this, we will order these, we will call the route in its right, it is okay in can right, the sum was done, this is ours, okay, what will we do here, again open the installed app and take three orders that these streets are in Order and what we will do here is call the root, then here then what we will do is turn it over, write the result, will not give the result, what you have to do here, first of all, you have to create another note that tree not toe that this What happened in this, the result has to be signed, okay, what has to be done here, this water has to be signed, when you return, you will add it and right it, okay and here, the result is final, here, but here we are. But we will keep it but when we do - then we don't want this diet, I want this - then we don't want this diet, I want this - then we don't want this diet, I want this lifestyle, then here will I commit suicide, then call me, I am addressing myself, I submit that the puja committee is done, Sai.
|
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
|
50 |
hey what's up guys John here so today let's take a look at this classic encoded binary search or recursion with memoization problem number 50 power xn so just simply ask you to implement the power of X to the N right basically given like two integers sorry two numbers if two parameters here first one is a float second one is a integer I ask you to get the what's the result of X to the power of n right and so remember notice that the end could be a negative value here right so if it's an active value so which means we need to do up to a 1/2 past in number we need to do up to a 1/2 past in number we need to do up to a 1/2 past in number right so with that in mind we can simply we can always convert the this number to a part to a positive number and then to the calculation right and so for that we want to calculate the power X to the power of n right so how can we quickly approach to the solution right so X to the power of 8 equals to what equals to the X power of 4 times the X power 4 right and then how about seven right 7 goes to X power of 3 times X power 3 times X right so basically every time we can always cut this end to half right based on the eye if it's a odd number or even numbers either to half and then very hard number we do a half times the tax and in the end we simply return the recursion result right and then how about then what's our base case right so the base case is gonna be X 0 it goes to 1 right x 1 equals x so this is our two base cases and then we can simply recursively call this helper function and then also we do a recursion with memoization right and this is a PI recursion with memorization and so that we don't need to repeatedly calculate the same result multiple times for example here right basically we're gonna call this recursion here with number four and the hero so number four right and every time we finish calculating the result for the N here right so we'll basically save it to a dictionary so that the next time we try to calculate again with four you can simply just returned from the addiction all right cool so is that being sorry said let's quickly go to the coding phase here so you're going to define the helper functions here are you know what let's do basically if n is smaller than zero we convert it to a negative value right and most of the final is negative value to false here right so that we can use it later on it's negative value it goes to true right and then basically we're gonna have a like answer here right equals to the helper n right if is it's an active right and then we do answer equals to 1 / cancer rising do answer equals to 1 / cancer rising do answer equals to 1 / cancer rising simply return answer here okay now it comes down how we can do a deviation here so basically divided by 2 here and define Harper right and with n here so and first if this n Oh like I said since we're going to memorize that right I'm gonna have a cache in memorization right then we simply returned the memorization is the current n here otherwise the base case the to base case if N equals to 0 we simply return 1 if n equals to 1 simply return X right otherwise we do a half and the remainder right equals to give mod current n is 2 right and this half will be our recursive call here right basically we do a I'm sorry cause to what equals will helper half writes times same helper he goes to half times either X or 1 based on the remainder right times X if the if there is a remainder right basically if the remainder is 1 we will times X hours if the remainder is 0 we simply read the time multiply 1 here which means we don't multiply anything right and then in the end I just add this answer to that to this memorization write return outer cool so I think that's pretty much it is right basically we divided by two and then use this and let's just run it all right so this one except let's try to submit it cool so it's also passed yeah so the only basically two things we need to keep in mind first is we always convert this and two it's positive number so then it's easier to calculate right and to calculate n every time we divide this and into a half right and then we just need to be careful with these two base cases right zero means 1 means X and if you thought it was greater than 10 then we Ricarda me a half and also this to work we saved the previous previously calculated results to this memorization dictionary here in the end of its return it okay yeah pretty straightforward I think that pretty much it is for this problem thanks so much for watching the video guys and see you guys soon bye
|
Pow(x, n)
|
powx-n
|
Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., `xn`).
**Example 1:**
**Input:** x = 2.00000, n = 10
**Output:** 1024.00000
**Example 2:**
**Input:** x = 2.10000, n = 3
**Output:** 9.26100
**Example 3:**
**Input:** x = 2.00000, n = -2
**Output:** 0.25000
**Explanation:** 2\-2 = 1/22 = 1/4 = 0.25
**Constraints:**
* `-100.0 < x < 100.0`
* `-231 <= n <= 231-1`
* `n` is an integer.
* `-104 <= xn <= 104`
| null |
Math,Recursion
|
Medium
|
69,372
|
743 |
hello and welcome back to another problem today we're going to be doing problem number 743 Network delay time it's a pretty popular graph problem in it so I'd encourage you to know it and so pretty much I'll just explain it an easier word so let's say you have this two you have a graph of nodes and then you have directed edges it's going to be like this and these edges symbolize how long it takes from one node to get to the next node and then we are given some starting nodes so let's say we're starting over here we have to figure out how long it takes until we can get to every single node what would be the total time well for this to be pretty straightforward right so to get the node one would take one time all right so this would be one so you get to know three would take one and then to get to note four we take another one so the total time node four will be the last node we're visiting and so the total time here would be two but how would we actually do that right and then also there is another case where like if we do have some nodes that we like there's node 5 over here then we can't reach it so we also have to figure that out so we have to figure out how long it takes to visit every node and yeah that's what they're asking and if you can't visit every node then return negative one so what we're actually going to do here is we're going to be using jigster's algorithm and so the way it works is you start at some node and you are going to we're also going to like pre-process this data also going to like pre-process this data also going to like pre-process this data where we're going to have like all the nodes and all the nodes they can go to and like the distances in some in like a dictionary so what we're going to do is like for example for this node two we're going to have uh the time like all the nodes it can go to and the um like how long the path is so for this example it'd be like two it can go to one you can go to one right with uh path one and then it can also go to three with path one and then three can go to four with path one so we are going to have that pre-process like we're going to that pre-process like we're going to that pre-process like we're going to process our we're given time so we're going to process that into a dictionary but what we're going to do afterwards is we're actually going to use a Min Heap and we are going to start with the node that we have so let's say like we have this node two we're gonna start the starting node we're going to put that into the Heap and we're going to keep track of how long that path is so we're actually going to put in we want our Min Heap to be sorted by the length of the path because that way we the projector's algorithm you want to get to every note as fast as possible and so the way to get to every note is as fast as possible is you just take all your available edges and you always Traverse the shortest Edge that you have so like well I'll show you what that's going to look like so for this node 2 here we are going to pass in so the path from node 2 is going to be zero right because if we take it to from 202 from the two to zero so we're gonna have node two this is our Heap and what our algorithm is actually going to look like is we're going to keep processing this Heap while there is a heap so we're going to take out this node we're going to say okay we have node two let's take all of its neighbors and put them into the Heap and let's figure out how long that next PATH is and it's pretty easy to figure out the next PATH because it's just the path to node two which is zero plus the path from node two to all its neighbors which we're going to have it's actually not this one it's over here we're going to have that sort in a dictionary so we're just going to keep adding to the path so we have this node two now we pop it from the Heap and then we're going to put in its neighbors with the appropriate path so it's going to be one to node one and then one to node three and there the reason they're one is because the path no two zero so it's really zero plus one here and so on okay and so and we are also going to every node we visit we're going to Mark in some visited set so we don't have to revisit it again and then we can just say like okay once we visited every node then just return the maximum path because that's like the that's the node that was the last one that you visited so if you had some nodes like zero one two three four and then they took let's say like the times so this would be in like our visited it would be an invisible dictionary so this one took 10 seconds this one took 15 seconds one second two seconds 25 seconds then the time to visit all nodes would be 25 seconds you just take the one that you visited last not the one that you visited last but the one that took the longest time to visit that's going to be our output and so in this example for example we're going to have this node one uh so we don't have a node zero actually so let's delete that but we're gonna have a node one we're gonna have a node two we're gonna have a node three and a node four and so for two immediately we visited right away it's at zero so we're here now so now these nodes are going to be sorted in terms of the like the path and it doesn't really matter which one you pop first because these nodes will technically be visited at the exact same time so it doesn't matter so let's say we pop this one now we have to check the neighbors of one and so the one doesn't actually have any neighbors so we don't have to do anything there and we are going to say we visited one at one time okay now we have this node so let's pop that and so this was node three so node 3 does actually have neighbors it has a neighbor of four it has neighbor of four and then a distance is one but remember it's one plus whatever the path to node three which was one so it's one plus one four that's gonna be in our Heap here and then we also have to write that we visited node three and that's going to be one now we pop node four so that's going to be two four we pop it and then we say we visited node four at time two and we don't have any neighbor we don't have any nodes in node 4 but even if we did we're going to be checking the length of our visited dictionary if it's and if it equals n then we're just going to return straight away that's going to be shortcut so if the length of this is n then that means we visited every single node and so then we just get the maximum one of these values so that's what jigsawcherism is first you make this you make a dictionary of every node and all the nodes you can visit then you simply start you give your Min Heap your starting node and then you simply keep adding all the neighbors that you haven't visited and we just pop from them in here the shortest possible path so chicken shot dragster's algorithm is always from all the paths you have just keep going the shortest possible path possible and that will be guaranteed to visit every node in the fastest way possible and also let's say you're not trying to visit every node but let's say you're trying to visit node four that would also work for that so if you're trying to visit OneNote in the like in the fastest way possible you just do that algorithm you always take the shortest available path and you keep using that okay so let's code that up so we are going to have remember we're going to have a couple things so we're gonna have a visited dictionary that's going to be an INT and then we are also going to have a like an edges dictionary list and now we have to process these times so for start and time many times so that's going to be so we want when in this edges you want the key to be the start and you want the value to be the end and then you also want the time so edges start we're actually going to store it in the other way we're going to store time and then end this is actually not equals it's a pen because remember this dictionary is a list it's a dictionary of lists so that's going to be time and like that okay now what we want to do is we want to make them in Heap so let's just say that's going to be like signals Maybe equals Min Heap and then we want to start with a remember path of zero and then we want to put in whatever node n is so I think it's actually K yeah so k okay and then yeah now we want to say while our Min Heap is not empty so while signals so what are we doing remember we are popping from the Min Heap so and when we're going to pop it's going to be a path and a node so path length maybe node equals K-pop length maybe node equals K-pop length maybe node equals K-pop and this is going to be uh our signals and then what we need to do is we need to um yeah so we need to make sure that we haven't visited this node so we can just say if path or if node and visited we can just continue here okay so otherwise we need to add it to visited so visited add node uh so this is actually sorry so this is not um add this is going to be remember we need to actually record how long the path was so visited node equals pathway there we go okay now we need to iterate through all the edges in the current node right so if we're at this node we need to iterate through every single edge and we need to check is that is the node that the edge is leading to has it been visited already if not we don't need to add it to the Heap but if we didn't uh sorry if we did visit it we don't need to add it to the Heap and if we didn't visit it we need to add it to keep okay so four and then remember these nodes are going to be in um like time and then and let's call it in visited and it's not visited this is measures right so you need to check every Edge from this node if and not in visited then we need to add it to our Heap right and we need to add the time plus the time it actually took to get to this current node which is this path length so that's going to be keep push signals then we are going to be adding a path length plus time and then we are going to put an end here okay seems good now we also can do a little check here so if length of visited equals n that means we visited every node so we can just return the max of visited Dot values what we could technically do to save us a little bit of time even though time complexity wise it's not really going to matter is still keep storing the max but I don't think it's really going to matter like yeah there's going to be like instead of oh then it'll be like oh two times n so it's fine this way okay so return Max of visited dot values here because that's going to be the number the node that we visited the last is going to be the node that takes the longest amount of time and so that's what it's asking for so the time it takes to reach every possible node means you visited every node and then whatever node you reach last is the time it takes to reach them all okay so now we can return minus one here because this means that we went through our Heap we don't have any more edges but we still haven't visited every node see how many years we have hopefully a lot yeah okay we nice okay perfect so I will say that uh I did some look on I did some looking on this time and space complexity and there have been conflicting opinions like um some you know some editorials say it's one thing some editorial saying another thing so I will just say what I think it personally is and then if you guys think it's something else or you can disprove or you know make a better case for it then feel free to write that in the comments so I think that the worst case here is actually every node is going to be connected to every other node pretty much except for like so it'll be not a fully connected because I don't think you can have Loops I believe maybe you can actually maybe you can sure but that's fine so yeah I think every node will have like let's say you have something like this I think worst case scenarios like every node's connected to every other node so it'd be something like this and so on right and so then in that case uh you know like this just like there's every possible path possible then in that case every no ever like if there's n nodes then every node will have n minus one Edge and so you would have this would be complexity of N squared edges and so if you have N squared edges then your HEAP would have N squared nodes I think worst case and so then if your HEAP has N squared nodes so actually when you have a log of N squared because a heat push in the heat pump is log N squared this ends up being something like to login and so this two actually goes away so it would be something like this where n is your number of nodes and then remember so you would have to do this many operations he pushes and heat pops but then if you also have you know edges like M squared edges so this would be edges so it would be something like that so your time complexity here is actually going to be e of V where e is the number of edges and then V is the number of vertices but like I said there are like two or three different um scenarios that are possible but I think this is worst case and then yeah and then for space I also think it is going to be uh so this is uh so worst case I think it's actually going to be this believe it or not because otherwise the same it can also be written as this because assuming that you know for every node there are n minus one edges then at a worse time it's never going to exactly reach that but at the worst time your heat can actually hold um N squared nodes because you will have duplicates because like let's say you have a node that's connected to every in the other node so you're gonna have like a starting node you're going to pop that node and then all those nodes aren't invisited yet but they can still be in your HEAP so your keeping your heat can definitely have duplicate nodes here and you can go through the code and figure out why that is so I think worst case scenario it's actually of e where and just e is really big but in an average scenario then it would actually be something like this where it would be like this if you know you don't have a billion edges because then I think your HEAP will contain an average of V vertices and then your dictionary remember is going to have uh every node as a key and then every Edge as a value so that would be V plus e because you'd have like you know key where it key is the node so this is like V and then you'd have a list of edges here yeah there's definitely um like I said some people think it's this some people think it's something like this for uh time complexity some people think it's something like this you know and I can definitely see Arguments for all of these things so but I do believe it's this one so you know you can make your own conclusions on that but that is all for this problem hopefully you liked it and if you did please like the video and subscribe to the channel we actually got over 100 Subs so thank you guys for that and hopefully we'll keep growing it more and thanks for watching see you in the next video bye
|
Network Delay Time
|
closest-leaf-in-a-binary-tree
|
You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target.
We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`.
**Example 1:**
**Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2
**Output:** 2
**Example 2:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 1
**Output:** 1
**Example 3:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 2
**Output:** -1
**Constraints:**
* `1 <= k <= n <= 100`
* `1 <= times.length <= 6000`
* `times[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `0 <= wi <= 100`
* All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.)
|
Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
383 |
Hello hello brother welcome and welcome back to my channel so what is our problem today tension note is available here see here we are roasting tension 9 end magazine what do we have to do na ransom note has to be set tomorrow magazine It is okay by using the latest version of the press note, if you get all the details mentioned in the press note, you can construct the work in the magazine, but you cannot return it back home. Ok, it is a simple problem, if we can construct it, we will go through the details in white here. Okay, so how will we solve this problem, first let's see, so look here we have placed it on the press note and magazine is also given, now what we have to do is to make the silk note by using the latest of the magazine but here. But what do we need that we will not get, so we will turn the force, look here, this is what we need and here is AB, you get one, but take the other, you are not here, in the same account, at least there should be more here. If it is also there then it will be fine but at least this much should be there but it is there otherwise it would be witful here. Now see here AB is given and here this is given. Are you present in this or not? President, a little present, heavy percentage. Yes, this is also one percent, but what is the meaning of war in the middle, three will work, at least there should be as much in it as Twitter, so how will we solve this problem, what will we do here, no, we will take two people, okay, what will we do here? Will start everyone's account in tractor Okay so here it is on the famous name so see what we will do here, how will we set up an account for one, see when you have one actor and we have taken the factor, then it is okay, tractor ka jo intact ho song. Actually we have a chapter of browser from Ekta so there is a job index that will indicate to the caterers how to do this so when you do one then what happens is zero also means if you do a survey then what happens one happens - when If you do one then happens one happens - when If you do one then happens one happens - when If you do one then what happens if you happen then we will start like this, okay in this we will learn protest outside with, its size we will take the front piece okay so that our index is from jio to 1025 and this is from zero to the front part. If the pain is okay, then we will store it here, add it, make it the best, along with this, we will keep the particular and express account in this vector, we will keep the tractors account, there will be one account on zero, which account will be sold on 1, the coin will get angry on two, ok like this we If you start, then look for a healthy society. Now send it, Hello Bittu, take it, okay, then life taxes on egg will be O, it will be accounted for, which will be 1, which is 1 on these tracks, it is OK on Bittu, B is * on these tracks, it is OK on Bittu, B is * on these tracks, it is OK on Bittu, B is * but what will happen to you? What will happen till this point will be one. Okay, what will we do now? Now we will again take zero index and go till hour five and check whether all the elements on the index are there. Look, Jurail will be the actor here, you have to get his account, the residence of Light and SP. But it will still be okay, we will ignore it, now what will we do, will we check whether this account of yours is not cut or not, is the account in this also not afraid, if the header means this is not full in this Can do its department, can't feel it, mute it is useless, it is doing this emergent, okay, how are you taking notes in it, something, when there is a clash of accounts in it, you are starting a song in it, then at least Less, the number of accounts in it should be in it, so you check here, let's do it, is the account of this boy actor of any one, is it not more than this, is it dominant, we ca n't feel our requirement, where We will fold it, if it is clearly decided, we can do it, then finally what will we do, if we start here, then what happened in this case, Jio, we cannot see what happened here, yes, you must be here, it happened here, okay, so its The work here is great, if the minutes will not be able to subscribe to it, the cactus which is in the magazine, it will be able to fold its requirement, what will the button do here, it will pause, okay, for the second example, let's see these third kilos, here it takes care of I have given it to you in a silk case and if you have given me even one, then start it in this building, play it on any person, let one person shine once, it will have 042 account, if it is in the middle, then there will be such an orgy, then first of all, this is zero separate commission. Is this result available for both accounts? Is it not graded from the card? This one will work. Now there is one such zero. See in this case too, is it more than this? Is it not much? Otherwise, this one will also work, so it means that Our requirements here are these fruits. Okay, so we will stop here after watching the finals. Okay, so now look here, look at the footwear. Here I am a rich person, I have taken vector art, peas and army. What will we do with this note? Twitter. We will keep the account, we will keep the magazine in the pen, okay, I have taken it from zero through this exercise, then what should we do in this, we will start the travel account. Okay, what I told you is - it definitely happens. B is minus one, so is - it definitely happens. B is minus one, so is - it definitely happens. B is minus one, so what will happen to you? This is your life, watching bf on tax, on the seats, on the screen, like this, it will go to the day after tomorrow, then till the divide, now you will start both of them, after supporting, will you kill, what art is for any particular tractor daily for any particular index Account details are not available, if available then Rakh Means Magazine is not available and false otherwise, proof is ok, this is the problem, thank you.
|
Ransom Note
|
ransom-note
|
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.
Each letter in `magazine` can only be used once in `ransomNote`.
**Example 1:**
**Input:** ransomNote = "a", magazine = "b"
**Output:** false
**Example 2:**
**Input:** ransomNote = "aa", magazine = "ab"
**Output:** false
**Example 3:**
**Input:** ransomNote = "aa", magazine = "aab"
**Output:** true
**Constraints:**
* `1 <= ransomNote.length, magazine.length <= 105`
* `ransomNote` and `magazine` consist of lowercase English letters.
| null |
Hash Table,String,Counting
|
Easy
|
691
|
448 |
hi guys hope you're doing great at today's question is find all disappeared numbers in an array so the question says given an array of integers where what a of i every integer in the array is in the range of 1 to n including 1 and n where n is the size of the array some elements appear twice and others appear once find all the elements of one comma n inclusive that do not appear in this array could you do it without extra space and in o of n run time we may assume the returned list does not count as extra space all right so for example this is the given array so the size of the array is 8 right so that means that 1 and 8 n is 8 right so 1 and 8 included there are 8 numbers in this and as we can see 2 is repeating twice and 3 is also repeating twice so there are two numbers between 1 and 8 1 8 inclusive which are not there in this right which is 5 and 6 and that's what we need to find out okay so i think this question generally has very this is a very unique type of a question and um the only condition we need to notice here is that it states that the numbers are in a given range because that is really important for us to use this approach so what we'll be doing to solve this question is that we will play with the indices and the number values so for example we know that since we know that the numbers are in the range of 1 to 8 here right and the indexes that we have in this array are from 0 to 7 because 8 is the size of the array that is why let's say we c4 so what we'll do is that to convert it into a zero based index we just subtract one from it right because there's no zero here so we just subtract one from it and the array element at 3 right 4 minus 1 3 we just mark it in a way that we are able to identify that i have seen a 4 in this area before okay so we just mark it negative right and then similarly for all the other values we take the absolute value of the uh element and subtract 1 from it and then mark the element at that index as negative if it's already not negative right so that way is what would happen is that at the end there will be certain indexes which have for which the values are not there for example since 5 is not there so 5 minus 1 4 the index 4 value would be positive right similarly since 6 is not there so 6 minus 1 5 so the value at the index 5 would also be positive so when we travel through the array once more we'll find that these two values are still positive which means that their index plus one these values have not been seen in the array and that is how we'll determine that this is our output right so we'll just start coding and see how that works yeah okay so you simply have to have a for loop simple one which goes still nums dot length and i plus okay so the current value is numbers of i okay numbers of i and of course we want to take the absolute of this because there we might have there might be a duplicate so we might have changed the value of this to a negative value before so we don't want to like work on that so we just take a absolute using math absolute function okay and then what we have to do is that um yeah so so we are not now converting it into a zero based index value because we don't have zeros here we just have one two n right so one will map to zero two will map to one and so on so this will be equal to the minus we just want to negate it and we want to ensure that we are not like we may be in the past we have already negated this value but since we will be negating it again it will become positive and we would not be able to identify the right output so we just want to negate the absolute value of it yeah so here we have taken out the absolute value and reassigned it a negative uh negation of the same value that's all okay so we just keep on doing this for the whole uh array and after that we just have to like travel through it once more okay and we need the indexes so it will be i based again okay and i plus and then we just check that if nums of i is greater than zero right so which means it's a positive value then we'll have to create a list for our output here it will be an integer just call it result new array yes so what we'll do is we'll just add to it now the index is zero based and since we had converted this to a zero base index the value so if for example the nums of 5 is positive it means that six has not been seen anywhere in the array right so that's what we'll do we'll just do an i plus one ah sorry we'll have to do a um okay so if at index five we are seeing a positive value then yeah i plus one right cool okay and that's it we should return yeah okay so clearly the time complexity for this is o of n because we have just traversed through the array once and the space complexity is of one because we are not using any collection or anything so yeah it works so hope you guys find this helpful and this is a really important approach and applies to some specific set of questions so please try to understand this and if you find this video helpful please like share and subscribe keep coding and take care guys
|
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
|
136 |
hey what's up guys Nick white here I do tech encoding stuff on Twitch in YouTube and this is a pretty cool easy problem called single number just because this one solution is cool I thought it says given a non-empty array of integers so given a non-empty array of integers so given a non-empty array of integers so an array of integers every element appears twice except for one find the single one your algorithm should have linear runtime complexity could you implement it without extra memory okay so my first instinct was okay we just need the frequency of the number to be 1 obviously there's a hashmap right so we just have number of frequencies loop through basic loop if the hash map doesn't contain the value we put it in with a you know the count of 1 otherwise we update the value and then we have this is basically a frequency map then you just loop through the frequency map if the frequency is 1 we return the key so then that's it you run it works perfectly but what they wanted in the problem was to not use extra space right so how do we do that well I looked at the solution and I'm not really that confident in my bit manipulation abilities I learned bit manipulation of data structures but I have to know it to get a job probably so I'm gonna get better at it but I you can bid manipulations useful I just saw this solution you just loop through the array and I was surprised by how simple it was and then I looked it up and had it explained to me and I was like wow this is really cool so I guess you can do you know like plus equals but like carat equals with these I'm not sure if you can do in a Java the solution he had was in Python so let's try it and then I'll explain it so this one is a linear scan and obviously we don't know if storage space we're just doing bit manipulation so looks like it works you can do this which again just means result equals results caret num shevai so yeah pretty fast hundred percent how does this work ok so the this caret symbol and when we're doing bin manipulation this means X or in bit manipulation is breaking things down to the lowest not be lowest level but a very low level where we're thinking of numbers as bits meaning a 0 or a 1 you know the binary representation of an integer value for example I think it's 32 bits in you know Java in different programming language it's more bit more or less bits so we have this list operation as 1 hash table I showed we already went through that this is like some math thing that we didn't do because it was it seems kind of dumb and then we have bit manipulation right and this is what his example was and I was like how does this work how is this working and you know there's a pretty good explanation here it says if we take XOR of a value and remember we only want every elements all occur more than once except for one element occurs once so I was like how is this working like I don't really understand well if we have this element set to zero we have this initial result set to zero and any element that we see XOR meaning this carrot if we XOR with zero it result will then be set to the element that we did an XOR with right so if we're looping through the array an array of integers like two to one and we do 0x or two on our first loop then result will end up being two right I'm going to use Python to kind of show my point here in a second but you know when we do we result will be two after we do result X or two because 0 X or 2 is 2 but now that results is 2 we see another - 2 X that results is 2 we see another - 2 X that results is 2 we see another - 2 X or 2 is 0 so any duplicate the way that XOR works is any duplicate number when you XOR it the first time the result will change to something different that we don't want but when you XOR with the same number again because there's all these duplicates then it's just going to go back to the original number so the only time that XOR will change from 0 to a number that we want is when we find the single number with no duplicates all of these are duplicates except for so right if what's fit say for example we do 1 X or 9 well that's going to change to 8 but if we now do 8 X or one that's gonna be 9 and if we did 8 X or 9 that's gonna be 1 so you could see how its kind of it goes back and forth so when we see duplicates we're doing 0 X or 2 well that changes it to 2 because 0 X or with anything is gonna be 2 or whatever that value is but then we see it again and it's just gonna be 2 X or 2 and it just goes back to 0 so as you can see when we see duplicates and we do the same computation using X or at the bit level it's just gonna turn things change things one way and change things back since everything is a duplicate we're just changing things one way to changing things back and when we see the only single element it changes things one way to the element that we actually want so when we see this one at the end we're doing we're back at 0 we do 0 X or 1 and it's gonna stay that way we're not doing 1 X or 1 because there's no more once it's there's no duplicates hopefully I explained that well I know it's kind of a hard one to explain I definitely recommend reading more about it because I'm still in the learning process it's kind of a harder I think it's one of the harder concepts like really getting bit manipulation down because there's a lot of trick solutions with bit manipulation so let me know what you guys think let me know if I'm stupid or not in the comments below I really appreciate knowing how stupid I am so just let me know and please you know so check out the other videos so thanks guys for watching see you guys next time
|
Single Number
|
single-number
|
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,1\]
**Output:** 1
**Example 2:**
**Input:** nums = \[4,1,2,1,2\]
**Output:** 4
**Example 3:**
**Input:** nums = \[1\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-3 * 104 <= nums[i] <= 3 * 104`
* Each element in the array appears twice except for one element which appears only once.
| null |
Array,Bit Manipulation
|
Easy
|
137,260,268,287,389
|
126 |
all right guys welcome to our channel code with sunny and in this video i will be talking about a series of problems called word ladder and now we are going to discuss the second problem right its index is 126 and it is a hard problem of the lead code okay so i don't think that this problem should be categorized into a specific category called as graph type problem this problem can be solved with uh like simple mathematical logic but we need to have some knowledge of graph theory like of breadth first search finding the shortest path and all that stuff okay so without wasting our time let's discuss this problem and then we will together build up the best solution for this problem okay so let's move further a transformation sequence from word begin word okay to word inward it means that we will be given a some string and let us call it as begin word we you can also understand this as source string okay and inward is a target string using a dictionary word list okay so we need to reach from the source string begin word to the target string inward using a dictionary word list where word list will be a series of strings that would be given to us and it is a sequence of words begin word okay so the transformation sequence would be like starting from the source string begin word and there will be like a path of strings you can see s1 s2 and it goes up to sk and it is satisfying a certain set of conditions now what are these conditions let's understand that every adjacent pair of words that is s of i and s of i plus 1 of that transformation sequence note that this begin word also lies in the transformation sequence so if you talk about the adjacent pair of words differ by single letter you need to talk about begin word and s1 also and similarly as s i and s i plus 1 also that is every adjacent pair of words of that transformation sequence starting from the source string and ending up to the target string must differ by a single letter so if you talk about s1 and s2 it means that all the characters that all the specific positions are same except the only one character okay now every s i from i up to this one note that the beginner does not to be does not need to be in the wordlist that is the source string is not guaranteed that it is lying on this word list it may lie or it may not lie okay and the last string of that transformation sequence is going to be the end word okay now what we have to do in this problem given two words begin word and inward and the dictionary of word list return all the sort test transformation sequences from the begin word to the inward okay so there obviously uh not saying it's obviously there may or may not exist some path starting from the source string and ending up to the target string suppose there exists a path starting from the source string and ending up to the target string and the path length is said to be x okay and we need to ensure that the path length should be the minimum across all the paths and if the x is the value of that minimum path we need to find all the shortest transformation sequence that is we need to find all the shortest paths starting from the source string and ending up to the industry or an empty list if there doesn't exist any path each sequence should be returned as a list of words this one as a transformation sequence okay so i'm also going to explain all these examples all not all these this is the very good example that i am going to consider okay and let's first look over the constraints how this is going to help us you can see that our begin word length is like at most five so it doesn't create some like it doesn't contribute to some time complexity and because the value is like very much small and in the word length is exactly equal to the begin word length and word list is at most thousand it means that you can have a n log n solution or o of n square solution and you can see that every word in the word list is has a length exactly matching with the beginning word length that is the source the string length and all the lower case letters and begin what is not exactly equal to the inverse so it means that the path length must be greater than 2 if that exists some path and all the word list in the sets are going to be unique okay so how we are going to approach this problem what would be the basic idea to start thinking about this problem let's move further to understand this problem in the very detailed manner okay so let's move further okay so let's focus upon what the problem statement is saying i am taking this example from this that is the example one that i'm talking about note that the begin word is this one and the end word is this one okay so the arrows are going to denote that is if i will draw an arrow from head to heart then it means that there exists exactly one character that is differing you can see h and h is matching tnt is matching but there exists a character i and which is not present over this one that is the only one character is being different and the that is the edge edges you are going to see it denotes that the that is the notes that are present over here that is the strings or 10 dot similarly hot and lot or are going to have the exactly one character that is going to differ okay this is the source string and this is the target string we need to find all the parts which are going to lie which are going to have the shortest distance you can see that for every like in a general graph problem what we are going to do we are just uh suppose we have been given a source string source node and considered this as a source node and considered this at the target node and if we have been asked that what is the shortest distance from this source string and up to this target string you need to find out the shortest distance only note that i am just trying to make this entire problem like in more understandable way by just explaining the concept of breadth first search okay so if we have been said that we need to find out the shortest distance from a source node to the end node in a graph problem what you are going to do you are going to just perform a breadth first search traversal to find out the depth of each node with respect to source node right okay so let's try to find out the depth of this every node with respect to the source node okay so what i'm going to do is let's first erase this and let's write it down as source okay now let's just name it as now the source node is at depth equal to zero and hot is going to with respect to the source node either depth equal to one and this is also a depth equal to two and this is at depth equal to three and now this is at depth equal to 4 right okay yes so it means that starting from the source node and we want to reach to this target node end node it means that there are exactly five nodes that are going to lie in the path including the source node and the end node you can see that if we try to reach this in node i have to come from like this one you can see that this is one of the path okay it means that i am going to just write down hit okay not i'm done i'm not just going to write down so let us look over here this is the exact path hit hot lord log nco this is one of the path okay and if you focus of what other path that is okay so let me just try to erase it down okay it is not going to be happening okay so let me just do this one okay yes almost done i don't know why this is not happening yes okay now what is the another part that i'm i need to talk about it should be like this one right so this is another path hit hot dot dog and cog okay now the thing is like how we are going to approach this problem by just like in one traversal we need to operate all the things very carefully okay by knowing that shortest distance is not sufficient we need to find out the path in this case right we need to find out what are the nodes that are going to lie in this path that is the strings okay so how we are going to do that okay so you need to just notice about that is you can do this problem like first find out the shortest distance then find out the all parts in that case you need to have a mapping of strings to some integer then that would be like very much complex i have tried that and it is like uh like very much complex so i thought i've thought some different things okay what is that different thing what you are going to do is you are going to maintain a q of like in case of when you are trying to find the shortest distance with respect to source node you are going to maintain a queue of integers right uh okay yes you have integers but in this case you are going to if since you are going to find the path you are going to maintain a q of vector of string why are why we are going to do this because we are we need to find out the paths okay so how the entire things would be done okay so let me just explain this in a very simpler way we are going to maintain a q of vector of strings in that case what i'm going to do is okay so first i will just restore hit which is going to be like uh begin word then what i'm going to do is then i'm going to traverse all the neighbors of this hit okay now the thing is like how we are going to find out the neighbors of the state note that i'm talking about the neighbors and the only neighbor is here is hot okay you can see that if we need to find out the neighbors of this hit this is the string the first thing that makes in your mind is why not to find out all the edges initially in oauth and square time right yes you can do that but i'm i don't think that should be a sufficient way because you can see that the length of this begin word or any of the word is at most five right if you notice about the constraints at most five and also word list of eye length is also exactly matching with the beginwa dot length so it is at most five so why not we do is like traverse all the characters one by one that is first i will traverse for the h then i'll traverse for i and then i will traverse for t and what i'm going to do is just to replace this ith position character with the characters any character starting from a and ending up to this jet okay it means that if i will just replace any corrected position with any of these characters lying in this range and remaining characters remain as it is it means that exactly one character is going to be changed suppose i have changed this h to any random character let's n okay so my new string would be like n i t right and this string is the adjacent of this string hit right but the thing is like whether this nit is going to exist in this list of word list or not that is whether this string nit is being provided by the like in the input or not that is in the word list or not uh like it is obviously not okay so we are not going to consider this one okay so which strings do we need to consider that string which is present in the word list okay and still it is not traversed okay why i'm talking about still it is not traversed suppose we have traversed this hot and again in a certain set of condition we are again trying to find out that is what is the neighbor of this what is coming about to be hit okay if the neighbor of what is coming about to be hit and hit is already traversed that is it is all already visited we are not going to consider that okay now the thing is like okay so let me do one thing okay now we have the string like hit and if i will change this i to some character o you can see that it becomes hot and now this is going to be present in the word list and adjacent to this character hit okay so we are going to find out the adjacent character of that is adjacent node adjacent string of any string by just doing the traversal for every ith position of the current string and changing that character to any character starting from a to z okay now the thing is what i'm going to do is like we have the hit in my current that is we are processing at the current level right hit and the for the next level i am just trying to find out what are the strings that is coming about that is hit adjacent is hot okay now hit that sent is hot and this is the only one part and again for the next level what i'm trying to do is find out all the adjacent neighbors of this hot which are still not visited you can see that the neighbors of this hot is like lot and dot okay so it means that here we will have two parts hit hot and lot and again another path is like hit hot and dot okay now the thing is like you need to store all these two parts into a queue and every time just take it out the one of the path and find out the neighbors and if you have reached out the target string here comes your answer okay you are since you are doing the q approach that is the breadth first approach every time if you just uh fetch it out the string that is the neighbor of the current string and if you find that neighbor is exactly matching with the target string you are going to push back your current path to the answer note that you need to return a list of odds right okay so now you can see i have the hit hot and lot as one of the path and another path is hit hot and dot now what you are going to do is pick up this path hit hot and lot and find out the neighbor of this one you can see that a neighbor of lot is dot also okay but dot is already processed that is dot is already visited so we are not going to consider that and lord that is the string lord has the neighbor hot also but hot is also processed so i'm going to find out the neighbor of the slot which is log and still it is not processed so i'm going to push back this path also watch path from lot to log and if you talk about this dot that is hit hot and dot what is the neighbor of this dot whose neighbor is still not visited that is it is dog so i will just push back the path dot now the thing is like we have this path in the queue and we have this path in the queue okay now again we need to pitch out the neighbors of this one you can see log neighbor is cog and dog neighbor is cog and this is the target string just push back all the paths when it is going to reach out the target string that is the path from this one and the path from this one so basically you are going to have the width for search over the paths not the distances with respect to source string every time you are going to process the path and how to find the neighbor efficiently as i have already said we need to find out the neighbor by replacing every ith character with any character from a to z since we are replacing the only one character it means that we will have the like we will have the difference of character or that is adjacent character has exactly differing by a single letter right that is hit and if we try to replace i you can see that with any character let's say h80 hat but this is not present in word list and if we try to replace it by oh but this is present in the word list so you need to check it out that also okay now the thing is like the implementation is very much complex but i have done something interesting so let's look over that how this is going to be implemented in much fruitful way okay so let's move further to the submission you can see that okay yes you can see a very complex type of like code okay so what this is going to do let's first discuss over that this function is used to get all the words which differ by at most one character with the previous word okay you can see that if i'm talking about this hot the list of words would be lot and dot right and the thing is like this can be like hit one that is the neighbor of what is also hit but i am not talking about that because when we reach the hot position it will be processed already okay now i am taking the parameter as word and unordered set of word list note that i'm talking about unordered set of word list because i need to check it out in the word list efficiently that's why i maintain the unordered set of word list okay now this set of word list is like uh when we have when we are just reaching out the position hot that the node hot it means that we have already processed this hit and we are that is this word dish will not contain the string hit okay that's why i'm just only checking out that position also note that i'm just erasing it out from this all words i think yes i'm just erasing it out okay and i'm just pushing back all the way okay i'm just talking about all these things later on but now this you can just think upon that is this function is going to just get down all the words which differ by at most one character with respect to the current word okay that would be like neighbor of the current world now it will be stored in answer and traverse all the positions of the current word you can see i from zero to word dot length and pick out the current character and for the current position change the current character to any character from a to z you can see word of i becomes c where c varies from a to z and check if that exists in the word list that is if that is being given in this word list okay if that is given you are going to push back the word it means that this is going to be the neighbor of the current word and after doing that you need to just restore that word also that is why i've just previously stored in the variable ch and finally return the list of strings which are adjacent to the current word this function is going to do that how this is going to help us we will talk it later on now just focus upon the actual function now this font is going to store whether it is like whether we have found the answer or not initially it is initialized with false now we will have a vector of string of q that is sorry a queue of paths basically vector of string okay and this is going to store answer for all the shortage transformations and this is another string of visited which is going to store words which are already visited okay now okay yes which are already visited now we will have another strings of all words which is going to basically store all the word list all the elements of this word list in a unordered set which is going to be called by all words store all the words in word list in honored set now start traversing the breadth first search manner push out the path and the only current path is starting from the beginning what you can see i pushed out the vector string of begin words now just i trade over in a grid first search manner now what i'm going to do is every time i'm just going to work upon the current level process all parts up to the current level okay now first i will find out the size that is what are the elements what are the number of parts ending at this one okay so if you are like at level equal to two you can see you will have two parts that is hit hot and lot and hit hot and door every time we are going to process in that path and that is the here we will have two parts and every time we will process one path so i will iterate over every path and find out the what is the current set of paths you can see vector string of current is going to store the front element of the queue for all the parts up to the current level okay now the thing is like we need to find out the neighbors of this current one you can see if you talk about this lot i will just find out the neighbors it will be log and dot okay now this is going to give us the all the neighbors of this current world that is the last word of this current path you can see i have just passed out current.bat passed out current.bat passed out current.bat current.back and all words is current.back and all words is current.back and all words is going to store the word list basically and this will store all the nodes which are adjacent to the current one now just iterate over all the neighbors and find out the new path would be like for all the current path plus the current string that is pushed back now if my that is my current neighbor is exactly coinciding with the inward i will just mark found as true and i will just push back the new path into our answer now okay if that if this is done mark visited that insert the string into the visited one and this push back the new path into the queue okay now if a current level is being processed if i will found that yes i found the path just break it out and return the answer otherwise you need to do this thing now this is going to be quite tricky okay what i'm going to do is like for all the entries in a visited unordered set i think visited is a unordered set of strings that is if i will just find it out what are the notes that are visited in the current level i will just erase all the entries from all words is like basically uh yes all words is like basically a string of word list that is all the strings that is present in the word list i'm going to store it in unordered set now this is going to be like very much important i will erase all the entries all the strings that are being inserted into the current table right now and erasing all the interest from all words is basically simplifying our complexity and also providing that is also preventing us to get us the wrong answer you can see that when i will just find out the list of words get current dot back and all words i'm passing down the all words yes okay now if i erase down the all the entries from the current level you can see that this all words that is at the next step we will just get down the list of words which are adjacent to the current string become like we are not getting those strings which are already processed so let's understand this with the help of example suppose so yes suppose we are just taking it out as hit now if i am talking about the string what is the neighbor of this hit the neighbor of this would hit would be like hot okay the neighbor of it is hot and if this is processed that is this is at the level one and if this is done what i am going to just remove this entry hot from the word list so now the word list will not contain the hot okay so i will just uh do it by cr making a cross over here okay now the next step that is at the next step what is the neighbor of this hot you can see the neighbor of this hot would be like lot and dot okay and the neighbor of what is also being called as it but it is already processed the neighbor of hot is and this dot and i will just also mark down this as with the tip okay now in the next step if you find it out the neighbors of also okay so one thing i forgot to mention if i will just say that the neighbor of what is lot and dot then it means that i have just erased the entries of hot already a lot already and dot already okay now if we are at the current path that is hit hot and lord let's say hit out and lot then if we try to find out the neighbors of this lord you can see that neighbors of this lord is also is like hot is like dot and the neighbor of lot is like log also but you can see that when i'm passing down the get function that is when i am calling on the get function current dot back is lot and passing down the all words right but in the previous level i have just reached down all those entry which are already visited it means that hot is rich dot is erased and lot is also erased and my current uh last element of the path is lot and i'm trying to find out the all those name but you can see hot is already raised dot is already raised so it means that whatever the unordered set of strings of wordlist that is being passed over to this function it means that it will not contain the slot string and dot string it will only contain this log string and all the elements of the next level okay so it means that i will just get down the vector of string which is going to be a neighbor of the current string lot as the only one string and what is that only one string it would be only log this lot and dot will not be processed because this is already being erased in the all words section you can see so this is going to be very much important every time we will just get out those neighbors which are not being processed right now and this is going to be all that okay finally data on the answer so if you have any doubts do let me know in the comment section of the video and i will ask the viewers to like this video share this video and do subscribe to youtube channel for latest updates thank you for watching this video
|
Word Ladder II
|
word-ladder-ii
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _all the **shortest transformation sequences** from_ `beginWord` _to_ `endWord`_, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words_ `[beginWord, s1, s2, ..., sk]`.
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** \[\[ "hit ", "hot ", "dot ", "dog ", "cog "\],\[ "hit ", "hot ", "lot ", "log ", "cog "\]\]
**Explanation:** There are 2 shortest transformation sequences:
"hit " -> "hot " -> "dot " -> "dog " -> "cog "
"hit " -> "hot " -> "lot " -> "log " -> "cog "
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** \[\]
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 5`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 500`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
* The **sum** of all shortest transformation sequences does not exceed `105`.
| null |
Hash Table,String,Backtracking,Breadth-First Search
|
Hard
|
127,2276
|
402 |
That Sohail Bhavan Today Dwipushkar Andar Lee Ko Medium Problem and 402 Removed Deposit This Problem Ho Saka Usaan Ki [ __ ] Deposit This Problem Ho Saka Usaan Ki [ __ ] Deposit This Problem Ho Saka Usaan Ki [ __ ] Please Like Mission Goodbye and Imprisoned for Six Pack Abs Khuli Not Talk But I Think You Are Not Them No Abuse Subscribe My Channel Like In this video that today subscribe our channel since it will work hard to bring you good interview problems quite sometime in the leaders will also be seen that let's start its question from fennel liquid state power but you to play the question from it Suraj and depression pav subscribe to That 1.32 219 it and give in the number of That 1.32 219 it and give in the number of That 1.32 219 it and give in the number of two that I invincible strain this tourism time one and a half hundred waste to recall value of this train e-mail value e-mail value e-mail value that is minimum torch light district cooperative credit so impressive 138 they remove physical 231 RMO for This Free Android 2.2 Subscribe RMO for This Free Android 2.2 Subscribe RMO for This Free Android 2.2 Subscribe 14321 9483 on December 09, 2012 by someone on December 09, 2012 Do A Great Khali Way Subject Ko Subscribe Must Subscribe And Finally Bigg Boss Numbers Pen Number To Back To Numbers With Same Leg The Same Line To Same Number Of It's Right Flash light at least minimum number of 20 value secretary and police loot most value i left most value that this minimum flash light issue means atta sapoch one to 020 so what is let's move will have to dream se enters into with all for android and 101 What is Left Most Different 12011 And Witnesses in Manzoor All the Latest Tracks Should Define Lutu Appliance Question Knowledge See How Can They Expect This Pack to Take Some See You Turn on True Strength From Left to Right A the Left or Right I Find It Number Track se is digit with this is its great day i plus one updated on the right is held in jammu remove decide youtube from now why support system traveling alone 13252 remove exactly one digit office nothing so what do you think that dark mode switch fire movie all Song Again Get Possible 3232 's Ninth System In This Forest Wealth 's Ninth System In This Forest Wealth 's Ninth System In This Forest Wealth Is But Can't To Be Achieved Tay Jamla Ko Subscribe Suvan Traveling From Left To Right In 132 I Come In This Month's Organized Visit To Britain So Understand That One To Three In This Side Held It is the Name of the Day 900 Vacancies Saifi Dasha Loot Vishya Jaroor Kariye To Wa Aarti 2.5 Number Se Left Side Important Part Is This What Is This Channel Subscribe Kar Do A Sudhein Roshni Ko End Pe Attention Hai Midnight On This Number One Who Read 219 It's Existence Suicide Push Visit In To The Point August That In All It's Right Down This Novartis In Condition Of Button I Plus One Piece That Alarm And Normal Modified This Academy In Accordance With My Bro How If Element That In Stockport A Great Then Were Current Element Rate Other Dial Been Looking At This Condition Is True Then Removed At Element Thomas Train Otherwise Simply I Worship Him Space Torch Light Soil Sono A Metro That Is Pro A Greater Than Vansh Gas It Is Gold Channel Saurav Is Condition Invited To A Point To text who invented cc i in it element which sport growth rate states to a point pro torch light addict mez k suno k smart v k leftovers pe my tab ask 981 gas rate elements of which is the current element ask question that boat ion counter Do a good fight to this prelims elements of top limited i.e. from this point top limited i.e. from this point top limited i.e. from this point today we your health torch light log in futu in this elements of wave din to 9 tone confirmed in that time nine encountered so that * this condition nine encountered so that * this condition nine encountered so that * this condition satisfied not so opposed to log In torch light 9 encounter what is this condition satisfied it decide to a point where to short form put at that time end quick weakness so normal k vikram ji sudhanshu white money growth process rastogi elements of elements problem subscribe channel vikram 219 200 vacancy yash This is the answer report handover algorithms correct hai na vo vriksha school board by clicking on this show what is the cost limit hai but did not come on mein is great son of growth side reaction hai subscribe and this post on may 21 2012 and Ginger and Kiss good also died December after certain point most all in increasing order aa rahi hai so in that case aka Billu this point discussion till code hybrid plum how to handle country from Switzerland send button right shruti profit which is point this point And 1000 lessons can be looted Nand Celebrity 100 List Ko 150 Effigy Issues That all given channel and simply the return gift right or not this creation of wealth creation of wickets that if it is done IP news talk show is DI tractor hai that nitrate hai Ashwin 's side in two hydrate over match streaming 's side in two hydrate over match streaming 's side in two hydrate over match streaming 179 here this is that is going up will be lost flash lights element so poor for best friend and student ride starts sirvi talking what should you should stop obscene ha ka one my baby k 102 k Central light among I cursed dream I understand that committee torch light is no more elements form that no more elements to pause that landlord current element who is chief minimum sopa to improve should be com 161 Vikram also has left motor limit and fight Inside finally condition is this is my current element was current voice mail element that is great than you all is this loops which bike current elements gave top leaders on that sister Kepler setting on map of the element pet suggestion sindhi style about finally bigg boss Subscribe this channel for notification 12345 Truly love you two give development and already in increasing order so I left most elements are automatically minimum is automatically minimum Siddharth Roy simply pause element to hang finally what does it is this cream and Ayush Bhawan and Bijli is accepted that this then becomes a strong body, hair test MP came positive also eliminated top end producers video subscribe 21 2013 subscribe my channel point Raghava is sure that Edward school will get started notice to wage board is the key related to pure and Memory Limited And Sur During Time Do Subscribe Only Like You Don't Like Share And Subscribe
|
Remove K Digits
|
remove-k-digits
|
Given string num representing a non-negative integer `num`, and an integer `k`, return _the smallest possible integer after removing_ `k` _digits from_ `num`.
**Example 1:**
**Input:** num = "1432219 ", k = 3
**Output:** "1219 "
**Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
**Example 2:**
**Input:** num = "10200 ", k = 1
**Output:** "200 "
**Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
**Example 3:**
**Input:** num = "10 ", k = 2
**Output:** "0 "
**Explanation:** Remove all the digits from the number and it is left with nothing which is 0.
**Constraints:**
* `1 <= k <= num.length <= 105`
* `num` consists of only digits.
* `num` does not have any leading zeros except for the zero itself.
| null |
String,Stack,Greedy,Monotonic Stack
|
Medium
|
321,738,1792,2305
|
263 |
Hello welcome back to Anonymous Data Scientist channel, today we will do lead code problem 263, what is the next number, how is the next number defined, if it is a positive integer, whose prime factors are limited to 25, now we should know what are prime factors. For this, as if six is six, For this, as if six is six, For this, as if six is six, what will be the prime factors of t and r, then prime factors of s will be t and r, then we will call six as s is n, next number, now assume that we have been given m1 and we know one. That is, one is not a prime number, then we will consider one as true and give true in the output. Now Example Three is given n = 14. Now that is 14, the Three is given n = 14. Now that is 14, the Three is given n = 14. Now that is 14, the prime factors of 14 will be 2 and 7. What will happen in it, which is seven, that is our list. I does not exist like 2 in 35 so because of this we will say this is not the next number and false will come in the output. Once we see the logic, what logic will we use? So now what do we do in this. We will take our number in the same way, the number given to us is 20. Okay, so we will run a loop in which we will keep the values 2 35. If the number given to us is being keep the values 2 35. If the number given to us is being keep the values 2 35. If the number given to us is being divided by any of these, then we will tell it as it is next. Number: If any number is coming which is Number: If any number is coming which is Number: If any number is coming which is different from these three, then we will call it false in the output, like first of all we do 20 on Y, we divide 20 by 2, then what will we get in the output, 10, then We have again divided 10 by 10. We have again divided 10 by 2. What will be our output f? Now we have divided f by 2, but it is not happening because our reminder is that zero is not coming, which means that division is not happening. If division happens then our two is not dividing f, similarly th will not divide but f will divide it and what will come in the output one will come in the output then we will end our loop and give the answer. Will give true like we took an example y one, suppose we took the example 14, what we did in 14, we divided it by two, then our output will be sen, now sen which is 7, we will divide it by two, this reminder on dividing by two is zero. If it is not giving then we will do three to thr p also will not give f to f p bhi sen which is there will not give the reminder zero then if it is not dividing by any of these then we will call it as false in the output that this is not our next number. Just have to use this logic, let's code it once and see how it will happen, so now let's start coding it, first of all we will see if which is our sorry if which is our number and lesson is equal to zero, if this happens then we will directly Will return false. Now we apply our logic then p in 235 if our p is among th and f then run the loop inside that we will check if our number when divided by p is divided by prime factor. If it is giving zero then a is equal to a p, we will do this and here we will return a ev a e means if a e is true, if a e is 21 then we will return true, this means what we have done a loop. Run our prime factors, give them the value of p, two or three or five. We divided them by our number. If on dividing by the number, we kept dividing it till the time our reminder came, and if in the last everything. After dividing, we got one. Just like we did 20 by doing it. Just like we did 20 by doing 2, then what happened to that from 25. Our reminder was that one came, so it is true, so this is what we did. Let's run it once and see only four lines. The code was only, submit it, if you have any doubt then you can ask in the comment section, see you in the next video, thank you.
|
Ugly Number
|
ugly-number
|
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.
Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_.
**Example 1:**
**Input:** n = 6
**Output:** true
**Explanation:** 6 = 2 \* 3
**Example 2:**
**Input:** n = 1
**Output:** true
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
**Example 3:**
**Input:** n = 14
**Output:** false
**Explanation:** 14 is not ugly since it includes the prime factor 7.
**Constraints:**
* `-231 <= n <= 231 - 1`
| null |
Math
|
Easy
|
202,204,264
|
1,396 |
Hello everyone welcome to my channel it will be very easy story is simple and will convert the story into code and this is one of the solid question where the story helps a lot the name of the question is Design Underground System and it has been asked by This has been asked multiple times in Amazon and Bloomberg. Okay, so once you read the input and question, let's understand what the question is. Okay, so let's understand the question. It is a very simple statement that you have to design an underground railway system based on customer travel between. Different stations, ok one banda, let's take this banda maa, it had ID band, checked out at B and account from 3:00, checked out at B and account from 3:00, checked out at B and account from 3:00, ok so how much time did it take, he checked out at 1:00, checked out he checked out at 1:00, checked out he checked out at 1:00, checked out from B at 3:00 Okay, so how much time will it take to 3:00 Okay, so how much time will it take to 3:00 Okay, so how much time will it take to travel? It will take two or two times to travel. Okay, after that, it is the Get Everest time because of mother. There is another guy, his ID is you, he checks on A, okay and he believes that it is 4:00 pm. Let's take Chadha Maa and he 4:00 pm. Let's take Chadha Maa and he 4:00 pm. Let's take Chadha Maa and he checked out at B. The guy checked out at 7 o'clock. Okay, so how much time will it take? It took this guy three times to go from A to B. 7 - 43. Okay, three times to go from A to B. 7 - 43. Okay, three times to go from A to B. 7 - 43. Okay, so now get the average time, don't know what to say. It will tell you the start station and interstation. It is asking you what is its average time. Brother, from A to B. Take the mother, he has kept the start session here and has also given the inception, so you have to see how much time it takes from A to B. Time is running out, show people that it took two times for ID number one to go from A to B. And show another that it took three times for ID number one to go from A to B. Okay, divide it, how many numbers are there? Identify ID, one is this banda, the other is this banda, then divide it by two, then its average will be 5/2. then its average will be 5/2. then its average will be 5/2. Okay, the answer will be 2.5, so it is quite simple. Now Okay, the answer will be 2.5, so it is quite simple. Now Okay, the answer will be 2.5, so it is quite simple. Now see why I am saying that this is the question, why such questions? They are formed from the story, okay, now such questions are there, you proceed with true questions, okay and IF you figure out that you must have decided that you have to map it, but how to implement it in the best way, a very clean and simple solution is available from you. Okay, so now I am telling you one thing, trust me in the next few minutes of the story, you are about me, listen to me, tell me you are helpful in story writing, now what I will tell you is the solution approach, this is what I told you, brother, how important is the code from the story. Why is it important to write and create a story? Thoughts are very important. Okay, so let's go ahead and see from these three functions, how will we approach this from the story to the solution. Okay, so look, pay attention to this in these three functions because I This is our tension, this is what we have to get, isn't it asking for the result in average time, do the rest, nothing is being done, it is just saying store it, but when it will do the get average time tomorrow, then I will have to return the answer. My tension is on this, my entire focus will be on this, so look at this demand, what input is it giving and understand what output is to be given. Okay, to understand this, let's take a very small example. There was a man, he had the ID band of something. That was Chadha at A station at 1 o'clock and the same Banda Chadha means checked in he is ok and he got down at 20 station at 3:00 means and he got down at 20 station at 3:00 means and he got down at 20 station at 3:00 means checked out ok. Similarly the other Banda was that Chadha at A at 4 o'clock and Banda from C got down at B. 5 o'clock is ok or else 7:00 mom, got down at B. 5 o'clock is ok or else 7:00 mom, got down at B. 5 o'clock is ok or else 7:00 mom, ok this is its second time, this is its check out time, it is clear till here, now see what had to be done for Everest time, do you know brother from this start station There is a start session till the station. What did you have to find out that brother, how much time is being lost from the start station. Okay, what does this mean? What information would you need? From the start station to the station, okay? You would need the information that there is translation and How much time is being wasted in people's lives? If we talk about forest then how much time was being wasted in going from A to B. Even in this case, how much time is there in saving lives? 3 - 1 2, isn't it 3 - 1 2? So brother, give it. It was 3 - 1 2, isn't it 3 - 1 2? So brother, give it. It was 3 - 1 2, isn't it 3 - 1 2? So brother, give it. It was okay for one, it was similar from A to B, in my heart, this one was spending so much time, how much time was being spent with me, that is, I was spending three, okay, so now see, what is our retirement, what do we have to send brother? The amount of time that is going from A to B in this life, one is two, one is three, what is the sum and division of all these, how many people are there, two people, so now pay attention, understand what you have to keep track of. Keep track of the route from A to B. Well, we will have to start the story, okay, we will reduce one, take a map, okay, and will say, and we also need to know how many people traveled the route from A to B. Here we will store the accounts, okay who will do the solar here it will become one thing that brother, this is the route or this is the route and after that we will have to start the account of how many people are doing it and this total time will also have to be made noise. Only then will you do the total time, that is, it will not be less than just the account, we will have to store one leg, but what will we do in which how much total time was taken and another one, what will be the total count, then reduce it by one, let's make such a map, this is our This is a map, what will it be, string versus a, here the total time account will be on B, now understand the most important thing that how can I populate this map, it is an obvious thing, some guy checked it once and finished, checked out on B, but only then So, this entire route is complete, what does it mean that only when the check out is done, I can populate it, right, so you think for yourself, what should I name it when the check out is going on, let's name it MP. Let me give it's okay for now, then it will be checked out, only then I can populate it, otherwise what will I put in it, as soon as this guy has checked out, he has checked out on A, he has checked out on B, so if you look at the function of checking out, right? Here, what is given in the check out is which station is it and at which station it has got down, here we do not even know from which station this banda started, okay and more importantly, we do not know here that I don't even know, brother, at what time this fellow came from the station, only then you will know how much time it took, see, this is the total time, how much time did it take for this fellow to come to life even like this? Okay, so how will I know the total time when I check out? I will check out the second time, only then will I know the total time. How much time did it take? Okay, and what is this Rawat? My A is B. Okay, what does it mean that when I am checking out? I only know at the time of check out, meaning B is known and when I checked out, I know the check out time, ok and I know the ID, but we do not know the checking time, what does this mean, we will have to keep another map. When you are checking here, its entry station and at what time you are checking it, you are seeing that on S, I have retired, I have made a map, this is what happens, you are making a solution by back tracking, first I saw what is needed here, okay, then You see, if you want here then you can fill it at the time of check out only. Then while entering the check out, we will also have to mention the check in time. So after coming to check in, this is what happens by back tracking and finding the solution. So see now in checking. That is, there will be another map of checking in which what will we store? What did I say that guy would have this ID? Remember this was the ID that the guy had given here. What had I written here that at which station did the guy enter and at what time? Okay, so what map will it be? This will be a leg here, where there will be a string that at G station, he got that chada and the time will be here, how big is the chada, let's name this map, second map, check out. Map very important information has been received, now see this map has a checking map, it is ok, as soon as this Banda Chadha, what is its ID, at which station, Chadha at A, Chadha at what time, Chadha at one o'clock, Chadha, now as soon as the same Banda comes, check. To check out, look, I have an ID at the check out, so what will I do, from this ID I will take out the second time of the person, which is one second time, I will take out the second time and I am getting the check out time here. But T Okay, so what will I do, starting station, which is what is We were storing how much total time did it take, what is the count, okay so let's take Ma from A to B, there was no entry yet, so how much did it take, remember this guy, take Ma, check out in this, it is 3:00 pm, so take Ma, check out in this, it is 3:00 pm, so take Ma, check out in this, it is 3:00 pm, so 3 - 1 is the answer of 2, isn't it? Mother, let's take 3 - 1 is the answer of 2, isn't it? Mother, let's take 3 - 1 is the answer of 2, isn't it? Mother, let's take T13, so it becomes 2 and how much is counted. Banda before sun, so I banded it is clear till now, it has been stored in the map, now in the check out map. Let's say another guy came, okay, he checked in at A at 4:00, okay and checked in at A at 4:00, okay and checked in at A at 4:00, okay and he checked out at B, what time do we take mom, it's 7:00, so what should I take mom, it's 7:00, so what should I take mom, it's 7:00, so what should I do? He is the same guy, isn't he? I took out the information that he had chadha at A. He had chadha at 4:00, so I will not calculate the total time, chadha at 4:00, so I will not calculate the total time, how much time will the person with ID take, with -4 date, I will add this 3 to this -4 date, I will add this 3 to this -4 date, I will add this 3 to this and science, this is the second person, so I created an account. It is clear that there are two people who have traveled from A to B till now, so what we have to do in the end is simply tell 5, we will have to return 2.5. 2.5. 2.5. Okay, so see, the most important thing was what is there in the map of map formation. You will enter only the most important ones and they have been building according to retirement. Like, I repeat again, here I saw that I have to find the average time, I only know the start station and rent station, which means I would need this information. How many people traveled from A to B, its account and how much time should I calculate in total, the total time is ok, now ACP, who has traveled and who, can now be known only at the time of check out, who had landed at Banda B and the repairers. When I came to check out time, I came to know that there is only one station near me, there is no information about the starting station, so where will I get the starting time, I will get it from the second time, ok, let's build the solution in this way, ok, so see. If we go, we have already come to know the solution that we will need two maps, as soon as the person checks out, it is okay and when the person checks out, we will need these two maps, our head will be reduced, okay, from then onwards Janani Travels started till Sorry Station. How much time did it take? Is it the total time? What is the total time by how much is the count? Now how do I know the total time and count? First of all, there should be a start station and the station is ok. Had traveled, it is ok. As soon as the banda checks out, only then it is at the station. It is known in Bade that this end session is actually fine and before that we know the station but we do not know the star station, so here I will have to enter the information in Bade of the start session that which banda is ok, which banda is it. Maa, let's take its name as check in map checking. So this information is clear cut. I am understanding it ok, what will be the interior and what is the mapping of whom and what, we need the entry station, where did this person do the checking, ok. Where did this guy do the checking? What time did this guy do the checking? Okay, so what I told you is that as soon as I check out, I will get the information, so what do I have to put in my check, brother, put me on this road. Brother, how much total time did it take? Okay, so what will be my road map? If I say string then it will be Rawat. Okay, leg off. Remember what was the time taken and how many people are there. Okay, let's write its name and check out the map. Here I have to write that I am mapping the route to whom, how many people have done the total time and count, so far it is ok, so what will I do here, what will happen, when we started checking, ID dot is the second member, so we have to Have you got the chart and what is my time and this is t so I have got all this information okay we have also made the route okay now all we have to do is check out b rawat dot first what to do as much as It's time, okay second, his account is being maintained here, plus this equal, 1 Yadav is clear, now he has taken out the exit, so he will have to be removed, this guy's check is fine, I am repeating again while checking out. Checked out, I found out when and in which station he checked in, what was its entry time, then I found out the starting one, he checked in now, I know about the ending station, there is no ending session and I know the time. So Rawat, I have made the Rawat of Inception from the start session, I have come to know the total time, how much time was taken by the team, I have started adding the entry time and time how much time was taken by the team, I have started adding the entry time and the account is also increasing, how many people have come and science is this bond. This ID has been checked out, so I have told it to you in the checking room, okay, till now it is getting cleared, okay, now all I have to do is auto and it is equal, you have taken out the check, okay, in which both total time and account are included. Okay Second, look at one more thing, our answer can be in flat or in double or even in decimal. Look, the answer can be okay because we are sending it by dividing it. So here I am sending it in double. Okay, I am converting all the examples in double. Let's see by submitting this. Let's see the variable, you pass which date is cases, they have passed, which date is this, they have solved this question. It was quite simple, just tell you the story. Had to make one more convert and had to do the same with the data structure. If you have any doubt please read in the common session and try you bill be out see you gas video thank you
|
Design Underground System
|
count-servers-that-communicate
|
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.
Implement the `UndergroundSystem` class:
* `void checkIn(int id, string stationName, int t)`
* A customer with a card ID equal to `id`, checks in at the station `stationName` at time `t`.
* A customer can only be checked into one place at a time.
* `void checkOut(int id, string stationName, int t)`
* A customer with a card ID equal to `id`, checks out from the station `stationName` at time `t`.
* `double getAverageTime(string startStation, string endStation)`
* Returns the average time it takes to travel from `startStation` to `endStation`.
* The average time is computed from all the previous traveling times from `startStation` to `endStation` that happened **directly**, meaning a check in at `startStation` followed by a check out from `endStation`.
* The time it takes to travel from `startStation` to `endStation` **may be different** from the time it takes to travel from `endStation` to `startStation`.
* There will be at least one customer that has traveled from `startStation` to `endStation` before `getAverageTime` is called.
You may assume all calls to the `checkIn` and `checkOut` methods are consistent. If a customer checks in at time `t1` then checks out at time `t2`, then `t1 < t2`. All events happen in chronological order.
**Example 1:**
**Input**
\[ "UndergroundSystem ", "checkIn ", "checkIn ", "checkIn ", "checkOut ", "checkOut ", "checkOut ", "getAverageTime ", "getAverageTime ", "checkIn ", "getAverageTime ", "checkOut ", "getAverageTime "\]
\[\[\],\[45, "Leyton ",3\],\[32, "Paradise ",8\],\[27, "Leyton ",10\],\[45, "Waterloo ",15\],\[27, "Waterloo ",20\],\[32, "Cambridge ",22\],\[ "Paradise ", "Cambridge "\],\[ "Leyton ", "Waterloo "\],\[10, "Leyton ",24\],\[ "Leyton ", "Waterloo "\],\[10, "Waterloo ",38\],\[ "Leyton ", "Waterloo "\]\]
**Output**
\[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000\]
**Explanation**
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(45, "Leyton ", 3);
undergroundSystem.checkIn(32, "Paradise ", 8);
undergroundSystem.checkIn(27, "Leyton ", 10);
undergroundSystem.checkOut(45, "Waterloo ", 15); // Customer 45 "Leyton " -> "Waterloo " in 15-3 = 12
undergroundSystem.checkOut(27, "Waterloo ", 20); // Customer 27 "Leyton " -> "Waterloo " in 20-10 = 10
undergroundSystem.checkOut(32, "Cambridge ", 22); // Customer 32 "Paradise " -> "Cambridge " in 22-8 = 14
undergroundSystem.getAverageTime( "Paradise ", "Cambridge "); // return 14.00000. One trip "Paradise " -> "Cambridge ", (14) / 1 = 14
undergroundSystem.getAverageTime( "Leyton ", "Waterloo "); // return 11.00000. Two trips "Leyton " -> "Waterloo ", (10 + 12) / 2 = 11
undergroundSystem.checkIn(10, "Leyton ", 24);
undergroundSystem.getAverageTime( "Leyton ", "Waterloo "); // return 11.00000
undergroundSystem.checkOut(10, "Waterloo ", 38); // Customer 10 "Leyton " -> "Waterloo " in 38-24 = 14
undergroundSystem.getAverageTime( "Leyton ", "Waterloo "); // return 12.00000. Three trips "Leyton " -> "Waterloo ", (10 + 12 + 14) / 3 = 12
**Example 2:**
**Input**
\[ "UndergroundSystem ", "checkIn ", "checkOut ", "getAverageTime ", "checkIn ", "checkOut ", "getAverageTime ", "checkIn ", "checkOut ", "getAverageTime "\]
\[\[\],\[10, "Leyton ",3\],\[10, "Paradise ",8\],\[ "Leyton ", "Paradise "\],\[5, "Leyton ",10\],\[5, "Paradise ",16\],\[ "Leyton ", "Paradise "\],\[2, "Leyton ",21\],\[2, "Paradise ",30\],\[ "Leyton ", "Paradise "\]\]
**Output**
\[null,null,null,5.00000,null,null,5.50000,null,null,6.66667\]
**Explanation**
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(10, "Leyton ", 3);
undergroundSystem.checkOut(10, "Paradise ", 8); // Customer 10 "Leyton " -> "Paradise " in 8-3 = 5
undergroundSystem.getAverageTime( "Leyton ", "Paradise "); // return 5.00000, (5) / 1 = 5
undergroundSystem.checkIn(5, "Leyton ", 10);
undergroundSystem.checkOut(5, "Paradise ", 16); // Customer 5 "Leyton " -> "Paradise " in 16-10 = 6
undergroundSystem.getAverageTime( "Leyton ", "Paradise "); // return 5.50000, (5 + 6) / 2 = 5.5
undergroundSystem.checkIn(2, "Leyton ", 21);
undergroundSystem.checkOut(2, "Paradise ", 30); // Customer 2 "Leyton " -> "Paradise " in 30-21 = 9
undergroundSystem.getAverageTime( "Leyton ", "Paradise "); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667
**Constraints:**
* `1 <= id, t <= 106`
* `1 <= stationName.length, startStation.length, endStation.length <= 10`
* All strings consist of uppercase and lowercase English letters and digits.
* There will be at most `2 * 104` calls **in total** to `checkIn`, `checkOut`, and `getAverageTime`.
* Answers within `10-5` of the actual value will be accepted.
|
Store number of computer in each row and column. Count all servers that are not isolated.
|
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix,Counting
|
Medium
| null |
816 |
hello viewers welcome back to my channel I hope you are enjoying all the videos and back with another problem from lead code today ambiguous coordinates we had some two-dimensional coordinates like 1 some two-dimensional coordinates like 1 some two-dimensional coordinates like 1 3 or 2.5 then we removed all the commas 3 or 2.5 then we removed all the commas 3 or 2.5 then we removed all the commas decimal points and spaces and ended up with a string s return a list of strings represented representing all possibilities for what our original coordinates could have be our original representation never had extraneous 0 so we never started our numbers like 0 point 0 1 point 0 so basically there are not numbers starting or ending with 0 ending with means ending with only after the decimal point so zero point zero was never the case like that so 0 point 0 1 that is also never the case so or any number that can be represented with less digits so for example 1 point 5 0 could be represented as 1 point 5 right so like that so there is nothing of 1 point 5 0 in their original list it was only 1 point 5 like that also a decimal point within a number never occurs without at least one digit occurring before it so we never started with numbers like point 1 so then there when there is a number like 1 right that means it was never a point 1 but if there is a number like 0 1 that is most likely a zero point 1 so things like that right so the final answer other lists can be written in any order also note that all coordinates in the final answer have exactly one space between them occurring after the come so basically if we go look at the example right for a this is a given thing so input is 1 2 3 with brackets right so when since we are reading the coordinates so 1 2 3 we could divide 1 2 3 several places it could be 123 or it could be 12 three so those are first two divisions but within 123 and 12 3 there is another possibility right it could be 123 12.3 because as per the could be 123 12.3 because as per the could be 123 12.3 because as per the definition of the problem they could they were they have replaced even the decimal points so one option is 123 or 12.3 so those two our options are done 12.3 so those two our options are done 12.3 so those two our options are done we cannot say take point 123 right as per the definition there are no numbers 0.1 right similar to point on basically 0.1 right similar to point on basically 0.1 right similar to point on basically so there is no point 2 3 also in that case right like that so that is those are two pairs and if we divide this number into twelve three right so one point two three or twelve three so for this number one two three within the brackets there are four possibilities so those four possibilities are given like here 123 12 3 so this is a first division and one 123 what you can do 2.3 you can have that is here and 12.3 2.3 you can have that is here and 12.3 2.3 you can have that is here and 12.3 12 you can have 1 point 2 3 that is what it is but this is a plain example write for example if there are zeros in it right there starting zeros as for the definition they never had 0.001 right definition they never had 0.001 right definition they never had 0.001 right so the only possibility for this number to be here is 0.001 and 1 so there is to be here is 0.001 and 1 so there is to be here is 0.001 and 1 so there is nothing like 2 0.01 and 1 that is what nothing like 2 0.01 and 1 that is what nothing like 2 0.01 and 1 that is what for the definition and then you take this is Iran to first coordinate the other coordinate will become 0 dot 0 1 so those are were two possibilities so let's go look at how we are going to solve this right so first thing is we need to split the given string into two parts such that each part has at least one character excluding the brackets right so for because brackets will be there for every coordinate that we are going to represent at the end so don't consider brackets with all the lengths that we are talking for the description right so one two three could be divided into 1 2 3 12 3 so that those are two divisions for that right we are going to look at the example anyway so for each part there are several cases that I looked at right with all the general possible coordinates right strings starting with 0 right if you know if the string is starting with 0 right if it doesn't end with a 0 we put a decimal point right after the 0 right so for example this is a string right if it is so this string right do this starting with 0 so this we are dividing it to 0 comma 1 let's say this is the division for example right then this is starting with 0 but it is not ending with 0 so what it says is we put a decimal point right after the 0 that means the first coordinate will become 0.001 so active that is the first become 0.001 so active that is the first become 0.001 so active that is the first stage if it is ending with 0 right and if it doesn't start with 0 then we just take the number as it is so that is another one and string with both starting and ending 0 if a string is starting with 0 and ending with 0 that means as per the definition there are no numbers of the starts right so we just discard that number and we don't do any process if the string length is 1 obviously if the string length is 1 there is no need to put any decimal points or whatsoever just take that number as it is if the string length is greater than 1 and the converted integer is equal to 0 for example there are 0 to 0 if we say the bow number we divided like 0 1 if this is a coordinate right so the string length here is greater than zero but if you convert this to integer it will be just zero then discard this number so that means there is never of that case like that zero one zero so there are no cases of like that so once the coordinates are generated for both parts we will use the cross product logic to come up with a final list of coordinates let's go look at this example right the one two three examples how we are going to go through the above steps so part one we divide it as one part 2 is 2 3 so 1 2 3 so the coordinates for 1 will be since it is a single number right if the string length is 1 just take that number that's what we are taking that's it right and the coordinates 2 3 and 2 point 3 so when the length is greater than 1 and if it is not so if it is greater than 1 and converting number is 0 then discard but in this case the converted number is not 0 and it is 23 so in this case we are going to apply a special either which you are going to look in the core right so for example for now on let's assume it is generating the numbers 223 and 2.3 right so this the numbers 223 and 2.3 right so this the numbers 223 and 2.3 right so this for the part 1 for the part 2 3 so the coordinate generated are 1 2 3 and 2.3 so we take the cross product so that 2.3 so we take the cross product so that 2.3 so we take the cross product so that cross product is for everything in coordinates here you attach the coordinates from here so there is only one here right 1 2 3 1 2 country so this is the cross product for this part division and then there is another division possible for 1 2 3 right that is 12 and sorry 3 here right so it is 12 1 point 1 12 4 3 6 8 a single number we just take as it is the cross product is 12 3 & 1 point 2 3 and we need to is 12 3 & 1 point 2 3 and we need to is 12 3 & 1 point 2 3 and we need to merge these two cross products right for the final answer that is the final answer so this is how we are going to look at that and solve the problem so let's go look at the code how we're going to solve this it's exactly the steps that we described so we get the length of the given string and we try to divide the string into two parts substring one and substring two so we take starting from the first character because we have to omit the zero a character why is the role character is emitted because it is a bracket and we go only until n minus two basically because n minus one is bracketed again right closing bracket so we go until n minus two so likewise we are going to get the 2 sub strings substrate one subsystem and for each sub string we'll try to the gourd generate the coordinates and we'll have coordinates for first sub string and coordinate for a second stripping as long as both are not null right if we are generating the coordinates for first two substring and second sub string if both are not null then we will have to do the cross product is for every string in coordinate one and for every string in coordinate two we are going to have a formatted coordinates in added to the answer list right so that is what we are going to return so let's go look at the generate coordinates part right so that is what the meat of this core this algorithm right so here we are go for a given string that means this is just a part the first part of the second part that are passed to the generate coordinates rate so for the first part of second part if we can parse the integer right if we can pass the integer then only we are going to look at what is going to happen we already know that we are able to parse it right if the string lot dot string dot length is greater than 1 and I is equal to 0 that means we are not going to have any numbers string length is greater than 1 that means it could be 0 5 zeros but the final generated number is just 0 that means there is nothing to be added we just read MD thing right and if s dot length is equal to one that means we just add that number to the result array if it doesn't start with zero and ends with zero then we are just going to add the string to the result array if at all if it doesn't end with zero and it's length is less than the string length that means basically we just put the decimal point at the first position the first version so if this is the number right let's say this is the number then we are going to insert it 0.001 so that we are going to insert it 0.001 so that we are going to insert it 0.001 so that is what this code is right and if at all it doesn't end with zero this is the final thing that means it is a valid number which is not ending with zero then we are going to divide that number and divide the number by ten and keep adding that double number into the result so this will have final answer right so basically once we get the answer right we will be having the coordinates for a given part of the string so once we obtain the coordinates for two parts then we will format that and return the result hope you like the solution if you understood the video and liked the solution please subscribe to my channel and share among your friends also please don't forget to click the bell icon so that you get all the updates for my future videos to your mobile devices are to email as notification if you are looking for a one on one coaching session or mock interview or interview guidance career coaching any of that sort right please leave your in the comment section below I will get back to you for those kind of sessions thanks for watching I will be back with another video very soon till then bye
|
Ambiguous Coordinates
|
design-hashset
|
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s.
* For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`.
Return _a list of strings representing all possibilities for what our original coordinates could have been_.
Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`.
The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)
**Example 1:**
**Input:** s = "(123) "
**Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\]
**Example 2:**
**Input:** s = "(0123) "
**Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\]
**Explanation:** 0.0, 00, 0001 or 00.01 are not allowed.
**Example 3:**
**Input:** s = "(00011) "
**Output:** \[ "(0, 0.011) ", "(0.001, 1) "\]
**Constraints:**
* `4 <= s.length <= 12`
* `s[0] == '('` and `s[s.length - 1] == ')'`.
* The rest of `s` are digits.
| null |
Array,Hash Table,Linked List,Design,Hash Function
|
Easy
|
817,1337
|
217 |
is a collaboration with programming knowledge in this video we'll solve contains duplicate the 217 lead code problem so let's start with the question given an array of integers find if the array contains any duplicates your function should return true if any value appears at least twice in the array and it should return false if every element is distinct so if the unique elements in the array we return false and if the even one appears more than once or at least twice then we return true so the examples here are one two three one so since one is uh appearing at least twice the output is true one two three four all unique elements so the output is false and here you have a lot of ones threes and fours and twos so the output is true so uh here we don't have any uh constraints regarding the problem uh where the array should be the size of the array is less than 10 power eight and pass seven or something like that so this is something which uh we can ask the interviewee interviewer the to make the question less ambiguous so that you have more knowledge and you know what to apply to a question so something which lead code here has also done is they've written that so you can actually ask that in the real interview uh to get a better clarification the next thing which you can ask which shouldn't actually make a difference but it's also good to ask is whether the array will include negative numbers and 0 or not and for edge cases whether the weather or the ra can be 0 or can there be an empty array and things like that so once you're done asking the first thing which comes to my mind is that here to check whether a value appears more than once we have to maintain the count of each and every element and once we have the count of all the elements of all the unique elements then we can check if the count is more than one so if it's more than one then uh definitely it's appearing at least twice so or field and false and if we do that for all the array all the elements of the array and if none of them have more than one then we just return false because every element is distinct so to maintain the count of all the unique values in the array we can use a map or a hash map so in c plus we just use a map and shouldn't matter much regarding the time complexity because uh we are trying to do this in ofn uh algorithmic wise and also uh the space constant or the space complexity is often here because in the worst case the hash map or the map in c plus can uh have all the n elements of the array and yeah so let's start implementing this so we need a map here which has the count and we call this account map as well uh the next thing is we what we need to do is loop through the array nums dot size and now what we do is we first check if uh the count uh in the map is more than one so if count map so let's count map oh sorry count map of numbers of i so if this value is one uh then obviously we cannot add another one or which indicates that this value is appearing more than once so we just do a return false and if it is the first time we're encountering a number then we just add that to the um count map so count map i plus so here we tell uh the corn map that we're adding or actually adding an element to r and the frequency of that element to our map and once we have looped through the entire array and we haven't found anything which returns false then by default oh sorry turn true because we found a value japanese twice and if we find nothing or no values which are appearing at least twice we just return a false so reread the code before you uh press run code or submit because you don't want to exploit that run code submit button multiple times just to see what you've done wrong because in the real situation you will not be having a run code or submit button you will have to probably write the code on a google doc or on a piece of paper and then on a whiteboard and then discuss that with the interviewer so here you have account map or the variable names look or decent you look through it then if you encounter one which is already there then you return true because uh it means that there are at least twice of that present in the array and if there's not and if it's the first time encountering an element then you increment the frequency and if you look through the entire array and you don't find any element then you return false so let's run it now and the run call test case is true and now let's do a submit and let's see so we have a success which is 46 times faster we could have made this faster with a boolean here just to see if it's a yes or no and then you can actually run it again or you can also maintain a frequency array and you know you do that to actually increase the speed of them or decrease the memory so yeah this is how you solve uh lead code contains duplicate 217 thank you for watching i'll see you in the next one
|
Contains Duplicate
|
contains-duplicate
|
Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** true
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Example 3:**
**Input:** nums = \[1,1,1,3,3,4,3,2,4,2\]
**Output:** true
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Sorting
|
Easy
|
219,220
|
15 |
hello and welcome back to the cracking vein YouTube channel today we're going to be solving lead code problem number 15 threesome given an integer array nums return all the triplets nums of I nums of J and nums of K such that I does not equal j i does not equal to K and J does not equal to K and the nums of I plus nums of J plus nums of k equals to zero notice that solution set must not contain any duplicate triplets so essentially what we're looking for is three distinct values here in our nums array that actually sum up to zero so let's look at an example here where we have minus one zero one two minus one four so what we could do here is we could have well look we have a minus one and one which cancel each other out and we also have a zero so if we do minus one zero one obviously this will just sum up to zero so that is a solution uh let's see what else we could have here well we see that we have a two and we see we actually have two negative ones so we could go minus one uh two and that would also give us a sum of zero which is what we want and I think these are the only two triplets that we can actually form here so relatively simple when you're actually looking at it you know on paper but how do we actually code this up well we're going to do something um that you can actually apply to the problem to some and you can also apply to foursome and if they ever come up with five some then you can probably apply it there as well although it's going to be much more complicated so the first thing that we want to do here is actually sort our array and it's essential we do this because our approach won't actually work and you'll see why we want it sorted in a second so let's sort this and we'll see that we get minus four uh we'll get minus one zero one two so now what we want to do is we essentially just want to basically try to build every single combination inside of our array so what we're going to do is we're going to have three pointers i j and k obviously uh because you know that's what we've been told to do and we're going to put I originally at the beginning of our array and what we're going to do is we're going to put J to whatever I plus 1 is so this will be J because it's one index before and we're going to put k at the very end of the array now what we're going to do is we're going to add all of the values at our indices i j and k so let's see what that is so that's minus 4 for I we're going to add minus 1 and then we're also going to add 2 to this so what does this equal so this is minus 5 apologies for the sirens in the background uh so this is going to be minus 5 plus 2 which is negative 3. so obviously negative 3 is not uh zero right so this combination is not a answer here but let's notice two things there's three cases here right so either the number that we sum up to it equals to zero right equals to zero or it's greater than zero or it's less than zero right those are the three possible cases if it equals to zero great we found a solution we don't have to worry about it anymore if it's greater than zero well we have to find a way to actually reduce this now this is where why we actually sorted let's think about this our array is sorted that means that as we go from left to right the numbers get what they get larger right they start small and then they get bigger as you go to the right because that's how we've sorted it and the inverse is also true if you go from right to left the numbers get what smaller so we now have a sum that is too small right this is smaller than zero so we need to find a way to increase this value so what are we going to do well we want to keep our eye fixed but what we're going to do is we're actually going to now that we have too small of a value we're actually going to increase our J because that way we know that we're going to be getting a bigger value if we simply go to the right with the J in this case J is actually the same for these two indices so we're not going to basically consider it we're actually just going to move to the next one because we want to just consider the next largest value because obviously if we just tried one and then we're going to try the same value we're not going to get a different result so now let's see what happens with those values so again we're going to add them so we're going to say 4 and now J points to 0 plus K is still here at 2. so that means we have minus two so we got a little bit closer to zero but we're not still there so that means that we need to increase J one more time so now we're going to go to J and we're going to make it 1 right so now let's do the math again so we're going to say 4 plus 1 plus 2. this time we get to What minus one right so unfortunately um you know we still are less than zero which means that we have to increase J One More Time but you'll notice that now J is at the same index as k so even though this would work four plus two equals zero even though technically that equals to zero remember that the indexes cannot be the same they have to be distinct indices which is why as soon as J hits K or k hits J then we cannot have that as an answer so now what happens is that having this I here was not correct so now what we need to do is let's just redraw our array so we're going to say minus four minus one zero one two so fixing this I here was not correct so now what we want to do is 4 is no longer going to be considered because we tried all the options with four and it didn't work so now I will move up by one and now I will start here and we're going to fix it for the whole iteration and we're going to do the exact same thing j is now going to be whatever I plus 1 is at the beginning and K will always be at the end here and now we're going to go through the same logic so let's try adding our values so we're going to say -1 -1 -1 plus minus 1 plus 2. and this time we have zero perfect so now we found one solution right so we have minus one two is a possible solution so now what we want to do is we know that we can't really do much here right if we increase our uh I uh sorry if we increase the J then we can't really do much right so we could potentially try moving either of them uh in a direction and hopefully that will do it so in this case when you actually have a solution that you find what you want to do is simply just move one of them and then keep trying and essentially what we want to do here is this same process every single time so remember that there's three cases either our sum is going to equal uh zero in which case we found a solution and we can move we'll just say we're going to move j every single time we find a solution we could either move K but it doesn't matter so we're going to move j if it's too big that means that our sum needs to be reduced so the way that we get a smaller number because it's sorted is actually going to be by moving the K index down by one if our number is too small then we need a bigger number and we're going to move j up by one so those are our three cases and essentially we just need to try this for all possible combinations and that's the approach that we want to take we'll always start I at the zeroth index J will always start one indexed to the right of i k will always be at the end of the array and then we'll try all of the options that way after we've exhausted all of the items you know between J and K so we'll basically have while J is actually less than k will then after that no longer holds true then we will move our I up by one and we'll keep repeating the process where J is always going to be started at I plus 1 and K is always at the end and that way we will basically go through every single option and we will then you know figure out which ones equal zero and at the end we just return the list of all of those answers so that's the general intuition that's also the reason why we sorted the array remember that when it's sorted when you're going from left to right the items will always increase and from right to left they'll always decrease which is useful for when our number is too big and we need to reduce it or when our number is too small we need to increase it if it's zero we found an answer that's the sweet spot but that is the reason why we sorted because we know that if it's too big we can just move our K down to get a smaller number because obviously anything to the left will always be smaller by definition in a sorted array and the same thing for this one so hopefully that makes sense if not don't worry when we walk through the actual code editor uh it should be much clearer I'll go through line by line and you know there shouldn't really be any doubts at that point but I hope this explanation uh was useful I think that this question once you understand kind of why sorting helps uh and how we move the pointers based on the value here um then it's really not too bad to understand so what I want to do now is I think I've talked for long enough let's go to the code editor and actually write this code I'll see you there back in the code editor let's type this up remember that the first thing you want to do here is actually to sort our numbers so we're going to say nums dot sort and that will do it for us in place we also want to define a result array to store our results and we want to set our first index I to be equal to zero and now we want to set up our Loop which is going to go from left to right over the array so we're going to say while I is actually less than Len nums minus two and the reason we do length of nums minus two is remember we need three indices here I J and K okay and if obviously there's not three indices then we can't do anything here so that's why we always need to make sure there's always room for the J and the k which is why we leave a gap of two always so now what we want to do is we actually want to make sure that we don't have duplicates in our solution which means that if we found a potential solution in the eye what we want to do is we actually don't want to consider a same eye remember that the array can contain duplicates but our answer may not so if we have an i and then we increment I and it's actually the same value we'll introduce duplicates so for that reason we need to actually when we increment our I or when I changes it actually needs to always make sure that we don't have a duplicate so the way that we're going to do this is we're going to say while I let's uh while I sorry I is greater than 0 and less than length of nums minus one what we're going to do here we're going to say nums of I uh sorry while the indices are correct um and uh nums of I actually equals to numbers of I minus one what we want to do here is we actually just want to increment our I and what we're doing is we're essentially checking is our current I equal to the last one um and is the indices valid and it's important that you check this greater than zero condition because if you don't do that in Python you'll actually wrap to the end of the array because you won't get an index error for accessing negative elements you'll just go to the back of the array and your answer is not going to be right here so you need to make sure that you have the correct balance and you also need to make sure that you check for whether it equals and in that case you want to increment your eye to make sure you don't get those duplicate values okay now that's out of the way we know that we always want to set J equal to whatever I is plus one uh when we start our second Loop and K will always equal the length of nums uh minus one so basically the end of the array um now what we want to do is remember we need to be moving our J and our K pointers so we're going to say while J less than k what we're going to do here is we're going to say that the current sum of our three pointers is going to obviously be nums of I plus nums of J plus nums of K right and we can have three cases the current sum can be zero which is a solution it can be greater than zero which means that our number is too big so we need to find a way to decrease it and it could be less than zero which means it's too small and we need to figure out a way to increase it so let's do the simplest case first which is that uh cursum is actually zero so we're going to say if not cursum we're gonna say res the append so obviously that's a solution so nums of I and I apologize for the really annoying sirens in the background I hate it as well uh we're gonna say nums of I nums of J and nums of K um those are going to be your you know solution values and now what we want to do is we want to since we have a solution we want to just move j and k up so we're going to say J plus equals to 1. and similar to what we did with I we actually make want to make sure that we don't have duplicate values so we're actually going to make sure that we move j up until we get a Fresh Value that we haven't seen before so we're going to say while J is actually less than K and nums of J uh equals to nums of J minus one what we're going to do here is we're just going to move j up now what we want to do is we also want to decrement K because we found a solution with our K so we can move it down because we know that um we can't reuse that K again so we're going to say while K is actually greater than or equal to J and nums of K actually equals to nums of K Plus 1. in this case we just want to keep decrementing our K until we get a Fresh Value That's Unique so that's what we do when we have a sum equaling to zero the other case is that curse sum is actually too big and the way that we're going to make it smaller is by getting a smaller number remember that our array is sorted so if k um is at the end then moving it to the left will give us a smaller number so we're actually going to move K down so we're going to say k minus equals to 1 and again we don't want to have um duplicate values so what we're going to do is we're going to basically copy this code here and double check that we move our K as much as we can to avoid any potential duplicates because we'll just end up processing a value that we shouldn't have and it's much easier to do it this way so the last case is that current sum is actually less than zero in which case this is the case where we need to make it bigger and the way that we're going to do that is we're going to be moving J up because obviously moving that pointer will give us access to a bigger element because again the array is sorted so we're going to say J plus equals to one and like we did before we can actually make sure we don't end up on a duplicate um by simply moving our J forward as long as there's a duplicate now what we want to do is once this Loop breaks for while uh J is less than K now we have exhausted all the possible combinations of J and K while we kept our I fixed now what we want to do is we want to increment our I and then we're going to try all again the possible combinations of J and K now that I is fixed at this new value and we'll essentially do that uh while I is less than length of nums minus two we will continuously generate all of these values we will populate our result uh when we see fit and at the end obviously our Loop will break and when that happens let me just line up the actual uh functions here all we need to do is simply return our results so let me just run this make sure to make any syntax mistakes because the indentation can get a weird and let's submit it and hello okay wait what happened accept it all right cool I'm just worried that for a second um let's now get rid of this and let's talk about the time and space complexity so for the time complexity obviously we have a sort here which in Python is going to be an N log n operation um but what we do here in our double while Loops since we're basically going for every single combination our time complexity so we have the N log n from the sort but then we have to generate every single combination here uh which means that this is actually going to be N squared so the N squared will actually dominate asymptotically which means that in the end this is just going to be a big O of N squared solution because the N squared of our double while Loops here will actually be greater than this n log n so we don't have to worry about it there for the space complexity uh we're not going to consider the actual results as space because we need to return it but you may think that this is actually a constant space solution unfortunately it's not if you do a sort in Python even though it's in place this does actually require extra space and in Python I believe sorting is a log n uh space so it's not free um it I guess it is easy to think that it's free because it's in place and you think that it modifies it but it does actually use extra space so be careful with that because if you said that the space complexity was actually constant uh your interviewer might ding you on that so do be aware that sort is not actually a constant space uh thing so even though we don't Define any extra space I don't count the result as extra space because you need it to return here like you have no other choice um so that's the reason why it's going to be Big O events so time complexity N squared um space complexity Big O of N squared that's how you solve this problem I think it's relatively intuitive you keep one pointer fixed and then you move the other two especially with the sort you can kind of think about it in that if your answer is too small then you want to move one of your pointers to the right because that will give you a bigger number by definition numbers to the right of a current index in a sorted array are greater than or equal to your current value and similarly if a number is too big going to the left will always give you a value that is either less than or equal to your current value because obviously they can be the same but most of the times you'll get a smaller value going to the left so that's the general intuition hopefully that all makes sense clears it up this problem is quite fun uh I definitely had this an interview way back when and yeah it's one of my favorites uh it will always be in my mind because of that anyway I'm gonna stop blabbing because this video is probably almost 20 minutes long if you enjoyed the video please leave a like and a comment it really helps me out with the YouTube algorithm if you made it to the end let me know in the comment section below if you want to see more content like this subscribe to the channel if you want to join a Discord Community where we talk about all things Fang interviewing um system design you can have your resume reviewed by me you can ask me questions join the Discord I'll leave you link in the description below otherwise thank you so much for watching if you made it to the end you're a hero thank you and I'll see you in the next one bye
|
3Sum
|
3sum
|
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`.
Notice that the solution set must not contain duplicate triplets.
**Example 1:**
**Input:** nums = \[-1,0,1,2,-1,-4\]
**Output:** \[\[-1,-1,2\],\[-1,0,1\]\]
**Explanation:**
nums\[0\] + nums\[1\] + nums\[2\] = (-1) + 0 + 1 = 0.
nums\[1\] + nums\[2\] + nums\[4\] = 0 + 1 + (-1) = 0.
nums\[0\] + nums\[3\] + nums\[4\] = (-1) + 2 + (-1) = 0.
The distinct triplets are \[-1,0,1\] and \[-1,-1,2\].
Notice that the order of the output and the order of the triplets does not matter.
**Example 2:**
**Input:** nums = \[0,1,1\]
**Output:** \[\]
**Explanation:** The only possible triplet does not sum up to 0.
**Example 3:**
**Input:** nums = \[0,0,0\]
**Output:** \[\[0,0,0\]\]
**Explanation:** The only possible triplet sums up to 0.
**Constraints:**
* `3 <= nums.length <= 3000`
* `-105 <= nums[i] <= 105`
|
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
|
Array,Two Pointers,Sorting
|
Medium
|
1,16,18,259
|
648 |
hello friends so today in this video we will be going through a problem from lead code problem name replace words so i'll tell you in simple terms what the form statement states it's not too difficult problem but still if you want to learn hashmaps and hash techniques then like why hashing is required why set hash map or maps unordered list can be used in c plus why they are important then you can watch this video so the problem statement is from lead code is a media problem it states that i'll tell you simple terms it states that you're given a dictionary and you're given a sentence now whenever you find out a valid prefix which matches with the dictionary value you have to replace that word with the dictionary value in simple terms that you can see the sentences the cattle was rattled by the battery now though is not in the dictionary but if you find out some valid prefix which is in the dictionary as you can see the cat in cattle is in the dictionary so replace cattle with cat was not in the dictionary rattle rat is a dictionary so replace it with the word itself which is rad so find out whether there is some prefix which is in a dictionary if it exists then just replace that prefix with that word in that like in this final sequence and then you have to print out the whole sequence but now if there is a dictionary in which there are some words which like almost same then you have to replace that with the smallest word possible which means that okay if in this sentence there is four is okay now you have to just find out the smallest prefix which matches out so a also is in the dictionary which is matching so just replace this with small a which means that if there is a smaller prefix if you are going through the prefixes and matching in a dictionary and if you find out the smallest prefix which matches out then just replace it with that prefix you don't have to find out the whole new prefix which matches out so i hope you understand the problem statement now so what you can easily do in this problem statement is you have to first iterate over the whole string and then just keep track of the prefixes of each word whenever the prefix matches out at the at that given point just replace down that prefix in the new sequence which is your other new sentence which you are forming out and then just go to the next word okay so it means that i'll tell you in simple terms let's assume that we are looking at this sentence we'll keep on iterating this word and keep on making the prefix of it so as you can see t h e when you come to the end of this word which means that you have faced a space that means that i have iterated over the whole prefix but still i haven't found out anything in the dictionary so we'll go to the next one so i have now making a prefix which is c then a and t at the same point when i found out t then i can easily see that okay cat is in the dictionary so replace this cattle with cat in the final step like sentence and now because i am at t i am making a prefix so i am moving from left to right and i am at t so it means that the complete word is not completed like the word on which i'm iterated is not completed so you have to go to the next page the space defined that's what is completed so do a while loop and go from this t to the next space you can find out and then again start doing this that just start making prefixes of the words and whenever the prefix matches out put them in the sentence if it doesn't match out you find out a space without finding out a prefix then put the whole word as it is and then go to the next step and that's the whole problem it's not too difficult but still i have discussed it so that you can understand like how you can match them out now to match them you can make a map or like another map in c plus but because you don't map store house the word and its frequency okay a key value here but now we don't actually need a key value here for fast searching what you can do because you just want to search that whether this word is presented dictionary or not so you can use a set because set only consists of single words which means that they should be like uh like this would be not identical okay and obviously dictionary doesn't consist of identical words so you just make a set of strings and then insert all the dictionary words of this words which are the sentences in this string because they are stored in the sentence this words and then this is the new answer which you have to print out and this is because in the end every word is marked by a space i always say that because in sentences like whenever this word completes out you can say that this word is completed out with the mark of a space but in the end word there is no space so you can like intentionally push a space at the end of the sentence so that you can obviously like you can iterate from left to right and whenever space is encountered it means that the word is completed but for the last word there is no space so you can like push a space at that so that you can easily it over the whole string then this is a temporary variable to store out the prefixes then iterate over the whole string from left to right whenever you find out a space which means that now my word is completed but if my word is completed i haven't found a valid prefix which means that if there is no valid prefix i have to insert the word itself so the word is stored in temp so add 10 in the answer which is the final answer and now add space because for every word like insert that word in the character and then a space so it's like i'm inserting the and space then yeah then go to the next word and make my temp empty so that i can redo the next word else i will what i'll do if it is not a space if i have not encountered a space i have some words then i am actually making out a prefix it is making a prefix in attempt at any point if i found out that this prefix is present in set then what i'll do i will take that prefix because that prefix is present in the set which means that is in the dictionary so i have to insert it in the answer string so after insert it in the answer string and put your space like this again make the temp empty and then my eye is not at the end which means that my eye is in the middle of the some word so i have to make it to the next space so i will do a while loop till i haven't found out the space and i will increment my eye and then when i found out incremented i will just go to the next word and so on and at the end because we are inserting in this format which means that i am inserting a word and a space word in space so in the end i have a word and a space but i don't want to go like last space in the end which means that as you have seen i have intentionally added a space in the end to find out another word but as you are doing the same procedure again we are inserting a word and a space word in a space so for the last word there will be a space ahead so i have to pop out the last space so that's what i'm doing pop out the last space and then we just print out the or like returning out the answer string i hope you understand the logic and the code for this problem if you still have any doubts you can mention it on a coin box uh you can pause the video to see the code from this and i'll see you next time until then keep coding and bye
|
Replace Words
|
replace-words
|
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`.
Given a `dictionary` consisting of many **roots** and a `sentence` consisting of words separated by spaces, replace all the **successors** in the sentence with the **root** forming it. If a **successor** can be replaced by more than one **root**, replace it with the **root** that has **the shortest length**.
Return _the `sentence`_ after the replacement.
**Example 1:**
**Input:** dictionary = \[ "cat ", "bat ", "rat "\], sentence = "the cattle was rattled by the battery "
**Output:** "the cat was rat by the bat "
**Example 2:**
**Input:** dictionary = \[ "a ", "b ", "c "\], sentence = "aadsfasf absbs bbab cadsfafs "
**Output:** "a a b c "
**Constraints:**
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 100`
* `dictionary[i]` consists of only lower-case letters.
* `1 <= sentence.length <= 106`
* `sentence` consists of only lower-case letters and spaces.
* The number of words in `sentence` is in the range `[1, 1000]`
* The length of each word in `sentence` is in the range `[1, 1000]`
* Every two consecutive words in `sentence` will be separated by exactly one space.
* `sentence` does not have leading or trailing spaces.
| null |
Array,Hash Table,String,Trie
|
Medium
|
208
|
1,015 |
hello this is wagga we're going to do another legal question the question in question is 10 15 smallest integer divisible by k right so we are given um you're given a positive integer k and you are supposed to find the length of the smallest positive integer n such that n is divisible by k and n only contains the digit one right so you're given that we could look at the examples you're given k and um the answer is one because n a one divided by one is going to be one uh you're given two the answer is negative one because there's no positive possible positive integer that could be divisible by that and you're given three and um the answer is triple one because um one has a length um has a length of three and is divisible uh by that right so how would solve this is there's a pretty intuitive way we could use right so you're told here that um you want the smallest positive enter integer n such that n is divisible by k right so um and it only contains the digit one right so if you write all our numbers if you write if you look at all numbers right one two three four five um six seven eight nine and zero the first thing you note is that um since all the numbers uh are made up of ones right where they're going to have 1 11 111 in that order there's some numbers whose multiples can never end up with one right one number one such number is two right so we could get rid of 2 is not to be considered because there is no possible way that 2 could um any multiple of 2 could end up with a 1 right the same is true with 4 the same is true with 6 basically all the even numbers right so you could get rid of these numbers like so we have one three five seven and nine to be considered for starters another number we should consider is um five right all possible multiple to five and with um with either zero five right so we should get rid of it but there are possible multiples of one that um end with one right like one times one and also if you multiply three by seven you get um 21 which end to the one right so it's possible that further along the line could have all ones that end up with one seven times three is twenty one so it's possible nine times nine is eighty one which is also uh within our realm of possibility right so um the first thing we would do is uh we would try and check um the modulus we could get the modulus of the number and if the modulus of the number like if the number we get the number k right if k the number that we're given and we get the modulus if we divide it by 10 if it's not among the numbers one three seven and nine we know to discount it because it's there's no possible way that integer could be divisible by um could be divisible by numbers that are all one right so that's the first thing we would do and then afterwards we just look through and check um the modulus if ever we get the modulus of the number and we start off with one and then progressively increase it by increasing to 11 and then 111 like so on and so forth and see that if we ever return uh the fact um return the length after we get uh the modulus by dividing it so first things first we check if k if we get the modulus of k by 10 if it is not in the possible um if the remainder is not among the numbers we discussed if it's not among one three seven and nine right so if it's not among one of them um we just return negative one like so right so that means that um there's no possible way k can be divided um we can get the smallest possible integer only containing ones right so the next thing we need to do is um we need to start off our number and we could say number is going to start off as one and um and after that what we need to do is um we need to check uh we could also have something len length okay we have to spell it out correctly in full to have length equals one and we check while true so that you can loop through or you could say um yeah while true and um we say if num modulus by k is going to be zero what we need to do is return true right so um we'll start off at one of course and then after that what we need to do is we need to increase the length by one and then um increase the number and how we make the number how we convert 1 into 11 is pretty simple right we take num we multiply it by 10 then we add 1 right so it will do it will convert 1 into 11 and then 11 into 111 and then 1100 and so on and so forth right instead of returning true we're supposed to return uh the length right so we come here and we say length rather than true right so in that situation we convert it we try to convert it now um to submit it and if we submit it hopefully it will be accepted this time okay so it has been accepted right um since we loop through uh okay um it's going the time complexity is going to be uh o of um the time complexity is going to be trying to think about the time complexity it's going to be o of we the structures we create are not i think are constant right so for the stress complexity uh it's going to be one because we only create uh this k here which is um for elements so the space is going to be straightforward one but the time complexity um is going to be let's call it over one the time complexity is going to be over one pretty straightforward and yeah basically that thank you for watching subscribe to the channel i'll see you in the next video
|
Smallest Integer Divisible by K
|
smallest-integer-divisible-by-k
|
Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`.
Return _the **length** of_ `n`. If there is no such `n`, return -1.
**Note:** `n` may not fit in a 64-bit signed integer.
**Example 1:**
**Input:** k = 1
**Output:** 1
**Explanation:** The smallest answer is n = 1, which has length 1.
**Example 2:**
**Input:** k = 2
**Output:** -1
**Explanation:** There is no such positive integer n divisible by 2.
**Example 3:**
**Input:** k = 3
**Output:** 3
**Explanation:** The smallest answer is n = 111, which has length 3.
**Constraints:**
* `1 <= k <= 105`
| null | null |
Medium
| null |
743 |
Hello hello guys welcome back to take admission in this video you will see the network delete problem Vishram customers alarms and this problem can dissolve very easily but this free mode driving direction of only one-third interviewer direction of only one-third interviewer direction of only one-third interviewer intuition for the second and third notice from the list Number 733 Show Latest Read The Problem Statement Giving Network Notes Live With 0 Times Earliest To Travel Time From Zip Code To U We W Viewers No Weer Is The Destination O W Is The Time Possible To Travel From Person Midway Between You To No Signal From Which Is The What Is The Language Of The Impossible Will Return - 1st Id Porn Will Return - 1st Id Porn Will Return - 1st Id Porn Travels All The Note So Let's Look At The Example In Order To Get Better Understanding Know Latest Subscribe To This Z2 S You Can See From 2nd Id 2nd Subscribe Now To Subscribe My Channel Like This Thursday Subscribe You Wait For Someone To Withdraw From All Sorts Neend Signal Also From This Point 0.2 Find The Neend Signal Also From This Point 0.2 Find The Neend Signal Also From This Point 0.2 Find The Time Taken By The Signal To Cover All The Nodes And Wick And Research Find The Minimum Time Tourist For This Withdrawal Notes from others but not to look at his photograph and disputes and signals from this time is the loot-loot 2f 2 and subscribe the loot-loot 2f 2 and subscribe the loot-loot 2f 2 and subscribe the longest time for this Note 3 times and what is the time in order to avoid food at first sight or Not to money water also time taken from 4 you can restore to in time two for you can restore three layer time to plus 3 but from ur valuable tourist rush one world it is not possible for sending a signal from this note 4 not able to cover All Notes and Signals Not Able to Cover The Internet for Widening - Not Able to Cover The Internet for Widening - Not Able to Cover The Internet for Widening - One Which Does Not Possible to Cover All Problems Important Observations from This Problem Fish And Always Consider The Short Time Inverter Tourist To The For This Noble Cause I Want To Minimize The Time Taken In Order To Cover All The Notes I Want To Minimize The Time Will Always Be Taking The Time To Find The Hotspot Between To 99 Subscribe 90 Time Does Not Know Why Didn't Do Any Time To 90 Time Does Not Know Why Did Not Do Any Time Not 200 Internetworking Gautam Video Liquid subscribe The Video then subscribe to the Page if the Video then subscribe to the Page if you liked There will be nothing but the distance from this is a separate topic the forest note distances now in this is the distance is Three layer for the answer will come out with which will win the time taken in order to cover all no weir will release the value of infinity and only source of will keep updating the distance to do go to 9 Oil Co Maximum Welcome To The This Will Be Returning Minus One So This Is Very Simple Logic To Apply Using Destroy Them Only Important Thing You Need To Understand How To Apply Textile Gautam First 100 The link for Live Video will represent introduction blue you can go and check the don't know before moving onto the native with beneficial fashion more taking every day in a latest research from this is the latest to like subscribe and distance can be measured in terms of That's value in terms of adequate security measuring in terms of the way they will work very fine but even depending on that film Saugandh this is it means the will not determine which given the 45 to 0512 409 plus 101 Subscribe Now to point different Meaning of subscribe my channel must subscribe peer giver customer develop this place for the distance a lot in this question addon se list records will be using structure in order to understand value notes 2018 19 two and three layer and also withdraw into the distance 143 subscribe to the Page if you liked The Video then subscribe to the Channel Well Wishers Vardhak You Know Details Or Later Nor Will Be Taking The Distance Celebs Ko Minimum Distance Delhi To Notes From Initially Only 1000 Picture we solve will be the volume maximum know what is the distance to the giver and subscribe And subscribe The Amazing and subscribe must subscribe this is the distance from source is oneplus for which will be 500 this is the structure of this cream and structure has been SCHEDULED IN SOLVING IN ALL THE STRUCTURE LATEST UPDATES WILL START FROM THIS POINT NOTE 0102 SUBSCRIBE 9999999999 TO END DISTANCES 120 MAXIMUM KNOW WHAT IS THE DISTANCE TO WHICH WE CAN REACH FROM NOTHING BUT A DISTANCE FROM SOURCE LOVE STORY * FROM ONE SO ONE ITSELF IS THE Source Code * FROM ONE SO ONE ITSELF IS THE Source Code * FROM ONE SO ONE ITSELF IS THE Source Code 1000 And In Order To Reduce To The Distance Values But One Which Is The Total Distance Values But One Which Is The Total Distance Values But One Which Is The Total Distance 2000 Volume Maximum Minimum One Is The Way We Are With You When You Will Have To The Total Distance To The Distance From One to three to the total distance 2012 song distance jis maximum rakho mobile mein ustuk minimum of two ko maximum which will come out with two 9 to switch off date will have to 593 ko murder total distance value inverter tours from 0001 to 9999 looter do And you can see what is the distance to 9 to the Video then subscribe to the two is the distance id quit from two for this point to that total distance between five one plus 4 no what is the distance and Forests maximum 100 IS and soldiers will get updated with setting of the total distance from source to the giver 4999 total distance oneplus 5t maximum place value will setting subscribe this three and distance Delhi to the notes35 person 102 vacancy date will have already on Maximum Vya But With The Distance To MP3 Love This 225 Already Present Tense 610 Will Get Updated And They Will Send You Will Be Distancing 9999999999 Subscribe Note Subscribe User Name And Fame Not Been Completed 100 10,000 First Not Been Completed 100 10,000 First Not Been Completed 100 10,000 First Step And Second Step Is Well Traveled Through This Distance Sexual Tweet Exactly Maximum Value In This Case Maximum Value Is Equal To 500 Time Taken In Order To Cover All Notes In The Graph Venue Subscribe To Student's Notes From This Is Not The Volume Maximum Not Possible To Cover All Notes By Sending Signal - Subscribe Apne Notes By Sending Signal - Subscribe Apne Notes By Sending Signal - Subscribe Apne Dad Find the Maximum Distance of All the Notes and Travels Notes of Not Troubled and Will Return Minus One Time Complexity Is Contra Voucher Services Pay Student of the Year This is the structure in order to gather notes in class-6 and gather notes in class-6 and gather notes in class-6 and class- 9 subscribe and subscirbe's class- 9 subscribe and subscirbe's class- 9 subscribe and subscirbe's 100th post and avoid distance to maximum will be thanks bf that this is the crop and nine ten is traversing the notes in this edition you will continuously updated distance values in order to distance values in order to distance values in order to receive whenever something like this is the distance Delhi to Get Updated With Continuously In Middle Age Person Will Always Be Minimum Distance To Do Subscribe Maximum Volume Maximum Value It Is That Was Not Visited Recently Visited AIDS Arvind Signal Will Not Be Able To Traverse Through All The Note Servi Minus One Another Is Not The Question Will Be Continuously Updated and Time Volume Maximum They Will Be Written in Different Languages Every One Can Benefit From Like Share and Subscribe My Channel
|
Network Delay Time
|
closest-leaf-in-a-binary-tree
|
You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target.
We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`.
**Example 1:**
**Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2
**Output:** 2
**Example 2:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 1
**Output:** 1
**Example 3:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 2
**Output:** -1
**Constraints:**
* `1 <= k <= n <= 100`
* `1 <= times.length <= 6000`
* `times[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `0 <= wi <= 100`
* All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.)
|
Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.