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 |
---|---|---|---|---|---|---|---|---|
219 |
hey everybody this is Larry this is day 21 21st of the October Lego day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about trying to find extra 10 points about this poem contains duplicate 2 which is a easy poem supposedly which is great because I'm really tired right now San Francisco is tiring me out uh along amongst other things so uh so let's get this started let's finish quickly and then see where it goes it should be pretty okay right so we turn through the two distinct we're absolute I and J is less than or greater than k um what does that mean that means that the two uh the duplicates where the indexes is very close so you could have do like a I think this is a sliding window but to be honest I hmm my first instinct is sliding window and it's you know three lines of code but I was like huh that doesn't feel like a easy or at least it's a very hard easy so I think that's a little bit awkward but maybe not a big deal so let's just do it so yeah so we have uh you know window maybe as you go to collections that counter and then now we have four no I mean you know maybe I shouldn't prematurely optimize I just gotta get this um yeah this is gonna be linear time in your space uh but yeah it's a window of num sub I we increment right and then if I minus k is it so now we're looking backwards so I'm just going to make sure I get the indexes right so this is one then we look back to three right so okay so if this is I just want to make sure I mean then window of knocks up I minus one or minus K uh divided by one right and here um I guess we actually could check beforehand right so yeah if foreign true otherwise we return first and I think that should be sufficient maybe off by one but otherwise sufficient uh looks okay here let's give it submit mostly because I'm lazy hopefully yeah uh yeah 934 day streak um that's pretty much all I have um this is like I said linear time linear space this is just a very rudimentary sliding window which I wouldn't say is difficult um in your journey of practicing and becoming better at these problems you should be able to do these things proficiently but I would also not say that this is easy per se so maybe there's an easier way I don't know but um yeah I don't know but uh but that's all I have for today though because I am only 41 I do people force or something what is the wrong answer not quite sure okay anyway that's what I have for today I have a morning flight I'm very tired that's all I have so stay good stay healthy to good mental health I'll see you all later and take care bye
|
Contains Duplicate II
|
contains-duplicate-ii
|
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:**
**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true
**Example 3:**
**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `0 <= k <= 105`
| null |
Array,Hash Table,Sliding Window
|
Easy
|
217,220
|
759 |
I was solving beat code problems and I was not planning to make videos of the problems that are provided but I found this one that is very interesting in the day it is not interesting for the problem itself but for the possible solutions this program 69 from the friendly and consell free time and what it is about is that they are going to give us a there is this class called interval and in this type of interval come well the work intervals of a series of employees for example in this case well in this is an employee this is another employee and this is another employee of ours are the hours that this employee is working so in few unemployed people what you should see is the hours in which no employee is working that is what the price is about typical problem of write a link that is He does in other programs pay attention so what caught my attention because really those types of problems are that of insomnia this one is then interesting because the advances that as a child normally happen with politics and that's what I did in this one but it doesn't work by a politician and that is to say why what we are going to do is we don't really care if there are 20 employees, two employees or one employer the amounts at the intervals of causes headquarters order the intervals by stark what is this and if the two are the same decision we are going to order ourselves therefore no so in this case it would more or less look like this it would look something like this so if you sweep this by removing the elements the first let's say that the first element continues from infinity to 1 not because it starts at 1 and we are going to take out this youtube to find out if the value of big in the heights is larger than the value of ende of the previous one then yes it is this one like in this case that from 3 to 4 yes it is so we are going to put a element here no and this is the result 3 4 it seems like something super simple no but it is not like that if you organize an aperitif for example when there are much more elements in fact over here I was playing and for example in this example here which was The example that I didn't get is an example because it is very long, you have many employees and many elements and things like that, when you get to the priority, the policy that does not guarantee you an initial order, which is easy to forget, in this exercise, the order is very important. What the apparent thing is that it always guarantees you is that the head element is going to be according to the comparator, that is, the elements above and below are going to be according to the comparator, but for the elements in the middle it does not guarantee an order. No, then that is a problem that is done with a tris, so if you use a trichet for this program, this is because it is very easy via another solution out there, this one, and they make too much of a mess. There is a solution that I like called monos de chavín here. which is called line sweep which is worth it for you to see it is so easy this solution was also enough the good solution is this so the rock to do is to create our the result that we want to make which is going to be the list of intervals this and we are going to simply take the intervals from this list and we are going to put them in a tris and now we have to make this twitter a buyer not to seem like the comparator we are going to do something like this if this art is equal to knit starts no if they are both the same let's go to do something and if we do the same then we are going to order them according to the andi and if not we are going to return them according to we are going to order according to the start e then the things and we are simply going to enter the left and what is going to be and his resignation of winning three sets is sad an inter editor over three jets and it guarantees us an order no so we provoke it to do now we are going to do a prep interval that will be equal to the first thing they have the trichet that is read the first we have to be the vote that if no we are not going to get the value that is the power first and then while he trichet points that distinguishes us in this I am not sure why we are going to see then we are going to take out no we are not going to go taking out 11 call corrents and we are going to start evaluating no then if there is a decent separation between run let's say it's late and current is although it would be older than laurent so in that case there is a gap there is no gap between these two and we are going to put the result from the prof until the arc rent d'art our make our interval and we are going to ask if current point is greater than predicted point ent if so I know if correct that is, the value that we are removing right now the end is greater than the end of the previous one that Yes, the working time is extended, then our new pre will be equal to the correct one and that's it. In the end, we simply return the other way around and this should work without any problem and it works because of this and it works to make it work for everyone and a supplement works. It should not take longer and this is a good solution and it is very easy to implement even though it is a hard problem there are many very strange solutions out there that I did not like at all the truth is that saying that this is a very simple solution that can easily occur in an interview
|
Employee Free Time
|
set-intersection-size-at-least-two
|
We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8`
| null |
Array,Greedy,Sorting
|
Hard
| null |
210 |
hi everyone it's Soren today we have a problem when we are given a courses and also we are given a prerequisite for each course so for example in this case we are given a two courses zero and one right and also we are given a prerequisites so prerequisite for the course one is zero and in our case we need to return the order in which we are going to take those courses so for example in this case since the prerequisite for one is z Z first we are taking a zero course then we are taking a course one the way we are going to solve this problem we are going to represent our courses in a graph and we are going to apply topological sort to the graph so for example let's take an example let's take we have four courses and we have one so for the prerequisite for the zero is 1 and two prerequisite for one is three and prerequisite for two is three let's represent that in form of a graph let's say that we have zero which depends so which means that the which has the prerequisite of one right also zero has the prerequisite of two and two has prerequisite of three and uh two one has prerequisite of three and two also has the prerequisite of three so how we are implementing our topology iCal sort in the topological sort we are starting from our node in our case the zero right and we are deep first searching we are deep searching and finding the node that does not have any dependency and we are adding that to our result let's put our result here right so we are deep first searching and first we are going to let's say that we are starting from the first one right first does it has any dependency does it has any prerequisite yes is three so let's go to three and does three has any dependency any prerequisite no it does not so we are adding three to our result first so besides that we are also maintaining two variables one is array of bullan right array of Boolean let's call it a stack and another one is array of Boolean again and it's um it is visited so which notes we have visited right so in this case we have only four notes right we have only four notes but let's say that the we have 50 100 and so on we if we visited that node we should not visit that again so first we are visiting in this case Zero node right so let's that put another color so first we are visiting the zero note then we are visiting the first note then we are visiting third note right and also we are maintaining our stack why because we need to in case if we have cycle in that case we cannot complete our courses right so first finish this one so we have we are adding to our stack 0 one and three right we are adding to our St zero one and three so we have completed this part so we are here now we are backtracking right so we did first search this Branch now we are backtracking so we are at adding one to our result also we are adding one to our result and now we are exploring deep for searching this part right so as we are def first searching we are removing from our stack these values right we are removing from our stack these values so we are adding two is two visited no two is not visited does two has an dependency yes it's three and three is already visited so we are adding two also to our result and the last one that we are adding to our result is three is zero right zero so this is the sequence in which we are going to return starting from zero first we are starting from three first we are taking the third course then we are taking first one then we are taking second one and the last one we are taking the zero okay so let's take one more scenario let's say that in order to take the course three we also need to take the course so for the three right so for the three let's say we have the prerequisite of zero right prerequisite of zero so what's going to happen in that case once we are deep firstest searching right why we are maintaining this stack so let's say that we are starting from zero then we are adding one so we are deep first searching right we are deep first searching and we try to find the node that does not have any prerequisite so we are adding that to our stack one then we are adding three right then we are again adding zero try to again add zero at that point we can say that okay we this is cyclic this is a cyclic graph and the we cannot finish to we cannot finish courses right at this point if we are trying to add the same note to our stack again so at this point we are going to return empty array or in our case we're ret turning empty array which means that we cannot find finish this course and as you can see from here it's a cycle right so in order to finish zero so in order to take the first course we need to take one and two and in order to take the one and two we need to take three and in order to take three we need to take zero so there it's a cyclic graph so we cannot finish our courses okay uh let's take a look at our implementation so what we are doing here first thing that we are doing we are creating a graph which is array of lists so first we are creating a empty array list for each prerequisite and then we are populating the values so we are adding here for example the index zero right let's say index zero is the zero course so this course zero it's prerequisite to what it's prerequisite two it's prerequisite to one and the two so for the zero index we are going to add the list of array list with the values of one and two which means that the courses one and two so as after we completed our graph now what the next thing is we have we are creating array of bullan visited where we are going to Mark each note that we visit and also we are creating a bullan stack we are that will help us to maintain a stack as we deep for search our graph so the next one is we are creating a result that we where we are going to store our values and we are going to return the next one for each value for each node we are going to De for search and the find the first one find the first course that does not have any prerequisite so in our case we are calling it a h cycle because at the same time also we are looking for cycle we are def searching and we are looking for cycle if we find the cycle doesn't matter in which node it means that we cannot finish courses so let's take a look at our H cycle method and in our H cycle method or function so what we do here first thing is we are checking that if we have that node in our stack right so it's our DFS at the same time we are looking for the cycle if we have in our stack that Noe what it means that we have a cycle already so we are returning true if another one is that if we have already visited that Noe we are returning false here and um after that if we are just adding that to our stack and we haven't that visited so we are marking both as true and we are recursively calling so for example in this case let's say that we are starting from the zero right we are starting from the zero and the so the prerequisite for that prerequisite for zero 0 is prerequisite for one and the two so we are going and exploring calling them recursively so first we are exploring first right and calling recursively passing gear one and uh passing gear our graph visited and the result and um as we so if we find the cycle then in that case again we are returning true if we are not so what we do next the next one is we are adding that to our result we are adding always to zero index because we want to maintain the order first we are going to add the three then we are going to add one right then we are going to add two and at last we are going to add zero in our example 0 1 2 three courses so and also we are so as we are backtracking right we are marking our in our stack so we are marking it as a false because we are going to use in another branch of our graph also so that's our as cycle method and uh as we exit this Loop right we have different search for every course so what we are doing we have a result but we need to return our result in form of the array not the array list so we are forming here our array and returning our result so that's it for the explanation part how about the time and space complexity of this solution the time complexity is that the first thing is for the time complexity is determined by our two for Loop these three for Loops right so we are first forming our graph which is that the of let's say that the number size of the prerequisite of P right of p and also we are deep for searching every note right so we are not visiting one note second time because we are maintaining visited array of Boolean so it's a o of let's say n right n being is the number of the nodes o of n so our final uh time complexity is n plus P right n being as the number of the nodes and the p is being the prerequisite so how about the space complexity is determined we have these four data structures here right we have the list of we have graph we have visited and we have stack and we have result these three are the sizes of n because the size number of courses right and the forming a graph is the size of the graph is the size of n plus P because number of courses and the number of the N being the number of courses and the p is being the number of prerequisites right so it's also o of n plus P okay that's it for today hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
|
Course Schedule II
|
course-schedule-ii
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return _the ordering of courses you should take to finish all courses_. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** \[0,1\]
**Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is \[0,1\].
**Example 2:**
**Input:** numCourses = 4, prerequisites = \[\[1,0\],\[2,0\],\[3,1\],\[3,2\]\]
**Output:** \[0,2,1,3\]
**Explanation:** There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is \[0,1,2,3\]. Another correct ordering is \[0,2,1,3\].
**Example 3:**
**Input:** numCourses = 1, prerequisites = \[\]
**Output:** \[0\]
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= numCourses * (numCourses - 1)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* `ai != bi`
* All the pairs `[ai, bi]` are **distinct**.
|
This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
207,269,310,444,630,1101,2220
|
257 |
all right welcome to this video we're gonna be doing miko prom 257 binary tree paths so I'll give you a binary tree and they want to return an array of strings representing all the paths from the root which is at the top of the tree right the one node in this example till a leaf and a leaf is a note with no children right so in this example a leaf would be this three note and this five node they have no left or right children so we're going to solve this with recursion and recursion is not your strong suit don't worry it's not mine either and we'll sell this with helper method recursion which I find a bit easier to understand now you like this kind of content be sure to LIKE comment subscribe hit that notification Bell so you're notified of all of our new content with that being said let's get started so why I wants to do is first handle an edge case where they pass us a invalid node when they pass this pass us an empty binary tree so I'll save no root return an empty array right there's no pass otherwise I'll say Const result is equal to an empty array and we're gonna fill this out with strings so I'll create my helper method recursion function I'll call it let's say find path it takes in a node and a current path and current path this will always be of type string alright and know it well it will always be a given node in the input binary tree alright so I'll say current path plus equals node dot Val right cuz we want to append our current node onto our path then I'll say if our node does not have a left child and a right child so if no dot left and no node dot right result dot push current path right because if the current node we are on does not have a left and right child we are on a leaf and the current path has been update consistently and so we're going to push the current path we are on to our result array otherwise that means there's either a left child or a right child or both so let's keep traversing so I'll say if node dot left then I'll say find path and takes in two arguments right node current path so I'll pass in no dot left right there's a left child passed that left child notified path and for current path right I'll pass in the current path plus this right directional arrow because Li code wants each of these strings right in between the node values we have this directional arrow right here so then I can just copy this actually just change a couple things so let's say if no dot right Traverse again passing in the nodes right child and you still pass in the current path plus this directional arrow all right so we finish to find this find path helper recursive function now let's actually call it so I'll call it on so I'll do fine path and call it on the input node they give us which is the root of the binary tree so I'll say root and then our current path is well an empty string on the first call of it right once fine path is called it's going to update our result array accordingly and I can say return result so I'll save I'll bring this over to leave code and make sure it passes their tests and it does great so what is the binary tree pass complexity analysis time complexity is o event because we traverse through every node in the tree and space complexity so event because we use recursion and so our cost that could be of length tree all right that should be it for this video
|
Binary Tree Paths
|
binary-tree-paths
|
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ "1 "\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `-100 <= Node.val <= 100`
| null |
String,Backtracking,Tree,Depth-First Search,Binary Tree
|
Easy
|
113,1030,2217
|
1,808 |
so we could 1808 maximize the number of nice divisors so in this problem you need to return the maximum possible amount of nice divisors of every number of any number that has at most p f prime factors so pf is your input you need to output the biggest possible amount of nice divisors of any number that has at most bf prime factors and a nice divisor is a divisor of n that is also divisible itself by all of the prime factors of n okay so in the example here pf is 5 and the output is 6 and n is 200 so n is just equal to 2 to the power of 3 times 5 to the power of 2 and the amount of nice divisors is 6. these are the nice divisors of 200 okay so that is the maximum okay so i've actually written here a little proof that makes this problem into the easier problem it's actually a medium problem called integer break so it's absolutely crucial it's absolutely a prerequisite to this problem having solved and understood the problem called integer break and i have it on my channel so you can go and watch the video about that and you won't understand anything here if you haven't solved that problem so that would be my fault it would be your fault because you haven't watched that video or solved that problem yourself before okay so now assuming that you already know the solution to integral break let's get into the proof so any number can be represented as its prime factorization this is common knowledge so that's just a bunch of prime numbers multiplied together with possibly powers so some exponents so for example here you have 2 to the power of 5 of 3 sorry 2 to the power of 3 times 5 to the power of 2. that's ok so what is the number of nice divisors of a number with a certain prime factorization it turns out that the result is just the multiplication of all of its powers in the factorization so here for example you have exponent of 3 2 to the power of 3 and here you have an exponent of 2 5 to the power of 2. and in fact the total number of nice divisors is 6 which is 3 times 2. now why is that if you look at the definition of a nice divisor you can see that the nice divisor needs to be divisible by every prime factor of n so the smallest nice divisor is always just going to be the product of all of the prime factors without any power right so for example the smallest one here is two times five and that's it and if you had some other nice divisor then it would have to also be divisible by two and five so then what makes the nice divisors different is the exponent so that's where the multiplicity comes in so you always have at least one two and one five but now you also have for example two times two so that makes the number different from the previous one so now you can see that to make a lot of different nice divisors you need a number with a lot of powers in their prime factorization okay for example here i can take two times five or i could take two times 2 times 5 or 2 times 5 and those would all be nice divisors so i could take 1 out of 3 powers of 2 and 1 out of 2 powers of 5. so i have three choices for two and two choices for five and all of them any combination of these two choices makes a nice divisor so by simple rules of combinatorics i can then derive the formula that the total amount of nice divisors is just the product of all the exponents of the prime factorization okay so now we have this which might be helpful later on now from the problem statement we know that our input pf is the highest possible amount of prime factors of our number n so this gives us an upper bound to the sum of all of the exponents for example here prime factor is 5 so the sum of the exponents of the prime factors must be at most five and in fact here we have two to the power of three and five to the power of two so the sum of their exponents is five okay so now we can also write this formula here so we know that the sum of the exponents needs to be less than n and we want to have the biggest possible amount of nice divisors and we know that the amount of nice divisors is just the multiplication of all of the exponents so now we've come up with an equivalent problem to the original one so it's literally the same problem and you need to really convince yourself about this before continuing any further so we just need to find the maximum product of some amount of numbers such that the sum of all of these numbers is less than the input is less than prime factors pf okay so now if you've convinced yourself of this then the remaining problem the body of the function is literally the same thing as the problem called integer break so go ahead and watch that or solve that yourself i don't care come here come back here only when you've already solved that or you won't understand anything here okay so this is literally the same as that problem except three differences so the first difference is that the constraints here are much larger so integral break has like uh the upper bound is like 50. and here we have like 10 to the power of 9. so this causes that we need to use big integers so we cannot just use normal integers or we'll have overflows loss of precision so we need to use big integers so that is the first difference then the second difference is that the problem statement asking us is asking us to do modulo of the result so this is the second difference and the third difference is that in the integer break problem you're asked to use at least two factors always so instead of having this you have the same thing but you also have the constraint you need to use at least two factors here we don't have that so it's the same problem with these three differences and the solution reflects that so the solution is literally the same thing as integer break so you have the three cases except that we use a special function that does the power while also doing the modulo inside right because we know that we're going to take the modulo so why not do it while we take the power so while we do the exponentiation right it's a little optimization and then the second difference is that we're using big integrals instead of normal numbers and the third difference is that we're taking the modulo right so yeah that's it uh so i'll just go quickly through the logic so i'll submit the solution to share it works first of all so you can convince that it instead indeed works and i'm going to go through quickly the logic of the integer break problem so why are we using factors of 3 you see that we're using the biggest possible amount of factors 3 possible now why is that the reason is that three is kind of the best number since it's the closest one to e which would be the best one but it's not an integer so we cannot use that so we use three instead if we can so the ideal case is where the modular with three of our number is zero and in that case we can use only threes so all of our prime numbers are going to have an exponent of 3 that's the best solution but if our prime factor is not divisible by 3 then unfortunately one of our prime numbers is going to have to be with a multiplicity of four so this is the best that we can do if the prime factors are not divisible by three so the our input is not divisible by three and then the second case here now why are we multiplying by four that's because we're instead of dividing by three we're dividing by three and then taking away one so we're basically sacrificing one prime number with multiplicity of three and instead we're making one with multiplicity of four so we have a modular of one so we don't want that to go to waste that would be a really big waste so instead we sacrifice a three we put it together so we put the three and the one together and we now made a four right and so we multiply everything by 4 and we sacrifice one prime number with multiplicity of 3. and the only case remaining is when the modulo with 3 is true and in that case all you have to do is the same thing as here except that you also have one prime number with an exponent of two so once again if you don't understand this it's completely normal you need to look or solve the problem integer break before and then you will understand this and just one more thing about the power so the time complexity here is logarithmic because we're using power through exponentiation so at every step if the exponent of your number is even you can instead square your current result and that will cause your exponent to be halved so that is just normal um properties of exponents and powers right and if instead your exponent is not even so it is odd then you can just perform one multiplication and that will cause it to become even of course so yeah that's it for me today thank you for watching and bye
|
Maximize Number of Nice Divisors
|
stone-game-vii
|
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions:
* The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`.
* The number of nice divisors of `n` is maximized. Note that a divisor of `n` is **nice** if it is divisible by every prime factor of `n`. For example, if `n = 12`, then its prime factors are `[2,2,3]`, then `6` and `12` are nice divisors, while `3` and `4` are not.
Return _the number of nice divisors of_ `n`. Since that number can be too large, return it **modulo** `109 + 7`.
Note that a prime number is a natural number greater than `1` that is not a product of two smaller natural numbers. The prime factors of a number `n` is a list of prime numbers such that their product equals `n`.
**Example 1:**
**Input:** primeFactors = 5
**Output:** 6
**Explanation:** 200 is a valid value of n.
It has 5 prime factors: \[2,2,2,5,5\], and it has 6 nice divisors: \[10,20,40,50,100,200\].
There is not other value of n that has at most 5 prime factors and more nice divisors.
**Example 2:**
**Input:** primeFactors = 8
**Output:** 18
**Constraints:**
* `1 <= primeFactors <= 109`
|
The constraints are small enough for an N^2 solution. Try using dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Medium
|
909,1240,1522,1617,1685,1788,1896,2002,2156
|
130 |
hey guys persistent programmer here and today we're gonna do another legal question surrounded regions now before we get into the question if you haven't subscribed please go ahead and smash that subscribe button it really helps me create these videos for you okay let's go ahead and read the question okay awesome so we're given a 2d matrix here and I've highlighted the rows and columns here and what we need to do is we need to convert these O's that were given into X's and we're given one condition to keep in mind before converting them and that condition is that if the o appears in any of the first or last edges of this matrix so by that I mean anything here in any of these first rows or last rows then we need to ignore them we are not going to convert this 0 this.o to X going to convert this 0 this.o to X going to convert this 0 this.o to X because that is the condition we're given and if we have a case where let's say this o is this in this last row and um there are both connected to this last row then we also don't consider those so we're not going to consider this and we're not gonna consider this so anything connected to that o we will just leave as it is and we will transform the rest of the matrix with X's so if I took this input and if I had to return the output it would look like this so we can see that this o is remaining as it is and the other olds that are not connected to this all because there is no way you can reach this o going up down left or right these are the three O's we can convert into the X's so that is the problem in a nutshell I hope you're able to understand it I know the question wasn't very clear about what all the cases were but by looking at the inputs and outputs you can figure out what it's asking awesome so the Strada gee I want to use to solve this problem is going to be DFS and if you're not familiar with DFS I would suggest doing some problems before you try to do this problem but you can still follow along and kind of see how DFS works and how its applied to a problem like this so that will help your understanding of this search so what we're gonna do is we will first isolate this first our first role here and our first column and our last role here and our last column okay so if I isolate these and if I run my DFS on these it is very easy to figure out what is connected to these zeros so for example if I'm at this zero I'm going to look to my left and there is no zero and if I'm gonna look to my right and there's no zero and down and no zero right so I can figure out what I don't need to modify like what are my invalid cases here right and what I'm going to do is I'm going to stamp those invalid cases with I or you can pick any other letter you want but I just thought that invalid cases could be marked as I you can pick any other character or like a star whatever however you want to mark your board so remember we're not creating any additional board to do this problem we're doing everything in place so it's very important to stamp our positions that we have visited and we have deemed invalid so that's why we're doing this exercise so if I went through each of these cells at the at these positions at the first row first column last year last column I should be able to see what is connected to these zeros and what I don't need to touch what are the invalid cases in this problem right so let me just draw this line here so I'm a little bit more clear right so I'm going to go through each of these columns and rows okay let's say I'm at this zero here right so I'm going atom by atom so each position in this column will be sent to the DFS function which will then determine what are the invalid cases so if I'm at this position I know that this zero is invalid so what I'm going to do is I'm going to change this to I right because it's invalid so I know that I have a system to mark these spots as invalid and they don't need to be changed to X's and then what is going to happen is I'm going to look to my left and okay there's no zero so nothing to do I'm gonna look to my right okay no zero nothing to do and then if I look up there is a zero so I'm also going to convert this to I and then I look again from this position to my left right up and down and I can see there's more spots here right so this will be a is will be our I and this will be I so if I were to transform this to D matrix it would look like this so you can see here that this is invalid so anything on these edge row and columns are invalid and on top of that we have found through our DFS that all these connected zeros are also invalid so we're not going to touch them and change them to X's right so we'll just believe them as the olds they are and you can see that once I've transformed this and checked what is invalid which is our first step so to check invalid cases you can see that there are these zeros which are valid and these should be turned into our X's when we iterate over this so this is a two-step check so first we're gonna do a two-step check so first we're gonna do a two-step check so first we're gonna do a DFS on all these border rows and columns and we will just damp our matrix with the eyes this is to tell us that hey just don't touch these eyes because they are supposed to remain zeros right so our second step what we do is we go over at these eyes and we just convert them to zeros so we convert the eyes to zeros and if we see a zero so this should be returned as a X so we if we see a zero we just convert it to X and that's the way we're gonna solve this problem so to summarize we will run the DFS on the Border's and then set the invalid positions and then we'll once again we iterate over the same Bourg but this time not calling the DFS because the DFS work is already done we have determined what is invalid right so we're gonna reiterate and then we will just make this conversion so any invalid we just need to change them to zero that's it that's all we need to do and if we see a zero we're just going to change it to X and that's how we're gonna solve this problem okay so the time complexity for this problem is going to be the rollout times the column once so n times n and we're not taking any additional space so space complexity is just oh f 1 ok awesome so with this strategy and understanding let's go ahead and write the code okay so the first thing I've done here is I've done an edge case checks if we're given empty board we just return the phone there's nothing to do here so we're not given any excess or owes the next thing I'm going to do is define my row and column 1 so it's just make kind of make it easier for me to access these instead of writing and getting the lines over and over so I will get the roll length from the board and I will get the column line from the first index of the row so one board index zero okay so now I have these two let's now what we're going to do is we will go and go to those edges of the rows and columns and we'll figure out what to mark as invalid okay so what I'm going to do I'll say four are in bro four are in range rollin okay so we're gonna iterate over our rows and what we want to send to our DFS function which I'm gonna call mark and is our row index that we are on and we will also define our search space so we don't want the role to search beyond the first column so what I mean by this is it should search like this right so this is column zero so it should be on the row it's on an only search here because we're only looking for the edges right and we'll pass the board as well because we're gonna update the same board instead of if we're not gonna make a new list to keep track of all of these changes and I will also mark the last row so these and to get to here I just go to the length of my column right so my column length will give me the last length and we just do minus 1 from that because our indexing started at 0 right so I can say row and then call 1 minus 1 and we'll send the board as well okay so after this we have marked our spots in the first and last rows and now what we need to do is iterate over the first and last column so we're gonna go over this here this first column and our last column here that so to do this I'm going to say for C in range koala 1 and we will say self-doubt mark so we're and we will say self-doubt mark so we're and we will say self-doubt mark so we're gonna write this DFS function mark in a bit I just want to have the structure there before I write it so soft up mark will say columns sorry row yeah row is going to be 0 in this case right so we want our role index to be 0 so it's gonna be like here and we want to grab the columns from this first index starting at 0 so we'll say C and send the board and we will also mark the last column right and to grab the last column we need to send it the role length minus 1 right and we're going to pass the column here that we're iterating over and the board okay so all these two are doing is it's going one by one to all of the edges and asking are there any zeros that is going to be connected to this and is it invalid so if it finds a 0 in any of these up/down if it finds a 0 in any of these up/down if it finds a 0 in any of these up/down and then these start is there these like last and first positions it's gonna do something right it's gonna mark it as invalid so that's all this is doing and then what we need to do after all of this is done is we will just iterate over the board again so we can say for our in range roll line and for C in Grange : okay so roll line and for C in Grange : okay so roll line and for C in Grange : okay so what we want to do after all of this is we will have a case where we mark the invalid ones and we will have a case where the zeros are remaining which we need to turn into our X so we'll say if board at the index row and column is equal to we need to check if it is a zero and we want to change that to X so we will say if it's a zero then replace it with this X okay that looks good and then if the board row and column is equal to invalid then what we want to do is we want to turn those back to zeros then we'll save board row column is going to be equal to zero because we want to leave those as they are right as per the question so that's why this zero is still here in that answer because it's an invalid case right okay so this looks good awesome okay so let's go ahead and write our mark so we will say mark and we are going to pass in self our row our so for this row column and board it's just making sure it that's what we're passing in here okay great so what we want to do is for any DFS function or we need to make sure that we don't have overflow so we want to make sure that our base case is there so we want to say if Rho is greater than if Rho is less than zero or roll is greater than or equal to board lengths of board we can say rollin or we can just say length of four dia that will work or if column is less than zero or column is greater than equal to length of the max column month so board zero or if board at the index after all and column is not equal to oh I just realized I need to make sure these are OHS I keep thinking that there are zeros just because of the font of the question it looks like a zero but it's actually all here okay so that looks good so that is our base case he doesn't make sense and if that is the case we just return okay else what we want to do is we are going to mark that spot invalid so remember since we're only sending in the range of the first last row first column and last column we are able to see if any other zeros are connected to that position in left right up or down direction and if they are then we're going to mark them i right so we'll say board at the index of row and column is going to be equal to I so this is how we're making them invalid and then we're going to do the search so up down left and right so we can say it's off dot mark and we need to pass in the roll so we're going to first go down so roll plus one follow them then board okay so that's the first and then I'm just gonna copy this and then we're going to go up so row minus 1 and we're going to go left so column minus 1 and we're going to go right it's so column plus 1 okay so this looks okay let's give this around and make sure there's no typos it looks like yeah looks like it's good okay I'm gonna go ahead and submit also accept it please subscribe to this channel if you haven't already this way I can create more content for you guys and help you guys out in solving these questions if you have any questions or if you want to share your solution below you're welcome to do that in the comments if you have any questions please leave them in the comments as well I will do my best to answer them alright happy coding guys
|
Surrounded Regions
|
surrounded-regions
|
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Explanation:** Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
**Example 2:**
**Input:** board = \[\[ "X "\]\]
**Output:** \[\[ "X "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is `'X'` or `'O'`.
| null |
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
|
Medium
|
200,286
|
1,773 |
hey everybody this is larry just me going with q1 of the weekly contest 230 uh count items matching rule um so this one i don't know uh hit the like button the subscribe button join my discord that's my world and those that's the number of items you have to match no i'm just kidding i mean well it would be nice if you did but the idea here is that there's no idea it's just brute force assimilation i think i wrote a good code um so that you can kind of take a look at to see what because i'm proud of this so that you don't have to write like what you don't want to do during a contest is write live if statements and you know stuff like that and you want to simplify the code so having the rules look up mapping uh this look this maps the world key to a column in items and that's basically what i have here um yeah and the reason why i took slower than i usually do for this problem was actually i should have named things uh in a not dumb way but what happened was that instead of item for each for items and items uh i should have named them rows or something because that's why i do but i won't if items is equal to value and i couldn't figure out why i wasn't wrong for a long time and then i once i removed the s i fixed it so yeah what's the album um well this is going to be linear time because for each item uh we only look at it once so it's linear time a constant space before this because this is always going to be one on one space and that's all i have let me know what you think about this one and you can sell you can watch me stop it live the contest next what is that oh what the okay what is the oh geez this one is annoying not even hard just annoying what oh come on am i doing oh misunderstood computer silver what don't mess that up type color name okay color silver hmm why is 10 not incrementing then oh wait oh no i uh typo no that's why items and items what a silly mistake okay one two let me not okay that was a silly typo let's see uh hey yeah thanks for watching hit the like button to subscribe one join me on discord let me know what you think about this prom uh take care of yourself take care of others love you everything and yeah it's a good mental health and i'll see you next fall bye-bye
|
Count Items Matching a Rule
|
percentage-of-users-attended-a-contest
|
You are given an array `items`, where each `items[i] = [typei, colori, namei]` describes the type, color, and name of the `ith` item. You are also given a rule represented by two strings, `ruleKey` and `ruleValue`.
The `ith` item is said to match the rule if **one** of the following is true:
* `ruleKey == "type "` and `ruleValue == typei`.
* `ruleKey == "color "` and `ruleValue == colori`.
* `ruleKey == "name "` and `ruleValue == namei`.
Return _the number of items that match the given rule_.
**Example 1:**
**Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "lenovo "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "color ", ruleValue = "silver "
**Output:** 1
**Explanation:** There is only one item matching the given rule, which is \[ "computer ", "silver ", "lenovo "\].
**Example 2:**
**Input:** items = \[\[ "phone ", "blue ", "pixel "\],\[ "computer ", "silver ", "phone "\],\[ "phone ", "gold ", "iphone "\]\], ruleKey = "type ", ruleValue = "phone "
**Output:** 2
**Explanation:** There are only two items matching the given rule, which are \[ "phone ", "blue ", "pixel "\] and \[ "phone ", "gold ", "iphone "\]. Note that the item \[ "computer ", "silver ", "phone "\] does not match.
**Constraints:**
* `1 <= items.length <= 104`
* `1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10`
* `ruleKey` is equal to either `"type "`, `"color "`, or `"name "`.
* All strings consist only of lowercase letters.
| null |
Database
|
Easy
|
1338
|
1,680 |
hey everybody this is Larry this is day 24 of delete uh day 23 whoops of the legal daily challenge hit the like button and the Subscribe button join me on Discord let me know what you think about today's Farm was a little gun had a good night say and yeah let's just get started uh I'll at some point I'll bring back some of the uh fun drum videos um but for now let's go with this problem 1680 concatenation of consecutive binary numbers and return the decimal value of the binary string formed by concerning the binary representation one and N in order module 10 9 to the 9 plus 7. let's say what okay I mean I think this is pretty okay right um the decimal so okay so we what does that mean the decimal value of this foreign so you want to I'm I think so what I'm trying to do right now um or this thinking to do right now is trying to they're a lot of Base switching um which is fine I'm trying to try to figure out if I need to do the bass switch or is it sufficient no I guess not I mean we could just simulate it I mean n is 10 to the fifth um this is also one of those weird problems where to be honest depends on number of inputs right so it's gonna be off and where n is the input which is technically exponential but um yeah so we can just probably do that and I think it'll be okay so that yeah let's just get started right I think this is just an exercise in understanding my modular math and what operation set you can do under different um uh under the space of modular under the modular space um so yeah so guys so for I and range from 1 to n inclusive um so we have a current thing and then I think there are a couple of ways you can think about it um trying to think what's the cleanest way uh um her thing was to cleanest way to write this I mean this is just gonna be simulation and we're just trying to be no not or I'm trying to be not sloppy I suppose um I'm just trying to think about uh yeah I mean um foreign I guess I have an idea I was gonna initially um yeah I think I was initially gonna I mean you can definitely you know there is a very straightforward way of like okay we convert it to Binary we take the uh you know the because this returns to Ox as the prefix so you just take the uh thing and then you know uh maybe we could write something like um you would ship it by uh oops by link of M and then you know maybe they'll fall up for uh this thing right for C and M then oh well maybe I did it the other way maybe something like this where for CNN if uh and C say and then you know foreign probably okay but I was trying to think whether I could do something a little bit um cleaner but yeah so this is going to be good we should test versus easily easy to test a big case just to see the timing um I think one thing you can do though if you are you know like you can simplify this by uh and I think I maybe just got ahead of myself anyway a little bit but we could shift this by length of M and then we just I right because then this is already the binary thing so yeah so we can do it that way and see if that's how much if it is any faster Maybe uh so oh wow that is actually much faster already so because we're combining the um the shift and I say ship and add I guess it's shift and all um very much um and then the other thing to notice that you can also optimize a little bit on is that um if you keep track of this uh this um the length of M function not M so which means the number of binary bits needed to represent this number um that actually only you know that only increases on Powers of two right so yeah so then you can maybe say shift is equal to one and then here if um I is a power of two which you know there's always the I'm not going to explain this one um but that's like the core way of doing it say um and maybe just it starts at zero so then you can shift it by uh and then here we can just do it by shift something like that right maybe I'm off by one though but yeah okay so yeah actually this one is a little bit longer I don't know that's just um yeah I think that's just you know uh lead code variant so I wouldn't worry that much about it so let's give it some of it apparently I didn't like well twice but a lot of submissions in the past huh am I gonna get time limit exceeded no huh it's way slow though anyway um that is my 906 day streak so that's kind of cool um yeah uh yeah this is gonna be exponential time and the size of the input because this is O of n how did I do it before wow one second in pi for on Java I guess I just did it lazy oh what am I doing here oh that's cute I guess in the past I did it a different way foreign no I mean I guess I just shift and yeah I think I just shift right and then shift and add I kind of did this in a funky way actually I did it twice in Java for some reason why did I do try some Java here I did the same thing Maybe and this is pretty poor Java too to be honest uh thank you oh I guess this is just to count the number of um to count the number of bits needed okay oh that is much faster even with the um about the optimization uh but this is much can I do a little bit better I mean these are the obvious ones for me um I'm doing ten thousand I'm curious if we space out the mods we'll be a little bit faster but again that doesn't really matter but oh well we had to do mod at least once oops which I guess it does time out but if we do I mean at that point I kind of have expected but at least do something like that because the mod is kind of not cheap either but yeah I don't know if that's gonna be much faster though it'll be I mean it'll be fine I don't know if it's much faster anyway that's just me playing around uh that's all I have with this one though let me know what you think hit the like button hit the Subscribe button join me on Discord I'll see you later and take care bye
|
Concatenation of Consecutive Binary Numbers
|
count-all-possible-routes
|
Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation: ** "1 " in binary corresponds to the decimal value 1.
**Example 2:**
**Input:** n = 3
**Output:** 27
**Explanation:** In binary, 1, 2, and 3 corresponds to "1 ", "10 ", and "11 ".
After concatenating them, we have "11011 ", which corresponds to the decimal value 27.
**Example 3:**
**Input:** n = 12
**Output:** 505379714
**Explanation**: The concatenation results in "1101110010111011110001001101010111100 ".
The decimal value of that is 118505380540.
After modulo 109 + 7, the result is 505379714.
**Constraints:**
* `1 <= n <= 105`
|
Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles.
|
Array,Dynamic Programming,Memoization
|
Hard
| null |
1,047 |
okay so lead code practice time so in this video we have two goals the first goal is to see how we should solve this problem um then we are going to put in some code here and the next goal is to see how to solve this problem properly in real interview so let's get started so remember the first step is to try to always understand the problem and if there is anything unclear please bring out the question and also at the same time think about some ash cases so let's take a look at this question remove all adjacent duplicates in string so given the string as of lowercase letters a duplicate removal consists of choosing two adjacent and equal letters and removing them so we repeatedly make duplicate removals on s until we no longer can so remove sorry return the final string after all such duplicate removals have been made it is guaranteed the answer is unique all right so let's take a look at this example so abb ac returns ca so pretty obvious we re move the double b so after we remove that will be the first a and the second a become adjacent and we need to remove the two ways as well okay so it makes sense to remove to return ca uh for this specific input so let's take a look at some notes so it says the string lens is between 1 to 20k and s consists only english lower letters okay so um for sure that the input string is not going to be empty so i think um i don't i cannot think of any ash case at this moment so let's go on for the next step so the next step is about finding a solution so how to solve this problem um i think there should be a linear solution for this one uh let's see actually so we could use a stack to solve this problem so for example uh we have a stack uh every time we just keep we just push uh the character into the stack so if the top of once we encounter character and it ha it is the same as a top element within the stack then we are going to try to pop the stack until we hit a different character so take this example so at the very beginning the stack is empty then we will add a and then it comes to b we compare the top element which is a usb so they're different so you can safely uh push b into the stack and then when we encounter another bbc that it is the same as the top element of the stack so we'll keep popping the top element from the stack until we entail either it is empty or the top comment is different from the current character and then the next character is a so we see that top element is a so we try to pop a from it as well and then we encounter c we just push it into the stack and then similarly we are going to push a into the stack and finally we just uh pop other elements from the stack and then return uh return the string connected with all the characters so that's pretty much it about this uh solution so the runtime is going to be olive n is the length of the string and uh space wise it's the same so let's get started and do some coding work so for the coding part we care about your correctness and the readability of the code and also don't be too slow so we first have a stack then we are going to iterate through the string so um let's change this car c to start to curl the array all right so um if uh the stack dot if the stack is empty or the stack dot peak how you pick the top element from the stack it's not equal to the current character so either of the case we are going to push the character into the stack so you're going to call a stock stack dot c and then you're going to continue otherwise it means um otherwise it means the stack is not empty and the top element is equal to the current character so what we are going to do is well the stack is not empty and stack dot peak is equal to c well this is true then we are going to um uh we're going to stack the pop you're going to keep popping the top helmet from the stack until the stack to be empty or the top helmet from the stack is not equal to c and finally we are just going to connect everything from the stack every character from the stack so you're going to have a string builder as trs new string builder it's like well empty so while it's not empty we're just going to sdr.insert sdr.insert sdr.insert zero and stack dot finally we are going to return str dot to string all right so um like i said um we are done with the code so when we are done with the code it's time to do some testing like i said before um let me go through the first example let's say abb acc sorry abv aca so we are going to try to do some sanity check on this piece of code and at the same time explain how this piece of code is going to work on top of this um this input example so first of all i have stack as empty and then we go iterate through every character so a when it is the first a stack is empty so you're going to push a into the stack and then continue when it is b similarly we are going to push b because it is within this a branch and then when you encounter another b we see that um we see that uh the stack is now empty and the top element from the stack is equal to c so we are going to keep popping the top element until either the stack is empty or the top limit from the stack is not equal to c and we just pop the top b from the stack and similarly for when we encounter the a we are going to pop a and then when you kind of see you push it into the stack and then you push the another a in into the stack which is the last character in the input example and finally um we try to pop everything from the stack and the each time we pop it we try to insert at the beginning of the string builder finally we just return the string so i think it looks good let's give it a shot okay all right so everything looks good um i would say regarding the test case setup um for example one i think it should be good enough for test carriage uh other than that i cannot think of any fancy test cases we need to um include to have good enough test courage so that's it for this coding question uh if you find it helpful please help subscribe to this channel i'll see you next time thanks for watching
|
Remove All Adjacent Duplicates In String
|
maximize-sum-of-array-after-k-negations
|
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them.
We repeatedly make **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**.
**Example 1:**
**Input:** s = "abbaca "
**Output:** "ca "
**Explanation:**
For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ".
**Example 2:**
**Input:** s = "azxxzy "
**Output:** "ay "
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
| null |
Array,Greedy,Sorting
|
Easy
|
2204
|
1,884 |
A Different Se Zaveri Stand Problem Vitamin Interview Hotspot Of Which State Agro Bittu Services Solved Problem In Which Is The Problem Of To Find The Number Of Subscribe And Subscribe The Channel Problem Key Problem In Which I Am The Thing Which Talk I improved this dance problem is which help me tow clients mid-1990s land acquisition clients mid-1990s land acquisition clients mid-1990s land acquisition policy building a that if unwanted which serious so it's good tow and baby when you drop time chrome but updates and withdraw cash withdraw from this thank you can do Do Subscribe 0 Ayan Jo Might Break Aur Gold Biscuit Le Sabse Zor 22.22 Minimum Fight From Which You Can Sabse Zor 22.22 Minimum Fight From Which You Can Sabse Zor 22.22 Minimum Fight From Which You Can Jump Subscribe Now To Find The Giver Chances These Rules Subscribe to the Page if you liked The Video then subscribe to the Page if you Rupee Ka Hai Know The Weather This Is The Maximum Light Always Smile Hidden Object Vitamin A Plus Pulse Felt Tube Report From This Idol Audition Break Per This Is Not The Smallest From Which You Will Then She Deserve This Is Just Saw It's Not Beneficial To Grow And Free From Any Problems Or Beneficial Black Widow And Subscribe Now School And Avoid Breakfast And Only There Will Be Boat Specific Antigen To Installments Hai Police Sources At Random Laxative 2310 Height Ok No It Hua Decide This 2nd Ed Returned pimp research solid liquid tree it another person then floor will withdraw pre-2005 but on this remedy lottery person pre-2005 but on this remedy lottery person pre-2005 but on this remedy lottery person 2018 side click a subscribe button a lower left hand office let you know aegis of left you to check so know the condition for example of simple Problem Incident - example of simple Problem Incident - example of simple Problem Incident - Explorer Left With You And To Accept One The Amazing And On The Side Just Level We Made A Man Die One Is The Meaning Of What Is The Meaning Of This Is The Meaning Of The Word And Listen Special Thoughts Requested Solution For Stopping At Na Dharma Loot Impressed With Soldiers From This Chart Mon Black Piper Dipping 20000 Management Students App Lets You Need To Adjacent To Prime Minister The Best Ones Upon Which Height Your Black Humor Accident Hum In Access Of Women In Wedding Ki Pke Na Oye Give One Example 2151 Left Leg Un dusted us number 2 f 2 eggs subscribe from one and to take and drop to one person subscribe now to receive new updates time to take meeting then word loop iodine like and share this and add ur birthday to you find what is the what means subscribe to the Page if you liked The Video then subscribe to [Praise] the Page हैं तो आया आया आया एक्सल टू लडक टोल न्यूबर एक लेंघ आर एक फ्रेलेक्टन को फ्रींड्स तो आया आया आया एक्सल टू लडक टोल न्यूबर एक लेंघ आर एक फ्रेलेक्टन को फ्रींड्स तो आया आया आया एक्सल टू लडक टोल न्यूबर एक लेंघ आर एक फ्रेलेक्टन को फ्रींड्स आप लव एंड संस्करेट फोर इंटेट्स फिल एस चनल को आप लव एंड संस्करेट फोर इंटेट्स फिल एस चनल को subscribe to the Page if you liked The Video then subscribe to the sperm donors for every 1000 points new dresses and this cancer developed and another person subscribe like this problem the given to stop this point subscribe to the Page if you liked The Video then subscribe Robin Reliance and Family Explain How Many Loot Number One Pinch One Side Many Loot Number One Pinch One Side Many Loot Number One Pinch One Side Will Start From Every Rule Number Five Walk Involve Will Account For The Subscribe This Video Subscribe And Subscribe The Channel Another That At This Point Of This Land We Love The Cockroach Animals Of Life This Year And for exhibitor SIM number to dates and where made in the current level if you don't want to show what benefit blackwater doing service record to you will give me sum taking MP number to find the value of the volume maximum district which will give me A What is the subscribe to the Page if you liked The Video then subscribe to the Page Avoiding Problem and Solution for This Harvest Criminal Obscene Hai Code
|
Egg Drop With 2 Eggs and N Floors
|
minimum-changes-to-make-alternating-binary-string
|
You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each move, you may take an **unbroken** egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves.
Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is.
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** We can drop the first egg from floor 1 and the second egg from floor 2.
If the first egg breaks, we know that f = 0.
If the second egg breaks but the first egg didn't, we know that f = 1.
Otherwise, if both eggs survive, we know that f = 2.
**Example 2:**
**Input:** n = 100
**Output:** 14
**Explanation:** One optimal strategy is:
- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.
- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.
- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.
Regardless of the outcome, it takes at most 14 drops to determine f.
**Constraints:**
* `1 <= n <= 1000`
|
Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways.
|
String
|
Easy
| null |
52 |
all right guys let's do the 50 second problem with lead code and queen two follow from end queen problem now instead of outputting board configuration return the total number of distinct solution so as we uh as we did in the previous problem we're going to follow the same approach uh let's define account universal variable initialize it to zero then let's have three flags call new pull in and because they're l columns boolean at a uh diagonal 45 is equal to new boolean 2 into n minus 1 uh boolean array diagonal 135 is equal to new boolean 2 into n minus 1 so once we have these three flags we are going to call our helper function with zero as row and color flag and 45 diagonal and 135 once you're done with this return we will return sorry return count okay so next we will have our void helper function so which will pass end row and the building arrays column diagonal 45 diagonal 135 okay next let's get right to it uh if is equilibrium then and then i'll just count have count plus and return else have followed and column equal to zero let's call it column is smaller than column plus now if not call of call and diagonal 45 color pulsar's row nut let's copy this 135 and just have and minus one minus zero after this we'll just have pretty true okay once this is done i will simply call my helper function again with row plus one after i return i'm going to have all of these equal falls let's run this eleventh where support oh i am so sorry guys okay carry convert to boolean line 18. what happened oh i'm so sorry guys okay now it should work okay let's submit this okay guys it works thank you
|
N-Queens II
|
n-queens-ii
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_.
**Example 1:**
**Input:** n = 4
**Output:** 2
**Explanation:** There are two distinct solutions to the 4-queens puzzle as shown.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 9`
| null |
Backtracking
|
Hard
|
51
|
4 |
Everyone welcome back tu channel, I am ready and in today's video we are going to talk about Median of Tu Sorted so this is a very interesting question of binary search and if you have come to this channel by mistake then subscribe the channel immediately. Like the video, if you start this video without any time, then the question to us is that Median of Tu Sorted disease is ok, very popular question is Jivan Tu Sorted Arrest Namas One and Namas Tu return in size respectively, Median of Tu Sorted. Diaries ok If there is an element, then you know that this one is in the middle. Brother, the question must be running very fast. If there are two elements, 2 4 5 6 here, this one has got a further length. This one was out of length, so take out the middle one here. The middle one here, how to find the middle, so here we get 2M, what do you do with these two, find the average of this, find the mean of this, okay, so how to find the average, four plus five divided by you, this bill will be something like four point something. But we take four, they are always ignored SMS, let's know which time is this, so long story short, if someone asks you medium, then you should brother, if the length is erring, then what will be the medium if I am doing total n elements? If is then the median will be N/2 and if and is the area of length N/2 and if and is the area of length N/2 and if and is the area of length then what will be the medium N/2 - 1 and then what will be the medium N/2 - 1 and then what will be the medium N/2 - 1 and N/2 Okay so remember this is the length of your N/2 Okay so remember this is the length of your N/2 Okay so remember this is the length of your order email Okay medium ok how to come Very It is simple, 3/2, what will happen to how to come Very It is simple, 3/2, what will happen to how to come Very It is simple, 3/2, what will happen to your 1.5 inch note, one, what is it, I am your 1.5 inch note, one, what is it, I am your 1.5 inch note, one, what is it, I am talking about indexing, I am fine, I know, it is very meaningless to tell, because we have seen so many videos, I have seen all these concepts many times. And how do I go again four by tu a date to take the same 1 and 2 I said N/2 - 1 and N/2 okay let's I said N/2 - 1 and N/2 okay let's I said N/2 - 1 and N/2 okay let's give more daring on this concept. We came to know what is our median. It's okay, now in the question, Ka is given. In the question, brother, you must have been given two sorted arrays. I have two sorted arrays. How is it sorted? It is sorted in increasing order. You must be seeing what you have to do, you have to find the median of these two variables. Okay, so I am not getting any clarity here, what do I do, I make a three, okay, with any jugaad, I say, I will make a three, what will I do, if I put all its elements here, then its elements. What will happen 2 4 5 6 8 9 12 13 Ok now what will be its length 12345678 mains two median coming index 3 and index ok then zero one two three index four these two medium A gaye will also be visible Friend, three here, so both of them have become medium and find out the sum of it, make it 14 / 2 because sum of it, make it 14 / 2 because sum of it, make it 14 / 2 because we are the mean, we are fine, so the answer will be 7, that is, the median of this sorted, 7, so 7 is not visible here. Yes but 7 Your answer to this will be ok So seven is the median of days You are sorted Chalo bhaiya ho do that form ok ho do that form Need you form this important question but ho answer I do here because now we have 2.2 I have not found the approach, so let now we have 2.2 I have not found the approach, so let now we have 2.2 I have not found the approach, so let me tell you a simple method. Hey, find out its sum. What is its length? Its length is suppose to be n1 and its length is A3. It is okay to do this in it. Copy all the elements and then it is okay. Copy all these elements and what to do is to shorten it, okay, sort this green, you will get something like this and now you can extract your median, okay, this is not a good approach, this is a very bad Approach Why did we take extra space, how much space did we take, n1 + N2 space, on top of that we take, n1 + N2 space, on top of that we take, n1 + N2 space, on top of that we shortened it, okay, I will tell you later about the time complexity of sorting, etc. Meditation is very TDS, you sort something, this is very time late, date is this, not N Very good approach and N 2.2 we did Very good approach and N 2.2 we did Very good approach and N 2.2 we did not read otherwise I will tell you that jugaad here how you can write it ok anywhere when we will read sort or merge sort there I will tell you how to merge sorted diaries. Do you date bill be match more, you understand this, so I am not going to make this video long by attracting that thing here, okay, so let's remove those saree buttons, we will see them in the next video, now the concept in front of us is Bin Ji. Test and we will find the answer only through binary search, why am I saying this because if you raise the question then where is the log of M plus N in the question, that is, you have to give the answer in the log meaning, you will have to apply binary search here. Anyway ok buy in the search etc. forget that we have to find out the straight medium here, keep it ready ok I told you about the property of Median it will divide this array into two parts where there will be equal number of elements here too and one here too. The characters will be the number of elements, okay, so my median does something like this, so if I imagine this, okay, if I imagine this, then you tell me where the medium will come, okay, what does it mean if I combine the gestures, Samvat like you. Four Five Six Eight Nine 12 13 Okay, that is, I can say that its median is something like this. Okay, because the people who find the mean of these two are something like this. So this part has become one more line. Now one more part has become right, now how many elements are there in it, look, you are four, five is six, look here, 2456, so can I say that this is my left half, if we combine both, then this is my left half. This happens to the right and which half is this? This is my right half, so all these come to the right half, so can I say that I can divide this? If I can do this, then which half is this? This has become my left half and this has become my right half. Okay, right now everything is going on high cortical, I don't know how to cut, I don't know anything, I just know that it has become short, it looks something like this i.e. some elements of A1. And become short, it looks something like this i.e. some elements of A1. And some elements of A2 follow the left hand side of the gesture as you can see here 2456 Okay 9 12 8 39 128 13 So this is what is happening Okay now it is possible that There is no six here, if we don't take six late, then it becomes something like this, okay, if it becomes something like this, okay then Samvat like, this line will not come straight, it is always visible, it is a very good example, I have taken the same thoughts. Dividing by is going on anyways. If we go back to back then there is a picture like this. Okay, now you know what your answer is. Six and eight. Okay, now what is going to be six here? Look, the left half of the left half. The largest element of and the smallest element of the right half, these two elements together are contributing to me when this and the length is okay, that is, what can I do, I can do here because this is A1 sorted, okay because. This is A1 sorted so I can say that this four is going to be the largest on the left hand side and this six is going to be the largest this six is going to be the largest this six is going to be the largest on the left hand side. A1 and A2 are in the respective i.e. whichever of these two is in the respective i.e. whichever of these two is in the respective i.e. whichever of these two is maximum. It will be okay, if I call it L1, it is okay and I call it L2, then I can take whatever is the maximum of L1 and L2, that will become my element, that is, the element on the left hand side will become similar to the right hand side. What will be the element of right hand side will be the minimum, in which nine and eight it is okay, that is, I can take R1 and r2, okay, so I can take this will go to my max, this will go to my mean, okay, their which The result will also come, if I calculate the mean then I will get my median right but if it was odd length, now the dream has to go smoothly and the length is getting, order late, what will happen in this, is it ok, then it is alt in this, if you are here, how? Look, okay, I will show you how hot I am, see, I said, 249 and 12 are okay and five six eight and 13 are okay, if they are of odd length instead of you and Link, they are okay of odd length. So what is the value here? If we remove 13 from the left then it will be 437. Okay, if you do 7/2, you will get the cut. Samvat like do 7/2, you will get the cut. Samvat like do 7/2, you will get the cut. Samvat like 3.5, other point five and you will get the cut. 3.5, other point five and you will get the cut. 3.5, other point five and you will get the cut. Three, okay, so I can. It was that I two would choose this and one would choose that, okay less, what would happen to me now here, this one is gone, this is yours, the second one is yours, okay, this third one is yours, this fourth one is yours, so what is your answer? What is your answer? Your answer is six. Obviously, write it straight and see 2 4 5 6 8 9 12 13. Okay, so this element is the third index which is zero one two three. Your answer will be six. What is six and this? This is ok date main's six is what and this? This is ok date main's six is what and this? This is ok date main's six is what six is nothing but minimum of this right hand six is nothing but minimum of this right hand six is nothing but minimum of this right hand side one if we are calling it R1 if we are calling it r2 then whatever is the minimum of R1 and r2 that should be your answer. Okay, how was this odd one, I will give it a mit, okay and similarly, what will happen in R1, r2 and this whole is divided by you, okay, so this is yours, imagination is the limit, it is not gold money. If it seems to be a memory, then we have imagined one straight and we have made it less. When you will actually face this problem in the real world, will you be given something like this that these two are irreconcilable, in this one is the tax element and which is that tax element? From what you can imagine from the gate, we will not see only this one, okay, we will see some test cases, we will see A1 A2, brother, tell me what is the medium, let us find out now what is this cut, how will we make this cut. Okay, how will we say that this is where the cut is? How will we say that this is where this cut is? This cut can go here too. It can go here too. And its length is 4. If it is there, then it is necessary to do it a little, even if it is three, it is power, even if it is two, it is power, even if it is one, it is power, and even if it is zero, it is power, okay, the problem is, what is my problem, what is being reduced, I know that if I take out the cut If I take it, I will get the answer from this formula Date men's know what I have you do next and wherever you find sir tea in a sorted dairy, then what do we pick up, okay then what do we do, we see a proposal, understand one thing I am from, I am naming my left hand side as L1 and L2, I am naming my right hand side as R1 and r2, these are my ones, see, now should there be some property in these and these? If the property is making this valid then the action will not become valid. What is a valid cut? Okay, so my question was that this cut is valid, why was this cut valid? Okay, now the property here, first of all I have to check these elements, just okay. Why is it because this element is bigger than all of these? Okay, that is, if it becomes smaller than any of these, then all these elements will become smaller than this half. By similar concept, if sex because these six in all If six becomes smaller than this and becomes smaller than this, it means all these elements will become smaller from here, so I can put a condition if I call this L1, call this L2, call this R1, call this r2, what is the condition I put? I can say that if my L1 is less than equal then why r2 and not R1 R one is already smaller than R one brother it is sorted so L1 is obviously smaller than R1 if R1 as well as r2 Also becomes smaller and L2 what happens to you, let Li become equal to which R1, why because it is smaller than r2 anyway, if this condition is satisfied, it means what is the cut, is it a valid cut, okay then I can. Completely like if Now look here, what will L1 become, what will R1 become, okay, now how many elements have I taken here, one, how will I know, how many elements should I take, how long is this is four's length, okay, how many elements have I taken, this is four. Length i.e. there are total eight elements is four. Length i.e. there are total eight elements is four. Length i.e. there are total eight elements here divide it by what do you give Kar elements are correct i.e. your Kar give Kar elements are correct i.e. your Kar give Kar elements are correct i.e. your Kar elements should be on the left hand side, you also believe right now what has to be done right here is that right here, what has to be done right here is that You have taken one element, you have cut it here, Date Mins, you have taken one element, where will you pick up the remaining elements, three elements will be picked up here, one, three, okay, I have taken the third element here, so you see, 1 2 3 4 Left Hand Side 10 1 2 3 4 Give right hand side, okay, four elements each, that is, I have to pick one element from here, in the remaining, I will pick it from the other, it is perfect, okay, now check the condition again, this will be your L2, this will be your r2. It will be done kya tu is li dene equal tu 13 get 2 is li dene equal tu 13 hai yes hai bhaiya perfect chal raha hai kam chalo kya 8 <= 4 hai kya 8 is li dene equal tu kya 8 <= 4 hai kya 8 is li dene equal tu kya 8 <= 4 hai kya 8 is li dene equal tu four hai na date mens this cut ise note Valid is fine, this cut is not valid. Now what do you have to do to make this cut valid? With whom is the problem? There was no problem with you and 13. With whom was the problem? With Aate and 4 it is okay, that is, either I or 8 will have to be made smaller or this four will have to be made bigger. I have only two ways. How will we make this four bigger? By moving it in this direction. Is it okay? By moving this direction, am I making a gesture? No, what am I deciding? How many are here? The elements will be from this one, okay here, if I choose This is dependent, there is no tension, there is tension, where am I making the cut here, okay, so from I can, I have to increase this value, so bring it bigger here, okay, now again this one has become your L1, this is yours. Now R1 has been made because this one is not a cut, now this new cut has been made. Okay, now for how many elements do you need two, how many were there, so I can do 4 - 2. If you want to pick me two, I can do 4 - 2. If you want to pick me two, I can do 4 - 2. If you want to pick me two, then one and you put the second cut here. Now this is done Okay, now what to do, nothing friend, find out the max from this, find out the answer to meet from this in maths because if there was length and length then we would have done something else but what is the problem, we will make a cut here, we will make one here, we will not make one here. Friend, look, understand this thing, you can do it efficiently only here you can apply binary search, how can I help in deciding this cut, that cut in first aid can be done through binary search, I cant say this. Obviously I can see this relationship, don't you see here, this is you, this is four, this is nine, this is 12, okay 10:30 Right now I am obviously making a cut here, 10:30 Right now I am obviously making a cut here, 10:30 Right now I am obviously making a cut here, okay in this and three here. Will go into this, now into this, I am comparing when I think I want to enlarge this four, so in the gesture, where are the big elements on the right hand side, so obviously I will move here, so will I increase it by one. Okay, if I want a bigger element like I had one more place, you have to move the bigger element date mains for bigger, where do you have to move it to the right, so how do we move it to the right, okay now, similarly, if you had cut here, then it is here now. If three elements are gone then you will have to take one here. Your 5 is smaller than 12. Yes, the condition is satisfied but can nine also be smaller than six. No date mains, I will have to make this nine smaller. The smaller one is here. If the smaller elements are here, then how do we move here? Let's do left hand side left how do we move here? Let's do left hand side how do we move in binary search and it is equal to me minus one so let's search gate of supply binding what will come out from the head we will take out in cut Okay and its relative we cut you here and take out We will take and cut one cut, we will find out the answer from you, okay, but again one more question, how should we know, A1 and A, you have given two answers, okay, now understand this, I am saying this, friend, from many elements here 257 13 This You have a big city and a small one, poor Seven, how many total elements are there in it? Three and two, five and one, six. If you go to the middle of it will be three. Okay, now it is very late, your Khatwani of Assam has arrived here, that is, you If one element is lifted with a gesture, how many should be there in the other element, there should be two elements to lift it, but here there is only one, here you have become deficient, it is okay if you have become deficient, then I can help, here the chances of failure are increased. What will we do because we have to make it efficient and minimal binary search has to be done, so I would say that I am fine with the smaller size array, that is, if I have to search for the smaller length one, I will search smaller. It is okay for the length ones, if it is of the same length as both of them, then put it on anyone, it does n't matter, it doesn't matter who is coming to ask, okay date men, we have made many conclusions first, apply, okay, condition number one is okay. So what did you get from this, n/2, you wanted n/2, so I said n/2, n/2, you wanted n/2, so I said n/2, n/2, you wanted n/2, so I said n/2, n means, n1 is one small, n is another l, so their sum is divided by tu, okay, so I combined it also, this is the anger, these are the minis, you cut one. How many elements have I taken, okay, so can I take out other elements from this formula? Of course, brother, I need elements from the first, I will take only three from the second, so that's what I did here, okay, N is equal, you are okay if this If the condition is satisfied then we check which condition is failing then if this one is failing i.e. then if this one is failing i.e. then if this one is failing i.e. I can say that L1 is greater then r2 is ok, it means what will have to be done to L1, it will have to be made smaller and this we How to do small How do you do small in feet How do you want small element in increasing Are where will you move Right no left Will be behind only give small element I can say I bill do and deziqual tu mine whatever I came or cut one your Whatever name you take, we will discuss the name there, then the middle one is fine and the second one is fine and what will we get in the second one? Start is found valid. Valid is found in some way, so please check it, friend. It is okay. Here the answer can be given in two ways A and if there is length then what will be the answer Bill B Mean of what Max of whose L1 L2 plus mean of whose R1 r2 okay its divided by tu and odd ke kaise mein kya Can I off in off R1 and r2 Okay, we've already talked about it Okay why because what is this is my n / why because what is this is my n / why because what is this is my n / 2 comes obviously and what is this comes this is my n / 2 - 1 and This comes plus is my n / 2 - 1 and This comes plus is my n / 2 - 1 and This comes plus N/2, okay, so eight is given, your answer will be N/2, okay, so eight is given, your answer will be N/2, okay, so eight is given, your answer will be N/2 only, right, this is A, this is N/2 only, right, this is A, this is N/2 only, right, this is A, this is okay, here you know in binary search, two important things are start and, okay, then start and. How do you keep one thing in mind that my start will be at zero, okay and I will always be at four, the last index of the gesture is three, but why I took four, because if I am of, I want all the elements in the era, then all means four. All the meanings will not be free, okay, that's why we are taking indexing plus one and now you will eat plus one, brother, you are taking it to zero, start it from one, no, we can also take zero elements in the first, this one. How to see this one, how to see 78910 is fine and this one is 1234, now how will its medium come out, it will come out something like this, it will be divided like this, okay and when you divide like this, then you will eat brother L1, there is nothing, L1, then go out. How come in this, what happens to you? In this way, your r2 is nothing, r2 goes out and if it is the reverse, something like this is distributed, okay, if something is distributed like this, then what happens here your R1 goes out. And here L2 goes out, okay so I can say this, how do I have to handle this one too, so what I did one less thing is that I changed the indexing from 0 to 4 that brother, this Eric can also take zero element from here. Four can also be taken similarly, zero here, 4 here too, okay, so what I did to and to n1 means its length is I am okay, I am the length of the smaller error, so I can take n1 and Start your zero is ok so you understood without searching where we have to apply what is our range going to be right ok but how will you handle the cases when L1 l2r1r2 is going out let's see and 1234 is this How is it not, this cut is valid, why because you can see that these are all small elements, the next element is your seventh, that is, this cut is valid, okay, you handle the cases, what should I say, I have to give a default value to L1, okay. And how is L1 satisfied? L1 should be less then equal to r2. Now r2 you yourself are sitting outside. Okay you, I have to compare them but I have to validate this thing. Adverise will fail me because I know this. If it is working absolutely perfect, then I will take such a value for L1, okay, the minimum value which is greater than all, only then it will satisfy this condition, then I will say give it the maximum possible value, okay if you are not able to see, let me lie. Me just write it here ok what am I talking about I have to satisfy this L1 take r2 and the second one has to satisfy but this is how I am in Andher Nagri Chaupat Raja Nal One, there is neither r2 here nor R1 nor L2 but I just have to You will have to validate because you are seeing it is correct that it will come only after 1234, it will come only after seven, but sorry if you are still not seeing it, but after four, 780 will come, this is what I said, okay, so what can I do? That if I have to correct this thing with some trick, then how can I do it in this particular way, if my L1 goes out of the year, when will it come out of the L1 era, when will it come out of the L1, Mines One Mines Tu If it is okay in such cases, then I can use L1. If at any time it is going out of error, then I will give a default value to L1 which becomes the minimum. Okay, now you have to make this condition true, then this guy should be given the minimum value. Do this and maximize this guy's maximum. From here, maximize this guy's maximum, minimize this guy's maximum. If you do, can you say that I am satisfying the condition? Obviously, it's okay. So this min we got another ACS that What is the smallest element and similarly this is how your L1 and R1 became, what will become of L2 and r2, what will be integer.max Underscore Maths, the score integer.max Underscore Maths, the score integer.max Underscore Maths, the score value is ok, perfect ok, tell me it is ok, number of elements here on n1, how many n1? Tax from pay element, how many elements are there on N2? If there are elements on N2, then I can do tax. Capital N means N OnePlus N2, how many are there? 8 and Median, how much will be yours? 8/2 Date Mains 4 means your tax yours? 8/2 Date Mains 4 means your tax yours? 8/2 Date Mains 4 means your tax element should be on one side. The tax element should be on one side and if you have 9 elements i.e. odd length then what will you get if you i.e. odd length then what will you get if you i.e. odd length then what will you get if you note 9/2 IT Bill B 4.5 note 9/2 IT Bill B 4.5 note 9/2 IT Bill B 4.5 then we still say tax here and there, one center one here and the same medium. If it is okay, then this is this point, we are understanding it, okay, the date is valid, what is medium, how do you get medium, zero plus four is not a minus video, then this is zero, this is your one, this is your three. Okay, this is three, this is you, this is one, something like this, okay, n1 is N2 perfect, here also understand it like this, zero, one, you are three and four, okay, then I am you, that is, I am making my first cut here, okay. Let's just change the color. Okay, I said, I'm going to make the first cut here. Okay, this is it, see one cut one. Okay, now how many elements do I need? Okay, I've already taken two elements here. That is, in the second hey, cut me, I can use here, if I have taken two elements in cut one, then how many elements will there be in cut one, this is cut tu, how many elements will there be in this am let me change it you. Okay, how will you get this mines cut one four, this is also not very important. Here, okay, how will we get four, so what is your M? Index Ko Eric Index is something like this 0 1 2 3 Okay, this is it but what is the index your M is M at this time you are pointing it i.e. you are M is M at this time you are pointing it i.e. you are M is M at this time you are pointing it i.e. you are pointing it nine to nine i.e. I can say that M is Nothing but i.e. I can say that M is Nothing but i.e. I can say that M is Nothing but which part becomes R1 so m is R1 pe that means you have to take out L1 then L1 bill b nothing but me what can I do from the concept that now here mujhe kat tu kya mila kattu milattu ok so Zero index first index tu index here 8 what happened to me 8 happened to me r2 okay so I can say cut here you cut you this is nothing but I came okay so L2 if it is removed then L2 What will happen to me this -1 ok so I can cut you minus -1 ok so I can cut you minus -1 ok so I can cut you minus one instantly your answers are coming ok very good this is mine this is my L2 condition is true fantastic you got the answer in one shot we can This cut is valid, now how many elements were there in total, here, there were eight, and is, that is, out of two answers will have to be taken, what is the max of this, the two answers will have to be taken, what is the max of this is nothing but six, the second is, this is nothing but It's 6 + 8, it's 14 / 2, it's 7, 6 + 8, it's 14 / 2, it's 7, we got it's simple, okay, so this question was very big, but how we broke it down, we told you that you can also apply liner truth, we optimized it, we If we find it, what will help us is that we should focus on the smaller one. Okay, so this sir, we will solve this question by drawing the conclusion. Okay, so it looks something like this for me. I am late in copying it because if you have seen it is two days old. What happened to me earlier, okay so there is no use of writing there, I type so much and so first of all what is the condition to check, we have to check that the make number which is minimum has to be put on it, so now I fail. Should I put it brother if the number is small then don't run this instead let me make it strict that brother I want only n1 to be small, I will always put binary search in it, okay then I can say IF, how will I say this, Namas one dot length is okay if this If it is big then it is equal then I have no problem if it is big Kiss Namas tu dot is ok with the length it means my name tu what is in this kaise is small so I will make the small one back to big I will say ok with me I will do the function tomorrow, we call it as nothing but function, you make yourself do it tomorrow. Okay, so I will do it tomorrow, so this will be done. Now what has to be passed here, what happened here, Greater and Namaste, you are smaller by the way, so because of this. Because you no name one make it smaller and greater perfect and if there is nothing like this then it will go down normal okay so just did not do anything to me I said friend if the length of name one is greater than n then return these two which The answer will also come and I swapped these two, so if the number was big and you number was small then I changed their name to Adal Badal, okay these short after this line the number is okay so this looks great. Friend, this is the fun of coding. Okay, if you have all these concepts, don't get overwhelmed that brother, all this will not happen to me, I am quitting coding from today onwards. Okay, look, you will have to see all this stuff, it will sometimes hit you, sometimes it will not hit me. I did not hit this for the first time, I saw it in the form of I think, some guy took the solution, okay, so others also teach you to study this concept, it does not happen that we know everything, but we have to understand it and the solution of others. Understand that this is one of the biggest art that you can learn. Okay, so that's why I am saying that don't worry about this whole thing, concentrate on what you are going to learn. Next time, if such questions come in the story, I will solve it. Okay, that was the thought. Should be the intention, let's put it, enough, start equal to zero, okay, these and this equal to n, let's take out n1n2. First, their length is okay, so I can say, let's take out the length. What will happen here, I always put n1. I am, I can, n1, okay, why didn't he do that, I have already explained it to you, okay, no, let's search, we can, in, cut, one, it is equal, what will you come, now cut, how will you come, this cut, how will you come, your place here. You have to do simple n1 + N2 i.e. total elements is n1 + N2 i.e. total elements is n1 + N2 i.e. total elements is ok minus cut one ok so obviously cut one as many elements as total minus cut one remove it then cut what will you get then I can do this n1 Okay n1 + N2 N If you want can do this n1 Okay n1 + N2 N If you want can do this n1 Okay n1 + N2 N If you want it will be capital approach What do I call this I say note equal tu what am I writing and here I can write cut you is equal tu N okay now what to take out now saving Is L1, l2r1 and r2, okay, so let's find it, what can I do, what will happen here, so what is visible here, we have already taken m=r1l, m=r1l, m=r1l, okay, it will go out, let's put inteaser.mender school. My cut one is equal to hero's is put inteaser.mender school. My cut one is equal to hero's is put inteaser.mender school. My cut one is equal to hero's is ok if how is it then obviously I ca n't do minus one in c so what to take here teacher dot in is ok note in maths the underscore value is ok and if something like this is not sold So what will we say, simple friend, what should we take of number one? Cut one minus one cut one minus one perfect. Now, similarly, take out L2, then I will copy it, ok, inter paste, what will happen? Now I say that friend, I am L2. I am talking about if my Kattu becomes zero then similarly I will take the mean and give it to us then R1 r2 Now what will be Cut One and Cut Tourist i.e. I can also tell the story of Cut i.e. I can also tell the story of Cut i.e. I can also tell the story of Cut One and Katu Mere Yer Ke Length So the problem is brother, okay then R1 = cut one equal = cut one equal = cut one equal what n1 is okay n1 what is the length of variable in this how in intejaz and max underscore value is okay and I can ka adware kya take NMBA one ka Cut one is okay, it is perfect. Now let's copy it and do it and L2 take it equal you are one okay adverb else how is it distributed you will have to find the mean okay so here I can easily return. Math dot minimum of what is R1 and r2 okay and because I have to return double here on here if I want to return double here on here then I will write double here okay what will be in this R1 r2 and this value divided by tu okay Value Divided by Tu Fantastic Everest Okay and what can I do here that the FU check is over Katwan plus one Okay and now this code is coming out of this you can do something simple here If you want to return something, then you should avoid it, I am returning 0.0, this is okay, you should avoid it. Which error is it, 0.0, this is okay, you should avoid it. Which error is it, 0.0, this is okay, you should avoid it. Which error is it, brother, if it is a double function, then return something, that one is okay, so let's go through it once. Said that we names will always make them short n1 took out n took out start and took out ok and this I searched now I found cut one and I found must be right meaning brother is 8 I want to do it I did eight, I said, you take one, which is a little like this, okay, this is the thing, I thought, I explained it to you a little, I gas, I explained, a mistake was typed here, l1l2, R1, r2, I have to get it perfect, no problem, okay, L1. How is this answer in Audi and how is this answer in K? It is correct, it is perfect, but it is not true, why is it not perfect, please comment and tell me, why will it give wrong answer, okay, so here your 2.0 will be correct. If you have gased why 2.0 will be correct. If you have gased why 2.0 will be correct. If you have gased why because it is an integer, by adding it you will get an integer, by dividing it is four A, okay and this is five A, 4 + 5, what has happened to you, nine, you have divided nine, 4 + 5, what has happened to you, nine, you have divided nine, 4 + 5, what has happened to you, nine, you have divided nine, if you have If you divide, what will be the answer? 4 This double is placed here, first this bracket will be completely solved, okay, then it will reduce its value, that is why I said make it 2.0, there is definitely no gas in this double, make it 2.0, there is definitely no gas in this double, make it 2.0, there is definitely no gas in this double, I am looking at this table. If you remove it then also the answer will come. Okay, so lecture you one think let's copy and check it on lead code itself. What is the answer? Okay, so I will copy it and go here. Let's go to the white screen. Okay. So I think this should not work actually interior plus wait divide by double your double this answer will come obviously ok 100% faster solution is beating 100% faster solution is beating 100% faster solution is beating everyone and this was your one of the most dreaded questions of DISA ok by set There is a lot of value in this question, it is a very hard level question and as much as I have convinced you, even a snake must have understood it with equal pleasure, so friend, this was today's video. If you have liked today's video and till now If you are watching this video, please comment and see you soon in the next video. Till then bye and take care.
|
Median of Two Sorted Arrays
|
median-of-two-sorted-arrays
|
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is 2.
**Example 2:**
**Input:** nums1 = \[1,2\], nums2 = \[3,4\]
**Output:** 2.50000
**Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5.
**Constraints:**
* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* `-106 <= nums1[i], nums2[i] <= 106`
| null |
Array,Binary Search,Divide and Conquer
|
Hard
| null |
1,029 |
Hey guys, welcome to some YouTube channel, so today we are going to show a question, its name is 216 question read, I will look at the subscribe button, if you have not subscribed again then the problem with the first question is that the question is saying that you have a list of candidates. For the interview, you are like, okay, there are some crazy 16 places for candidates A, so this one which is this one and this divine one tells that if you have to interview the candidate number one can be drawn in you have to get it done in the city number, city level payment. So you started trying to get accepted in the city, then you started fasting. Okay, after the company, there are cities, it is okay to do the interview and some candidates want to get the interview done at minimum cost to the company, but the company wants the office. If two NSS posts are not vacant and there is one candidate in each city, then it is okay if our two teams have equal number of candidates and the cost is minimum, then how much effort is there to make us have such a distribution and tell us that we are its intensity. If you don't protest then do it according to the union before this then I say subscribe forest officer take loot M then if I do that Okay, okay, I will come for a special dish. President number two came at Ravana Gate number 2, so friend at number two, send it from here on 1212. There is an option in Arabic. Okay, so I want to go for the exam. Telegraph India on Thursday. Some options. A had happened, okay, till now I have sent messages to two candidates, so now I Then if no one can survive like this then we will go in the meantime okay similarly here I sent the extra on earlier also seeing the maximum ones by the studio last year here who took ice cream y3 from the candidate then X So we have also sent this messenger that this same candidate should go to other theaters and this theater has to be maintained and all the cosmetics have to be shared. Okay, if I send this to this person, then pick my cost, this also music, then my quantity. And the maximum of which has to be returned to the answer also. Okay, so I make it functional from medical, then I will apply anti in it. Okay, if I make them in this way, then I make them depend on different time, make that chapter different. So the city in these angry people is okay, first of all this brightness is maximum in government exam 2009 subscribe this Video Channel subscribe our group admission is okay and in your quantity where cost free is to be taken then coastal plains we will cook that At present, where is Posh, wife? You go and we have reached our result. Now we do not know whether this result is minimum or not, so we will simply return it. Okay, so what should I do, right now I am doing zero return at home. Okay. So when I go up the stags then I send my now Aman return zeroed ok second by selling which if the existing that if I am yours where should I reach Yuvraj that the cancer is separated if my total arm forces and I Do n't forget to subscribe to Three Idiot No. 13 and are appointed as Inducted Return's message start match here. Ok why am I sending the message to remind my time. If I can keep the text message to minimum then this is the answer in Vellore. Now let's decide our call. Okay, so our call has been made, but we have a feeling that we will go to our next date in this action replay and the minimum that will be on that will be the answer from our biddat, both of us are the answer planet, how will we take the moon sign. ok my favorite I will call one more ok the first one will be cosmetic if I ring 1 or still ring ok if I send the assistant to one or is liquid that message will be received by me ok whatever I am crazy I send then I The answer I got is 20 from the election date. I am not getting the answer. Given my page, I am getting it. So I will be skimming during those times. Okay, so what will I do? Now I decide and the answer is yes no. In this video I will tell you. Its race is passing city next medical college plus one shy please input one more if one of these account will increase but will remain firm then we will die from obscene A Caution I should go on next date die from obscene A Caution I should go on next date die from obscene A Caution I should go on next date ok and will keep a message on this we will also Even if you unmute, the number of contacts increased and at the same time, I have to add salt, we have to add it, if I add more breadcrumbs, how much will it cost, so that when it comes back, the call recorder comes back, something like this, the track is made by me, it is okay by doing this. So here is the cost, when Bigg Boss comes back then the cost goes to Reddy okay so when I come above I have the cost total in the answer okay so I am adding some cost here okay so in case of that In case of 1 the cost side in this we are the candidate but we need it because in the acidity custom Patel Murali wale and I ghee, I am enjoying it, now my stomach birthday I fold it like this, return send WhatsApp systematically. 110 common minimum services at home, paying guest to something is from the earth Jhali Shalu Jhali on the basis of great benefit increased minimum taken sir doctor Australia Tarse ke rugged one point get done to 1968 cost then 100 or 200 commission of this we are a If it happened then our answer is that the body is fine from the experiment, the situation is not right that the soldier because it is very slow, how do we see it from the plate, we understand that I and my son continue there, it is in the bank accounts like if it remains then I will do one or two. So in the beginning, when I started, you are ok, one candidate went like this, ok on Thursday, so I wrote 200 like this and in the previous video, number one, number 11, left side 2012 ok, so now we subscribe to both of them from here. Here I asked the third candidate that if I am one day ahead and that child is one, then tell me that if I am defeated by two candidates and I am on the third, then what will be my decision, it is my call to crush from here. Or some refused them, if it comes from here also, then in terms of ghee value, the candidate is also the same and in the case of wife, these two will be the answer, this will be from the sample of MPs, this is fine, it is an increase of small liter if support. If there is a button then it will have many values which will be the support. If there is a button then it will have many values which will be the support. If there is a button then it will have many values which will be the same but they will have many values and same but they will have many values and same but they will have many values and from the big Rs 3000 onwards it is quite a battery saver so you can use it on your bike but if it is ok then how is it a festival then you can use it. It is okay with my tension or cutting, our answer will be with you, we will start, so to do that, I get the display, pass the matriculation here, look for the dictionary, okay then how to do this in the store. I am starting the basis, the proof is that I am judging the memory element and I am doing the Play Store, on whose basis it came, which one is my favorite and it is even better, so I have got it at the rate in Tappal, which is the list. That's dutyable is patience okay so here I D where I call here I pass my dictionary that comedy okay so if the f-18 patient and f-18 patient and f-18 patient and it's on the level and so white then I Again, at the same time, everything is fine, so all this is far away, so find it separately, please subscribe, it is fine, so on that, it is quite simple, 800 jhal and government and fee and Pintu Sen, but this comment is fine. So it will be four managers and delivery, so now it is time to send it on leave to school, if I give acid to everyone here, then I am fine here, if I meet, then subscribe to my channel - 2 - two in a separate profit, which would be 2 - two in a separate profit, which would be 2 - two in a separate profit, which would be Bigg Boss property. Is in this case set a reminder for me near - protein rich profiteer this near - protein rich profiteer this near - protein rich profiteer this clip now in this case I turn off the torch 0 - 5 ok one tasty turn off the torch 0 - 5 ok one tasty turn off the torch 0 - 5 ok one tasty this thing in this and this case 98100 so what do we do if I transfer money I need to subscribe as per minimum, it's only one I and one you in profit, if I am fine by subscribing, then what has happened, uncle, I have made a negative profit, so here my loss will be minimum, where my sum in the last But I will send one to you, okay children, how to survive, I will give you a lot, so this is our meat, we will appoint you from this, okay, I have no words, I am a child for one month, now look at the logic from you are the leader, so in this, we will take one under you. But in the dance, he made an agreement with a seller of cigarettes - It is also okay, if I send it to him, then - It is also okay, if I send it to him, then - It is also okay, if I send it to him, then how much difference will I get from him, if ours is low, then think that if it reaches the minimum, then the benefit in this is all that we have given the cigarettes to him. The best approach, the best answer is that you will reduce the idle speed, so now we come and do this, move the free dish to the side, so I do, I put it last, so that's why I told this is ok, please note that I will cost. Okay, so the Commission please clarify, so I have expressed in the to-do list that at what time, I should subscribe and subscribe to appoint and subscribe to that express element and element to the concept of Schezwan meaning of difficult, so subscribe to the most. We will reduce it, okay, we are children, so now what do we have to do, we have to pick up, okay, so let's do one thing, Core I3, a range of flash light, cost, then instead of doing the whole station, I will commit suicide only during the positive vibration time, so first. From then on, I am forced to take the answer. Now what do I have to do, which is my topic and subscribe to it? At least, if I am here, it is fine for me in a day and if I click here, it is fine if I If you click here, then I have to click here. Okay, so from here, turn me on 10, it will be something like this, so I have one point, so I have gone from here to here, one point, after taking the amount in advance till here, these two are one. Same principle, they will take one point, if you cooked it at zero and 250 which is this and two plus minus 10, then you will get cancer. I have to add the sequence time in the answer, what should I do about the loss part i.e. the pilot should understand what to part i.e. the pilot should understand what to part i.e. the pilot should understand what to lift a crow. So 1 hour ago post nfo 10 plus do subscribe in the loop and what all is happening just understand that the ticket is going on quite close I submit crores and 13 so guys she will ask
|
Two City Scheduling
|
vertical-order-traversal-of-a-binary-tree
|
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000`
| null |
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Hard
| null |
226 |
Hello Guys Welcome Back To Take You Jai Hind This Video Also Developed Inverter Battery Problem Which From Day One Of The June Challenge So Let's Not Look At The Problem Statement In This Problem Veer The Very Simple Approach To Construct New In Water It Will Be Not Afraid To Solve Subscribe Now To Change The Giver This Problem Solitaire Facing Some Problem With Request Din This Is Level Problem Co Unmute Practice 100 This Is Fruit Okay So Will Start From Radhe Latest Jobs At Will Through Postal Processing This is that will travel tours and died in the return back to the time when will do the process in which is the latest updates report subscribe now to receive new updates subscribe to the Video then subscribe to the two and will be known you can see the Left and Right Side Par Hai The Sources of Postal Processing Type After Processing Left and Right Side Will Process the Current Not Solved Want to Process Actually Will Just 120 Days Pointers in This Way Want to Make This Left Side Se Right Side Par A Subscribe Click the button Subscribe And What is the City Tours And Use This Point To Subscribe Like Comment Subscribe Quarter Left Has Been Assigned With The Right Pointer So This Point Arvind Change So After Country Your Structure Will Look Like this to will remain in the same position and you will come to the left side and welcome to the right and right to left and right subscribe and subscribe the Channel Please subscribe and subscirbe will not only subscribe now to go to make a call to 16 Have to take right side from Apne Pujya Swami Pointers So after swiping pointers this 6 will be removed and this will actually behave this point Vikram Nal's operation 9 4 Subscribe will actually change the language of the Tarzan The Subscribe Now To The Black 06 Item Side 100 Six Will Now For Android And Left Side Vikram Nal Because Initially Right Side Personal And Those For The Right Hand Side This Two Will Actually Also Move Into Light And Sound Show To Welcome To Right Hand Side And Destructive 103 Veer Subscribe My Channel Thank You Will Make You Love Me Say That Modi Schools Will Have To Process Mod Member Left Yesterday This Is It Well In This Process Is Nothing But You Are Just A Temporary And Subscribe Numbers Between A Very Simple And Complexity Of Enterprises Subscribe Button Solution In Different Languages Please Like Share And In Different Languages Please Like Share And In Different Languages Please Like Share And Subscribe
|
Invert Binary Tree
|
invert-binary-tree
|
Given the `root` of a binary tree, invert the tree, and return _its root_.
**Example 1:**
**Input:** root = \[4,2,7,1,3,6,9\]
**Output:** \[4,7,2,9,6,3,1\]
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,3,1\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
437 |
hey guys welcome back to another video and today we're going to be solving the lead code question path sum 3. all right so in this question we're given a binary tree in which each node contains an integer value so our task is to find the number of paths that sum to a given value so we're given this value called sum and we need to find the number of paths which give us that value when we add those integers together so this is a really important point the path does not need to start or end at the root or a leaf but it must go downwards traveling only from parent nodes to children notes okay so you can only traverse from up to down right and also it does not need to start at the root and it does not need to end at any of the leaves so what that means is if our answer exists from the between so let's say in this case the sum has to equal to eight so one of our answers is five and three and that's a valid path because five plus three equals to eight so now let's just take a quick look at how we can solve this question okay so i'm just going to draw a quick tree um and we'll just work off of that so the r over here is going to start to stand for root okay so let's just consider this as our tree i'm not going to be using any integers i just want to keep it really simple so this over here r like i said earlier this is our root and what we're going to do is we're going to maintain two variables one is going to be called the current sum so this is going to be the sum starting from the root all the way to whatever node we are at let's say we are at node c so it's going to be the cumulative sum from the root over here all the way to c so that's going to be our current sum and our previous sum is going to be the value from our root to the node we are on but the one previous of it so if we are trying to find the current sum of r to c the previous sum is going to be from r to b so that's pretty simple so those are two variables we're going to be keeping track of so we're going to be storing it in some sort of data structure and for this since we're using python we can just use a dictionary so i'm going to be storing all of these in a dictionary and so how is our dictionary going to start off so in the beginning without adding anything we're going to have of sum of zero so that is going to be our key and the value is going to be its frequency so it's going to have a frequency of one pretty simple okay so now we're going to go to our root so we're going to add r plus zero and that is going to have a frequency of one okay so now we took care of our root over here so now we're going to go to the next node which is a so r plus 0 is just r so i'm just going to uh so i'm just going to ignore the zero so over here we have r plus a right so that's the sum and the frequency is one and we're just going to consider for the sake of this all of these nodes have different integer values okay so we have b and for b it's going to be r plus a plus b and it has a frequency of one so let me just fill out the rest of it real quick okay so we've accounted for all of our nodes and these are going to be all the current some values but what is the point of having this and to understand that let's just take a look at a quick example so let's just say in this question the sum so the sum is the value that we're looking for and in this case the value that we're looking for is going to be c plus d if something is equal to c plus d that's the value so let's just take a look at our tree and we know for a fact that we have c plus d over here so this is a valid path c plus d that gives us the sum that we're looking for which is c plus d perfect but the truth is so for our dictionary we're only considering the cumulative values starting from the root how about stuff like c plus d we did not even account for it so how can we take care of such a thing and the answer that is pretty simple so let's just take a quick look at it okay so what we're going to do is so c plus d is equal to our sum and we know that right c plus d has a value of the sum that we're looking for which in this case is c plus t obviously right so what is our current sum going to be so in this case we went all the way to d so our current sum starts at the root and it's going to end up all the way up to d so we're going to draw kind of like a box just to represent that so this over here is our current sum okay so root all root plus a plus b plus c plus d is our current sum and we've already accounted for it in our dictionary and our sum is c plus d okay now the question is how do we know or account for the fact that c plus d exists and all we need to do is if you look at this you can make it into a simple a mathematical expression you could say so over here the current sum is the whole thing so i'm just going to call it cs and the sum is a part of our current sum so i'm just going to do cs is going to be equal to our sum plus another value so some blank value over here and we need to find what this blank value is i'm just going to call this x right so let's just rearrange our equation so let's call this x so this whole thing is called x okay so x is going to be equal to our current sum minus our sum so what is that so let's just solve this equation super quickly so r plus a plus b plus c plus d sorry i forgot to add the c here okay so we have this and we're going to subtract it with our sum which is c plus d so when you subtract it the c's get cancelled out the d's get cancelled out and what we're left with is r plus a plus b so this is what we're left out with and if you look to our x value this is what our x value is r plus a plus b but again how do we know that it's one of our paths and the answer to that is super simple so we went through each and every one of our nodes and we added that to our dictionary and if we had this value r plus a plus b plus d then it is going to be in our dictionary so now let's go to our dictionary and let's look for this value and right over here you can see that it exists so the value r plus a plus b has a frequency of one so we're going to add the value to one so r plus a plus so our count so count is going to be our final answer which we're going to return starts off at zero and each time we find something which has a path which equals to that of the sum we're going to add whatever frequency this is so in this case the frequency is one so we're going to count plus one so our count value is going to equal to one for this question and there might there are a few cases where our frequency is not going to be one since they're integer values and you can have the same sum repeated a few times so this is how we're going to solve our question and let's take a look at how we can do it using code all right so we're going to start off by initializing a few variables so we're going to have our count which is going to be the answer that we returned so it's going to start off with the value of 0. uh then we're going to have the dictionary and i'm going to call it frequency and it's going to start off with the value of 0 which has a frequency of one and now we're going to create a function called dfs which is going to be for the depth first search it's going to be our helper function in this case and we're going to give it the value of the node that we want to is going to be our root and we're also going to give it the value of the previous sum so in the beginning the previous sum is going to be nothing else but 0. okay so now let's actually create our dfs function so i'm going to make it inside of a function if you don't like doing that you could do it outside of the fun okay so we're going to first start off by doing a base case so if this happens we're going to end our recursion and we're not going to make any more recursive calls so if not root then in that case we're just going to return and stop the function okay so over here we're gonna initialize our current sum so our current sum is gonna be equal to our previous sum plus our uh the value of the node that we're on so it's going to be root.val and i so it's going to be root.val and i so it's going to be root.val and i forgot to add those arguments so the two arguments we'll be taking is the root and we're going to take the previous sum so i'm just going to call ps okay so now i'm going to make that variable that we i was talking about earlier i'll call it x and this is going to be our current sum minus our sum and we get the sum from the question over here okay normally you wouldn't call a variable sum since it's a function in python as well but anyway so in this case it's called sum okay so over here we're gonna have uh three statements so the first one is gonna we're first gonna check if x is in frequency and if it is in frequency so this is in the case that it is in frequency then we're going to add whatever that frequency is to our count so we're going to add it to our account and we're going to do frequency and go to that value of x okay so uh now we're going to have an other condition and this is going to be the case if our current sum is in frequency so if that's the case we're just going to add a value of 1 to increase its frequency by 1. so frequency of our current sum is going to increase by one and else if our current sum is not in our frequency and in that case what we're going to do we're going to add it as a key and we're going to give it a value of 1. so frequency of our current sum and we're going to give it a value of 1. and now we're going to make two recursive calls so first we're going to call for everything in the left so we're going to call our dfs function we're going to do dot left and we're going to give it oh sorry dot left and we're going to give it so the pre we need to give it the previous sum so the previous sum for the next node is going to be the current sum okay so we're doing uh the same thing but now for everything on the right so root dot right and we're going to give it the current sum so over here what's going to happen is so we reach the ending once we're done with a certain branch and once we are done with a certain branch what we're going to do over here is we're going to its current sum is not going to matter anymore since we're done with that branch so in this case we're going to decrease its frequency by one so we're going to go to the frequency of the current sum we're going to decrease it by one okay and that should be it so after this we're just going to return the count again so return self.count so return self.count so return self.count okay and let's submit this and let's see what happens okay and as you can see our submission did get accepted and finally do let me know if you have any questions or if you have any better solution to solve this and thanks a lot for watching guys and do let me know what you thought about the video thank you oh and also don't forget to like and subscribe thank you bye
|
Path Sum III
|
path-sum-iii
|
Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
**Example 1:**
**Input:** root = \[10,5,-3,3,2,null,11,3,-2,null,1\], targetSum = 8
**Output:** 3
**Explanation:** The paths that sum to 8 are shown.
**Example 2:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[0, 1000]`.
* `-109 <= Node.val <= 109`
* `-1000 <= targetSum <= 1000`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
112,113,666,687
|
371 |
hey guys welcome back to the channel today we're going to solve a little 371 sum of two integers it's a medium problem and to be honest it's not that difficult by just if you know the tricks it's it becomes super easy so you're saying give it two decimal numbers a and b we want to add them up without using the plus or the minus sign and i say decimal on problems because when you see a problem like this you want to think binary okay you want to think bit wise manipulation bitwise addition something like that but before we go the bitwise okay hey it says sum them up without using the sign so we can use the cheat code okay we can literally just say return okay son okay keep in mind the sum function provided by python as always we like to use python 3. it needs it an iterable item so we're just going to put a and b inside the list okay now we're just going to submit this i believe this works um i think so yeah it works it's super fast 78 and 43 in terms of memory for 30 which is pretty good but this is obviously not what you're asking for this question cannot be this straightforward although it fulfills the description they requested right i added them without using the plus sign or the minus sign okay i just use the iterable property okay but it's not what you're asking for obviously it can be this straightforward okay so when you see a problem like this like i said earlier think of bitwise manipulation and to do this that's a trick the trick is to only need two variables to do this okay so first i'm going to create a while loop and i'll explain on white paper later to show you guys what's going on so i'll say while b okay while b has a value while b is not zero okay do this i'm gonna create a variable called xor okay xr and he's just gonna be the exclusive or again i'll explain on paper later for those of us who don't know what exclusive r is and he's just gonna be xor okay and the carrot symbol and python is the xor okay it's just gonna be the x of e and b okay i'll create a second variable called carry and carry you're just going to keep track of you know when you add you have to do a carry bit if you have a one plus one obviously one plus one is two okay in binary that's one zero so you have to carry you have to put zero down and carry the one which we'll see on paper carry just simply end of a and b left shifted by one you have to end them and left shift by one and we'll do it on paper and see what's up and then we're gonna assign a and b okay a is just gonna be our xor and b is going to become our carry okay this literal decimal and then once we're done with the while loop once b becomes zero because b is going to keep being our carry and our car is being left shifted so there's gonna come a time where he's just zero because we've left shifted so much that's just zero and once we're zero we're gonna break out of the while loop we just wanna return a okay this is the right solution however this should give us an error and i'll tell you why it gives us an error but this is the right solution don't trip it's the right solution okay good it gives us a timer error why because python doesn't have the concept of negative data types it doesn't have the concept of negative data type so meaning in a situation where we're given one of the numbers to add is negative it fails okay but if it's positive okay let's just do one so you can see a positive test case if it's two positive numbers this the solution works so for this we need a language that has the concept of data type of unsigned data types so let's switch to c a c possible so let's switch to c okay so again keep in mind that programming is just a tool okay it's too like languages don't matter okay it's just a tool you want to find the right tool for the job it's kind of like if you come to my house and i get and i'm going to serve you some food but you don't know what food it is they say i'm going to serve you donuts do you want to eat donuts with a fork do you want to eat the nuts with chopsticks or do you want to eat it with your hand so think of the task was to eat whatever food i brought to you but the two you're gonna use depends on the food so it's kind of like programming the two the language you use depends on the problem you're trying to solve in this case i think c is better okay so let's go the same um the same so we're gonna define our two variables okay and which is xor and xor carry okay these are two variables okay define that as integers don't forget your semicolons at the end everything else is the same okay with python we didn't have to define variables because it does dynamic typing so okay create a while loop while b okay xor actually just equals so again the same a x or b the same carrot symbols x are also in uh oh yeah let's not forget our semicolon okay so now curry carry is just going to be equal to the same as what it was before okay a and b okay let's shift it by one okay now the same a oh i keep forgetting my mind is stuck on python okay now a is gonna be equal to xor and b is gonna be equal to carry okay now this is exactly the same as a python code but the difference is we have to dynamically type it okay to what we want to do you ins on time integer 32 okay see okay so this should be correct so let's go ahead and first run code uh we have a we have an error okay it says get some oh okay i'm tripping okay at the end of this obviously we have to return something right because it's literally an integer you have to return an integer so what are we returning will return a okay let's try one more time compile i'm tripping you guys semicolon okay accept it yeah let's go ahead and submit it back oh my 100 faster okay see that this is the power of c it's a hundred percent faster okay 68 man this is so good this is so freaking good it literally compiles zero milliseconds but anyways let's go into the white paper and kind of explain what's actually going on behind the scenes actually uh i'll kill this video here we're gonna have a part two where we explain what's actually going on so stay tuned for part 2.
|
Sum of Two Integers
|
sum-of-two-integers
|
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** 3
**Example 2:**
**Input:** a = 2, b = 3
**Output:** 5
**Constraints:**
* `-1000 <= a, b <= 1000`
| null |
Math,Bit Manipulation
|
Medium
|
2
|
415 |
Hello hello everyone welcome to inflect channel in this question has its recent years in the 2nd id for most recent visit to do the past midnight children to the number two that electrolyte presentation of deposits and its very simple question art friends let's move laxative inside 158 In the input is given to words in this point district 1234 dashir 1212 subscribe will do subscribe to a super - 0characters entered similar one - a super - 0characters entered similar one - a super - 0characters entered similar one - york blue wave ki hanuman sihag betu inter juice pilaya the solid 5 to 0213 dash latk number one 129 and where Trying Toe Of David Two Cups Of Sugar Li Hai That 24 Cricketer Gary Wilson Inside Your Wedding The Number It Will Toe 89 Subscribe Model Subscribe To A Sodid Fixed Deposit Fakt Next To Characters Art 2.1 Feel Extra Delhi Characters Art 2.1 Feel Extra Delhi Characters Art 2.1 Feel Extra Delhi From Its Buddhist Roots As One Plus One Subscribe Avoid Model Subscribe Container Process Inside To I Will See The Only One Internet Left With One Officer Is Dynasty 2014 This Is Universal Object In Case Of Bird * Number Nine Plus Seat Subscribe To That Bird * Number Nine Plus Seat Subscribe To That Bird * Number Nine Plus Seat Subscribe To That Without Laborer Electrolyte That Recording Paa That You Comment 200 Ultimate Fighting Over The And In The Ultimate Fighting With Spring According To Thursday Video Subscribe Number One In The Mid Day - Now School In The Mid Day - Now School In The Mid Day - Now School Ki Shaadi Get Updated December 10 Understand Small Distance Between Two Points Hain Inke Is Dahej Video Same Time I Don't Need You Tube Skit For The Subscribe Now To Receive New Updates Amazing Do It In Hindi Minutes Check This Time Answer This Career Astitva Viheen More Subscribe To Hain Akshar Update Time Complexity Of This Approach Is Length Of Album Plus To You On 128 Watching The Video Is Villa Dare To Like Share And Subscribe Our Channel Sabs Great This Is Institute Mom With Another Expressing Only Good Night
|
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,314 |
I had also today we're doing this vehicle contest 17 I'm going to start with the second problem here so prob 1314 match matrix black something so the problem says given an M by n matrix and an integer K want to return a matrix answer where each answer I check is the sum of all elements in matrix C such that R and C are in the range i minus k j- k and the column is in sorry the row j- k and the column is in sorry the row j- k and the column is in sorry the row is in i minus k i+ k range and column in is in i minus k i+ k range and column in is in i minus k i+ k range and column in J minus k j+ k range and our c is a J minus k j+ k range and our c is a J minus k j+ k range and our c is a valid position in the matrix so something like this with k equal to 1 so for each one it's i minus one man's want to I plus one range and then we sum that and it's nothing with the columns here the ranges are 100 from 1 to 100 here for both the lengths of the number of rows the number of columns in the value of K and so here you could see if we do just the normal growth for solve a solution we would do well to for loops for the rowing comes so that 10 to the power of 4 fights and then we'll do to go from I minus K 2 I plus K will do another for loop that is the COS is 100 at most and then another one for the column so 100 so 10 to the power of 8 because 10 to the power of 4 to the power of 2 and then 10 to the power of 2 so overall it's 10 to the power of 8 which will certainly gets us a time-limited exception and so we'll just time-limited exception and so we'll just time-limited exception and so we'll just avoid doing a time doing a brute force or so far this one here but you could see here we want to sum of all the elements so if this was an array right and we want have some inner range what we'll do is just take the sum from the start of the array to the end four of us say aye and then the sum for J and then just take the sum for the bigger one - the son for the bigger one - the son for the bigger one - the son for the smaller one right this is just called a prefix son right so we can extend that to be used for a matrix or a 2d array and so let's see how this can work and then we could submit okay so now let's see how we can solve this problem so as I said for the array if we had an array and we had a similar problem for an array right so what I say we had an array like this two three four it's always a good idea when you have a problem that has a 2d array - first if problem that has a 2d array - first if problem that has a 2d array - first if you are struggling to solve it you if you are struggling to solve it just try it with an array and see if that works if you can come up with something and try to apply that idea to their 2d array so here let's say I had this array right here not necessarily sorted but maybe let's just make sure it's not necessarily hmm maybe four right so what would happen here is that if you got asked it for a range like this from let's say so this is 0 1 2 3 4 5 right so we'll further ask it for a range from 2 to 4 for the sum for that and maybe basically we are asked it for the ranges for all the range sum or something like that and so maybe the array could be really long so we can't just do it brute force way so what we'll do first is just well let's get the sum prefix sum for each element so prefix so which basically is some in the range 0 to i right so for every pick some I it's the some time 0 to I so we'll take the sum from 0 to I compute it for everything in the array and then from there to get this something like the range to 4 we just take for the prefix and for 4 and subtract it from the prefix some 4 - subtract it from the prefix some 4 - subtract it from the prefix some 4 - right so the solution would be some for this range 2 to 4 we be just the prefix some for right from 0 to 4 so that would be 4 and then minus the prefix and for 2 right because that's what this range is it's just this entire thing - the one R - just this entire thing - the one R - just this entire thing - the one R - right and so this is the idea that we are going to apply here because what the problem says is that for the answer we need to be essentially the sum right for I minus K 2 I plus K this is for the columns and then J - K - J plus K right columns and then J - K - J plus K right columns and then J - K - J plus K right so if we kind of construct them the matrix in a way let's just represent the matrix as a kind of a square like this so if I had something like this and we are asking for answered position IJ right so I'll say this is IJ then what we want to return for answer is actually I minus K like this maybe K is less a 3 like this so I say cake what 3 and that's 3 and so we'd really need to return something like this rectangle here the elements in this rectangle right and so this is in the same way in the array here where we wanted to return to some industry kind of rectangle here and so to do that is if we had the prefix son right so we know the prefix some for or say this is um I - okay J and this is or say this is um I - okay J and this is or say this is um I - okay J and this is my plus K okay something like that yeah actually it's a I drew this a little bit wrong so let me just so it's more something like this because this would be yeah essentially it's something like this and then what we need to do is if we had if we know the sum from zero all the way to here right so we knew the sum in this entire portion right here right what we can do then is just well we could just subtract the sum in this portion which we can obtain because this is also a prefix um because it's from zero to this position right and then subtract also the sum in this portion here which we also know because it's just the prefix on for this position right and now the only problem we have is that while we actually did remove this part here twice so we will need to add it once to make up for that okay so we will need to add this part and this part also is a prefix um so that means all we need is to compute the prefix sum and we can essentially to obtain what's called this portion here that I drew the rectangle here that we are looking for what's called this may be one right so one would be equal to the this portion here the orange one which is let's call it 2 is equal to 2 which is the prefix on for the entire region up until this point right - the region up until this point right - the region up until this point right - the green one which is let's green one the green one which is let's call it 3 so minus the green one - the blue light blue one this one here - the blue light blue one this one here - the blue light blue one this one here it's called a fall so this one is three and then this one is four and then the portion in red here that will move twice this here was called five we need to add at once because we removed it twice so we need to make up for the one time that we removed it the extra one time that we removed it one more time right and so to do that we are going to add five right and so now all we need to do is compute the prefix some know what these in what these portions correspond to in terms of indices and that will be it so just to know how what these workers pull us name them right and so basically one is what is one is the sum of the region of I minus K the region that spans i minus k j- k all the way to I spans i minus k j- k all the way to I spans i minus k j- k all the way to I plus K and J plus K that's the work that's what the problem says this is what we want in answer I J's so this is what we want for an answer IJ right now what is two here so 2 is the upper so 2 is actually the prefix um so it's prefix um for IJ right one thing though that I will be doing to make industries better is prefix um for position I J's actually I plus 1 J plus 1 this is just four indices sake to not have to do a lot of if and else right now for the so that's the entire prefix sub right and then for the actually I made a mistake here so it's so this portion here that we have here this is I plus K J plus K right because that's the far left because the IJ is actually here right so this is the prefix some for I plus K of course plus one this is just for prefix some color this is sake and J plus K the other portion which is at three here this is the upper portion so it's called upper and then the upper side is just in terms of values that's just prefix sum so we are going to write everything in terms of critics um and then calculate the prefix son so that's the prefix sum for so here since this is I plus K and J plus K so it's the same column so we know that it's J plus K right so here we know that the column is J plus K and the row is I minus K right but one thing just here to make this easier for us in terms I want to keep writing I minus K and J minus K so let's just say that L 1 is going to be I minus K and G 1 is going to be J minus K and then R 2 is going to be I plus K and C 2 is going to be J plus K ok so if you say this we can rewrite this in a shorter way here right so this would be prefix some for R 2 so prefix some for our 2 plus 1 and then here prefix some for c2 right so that's the I plus K mg plus K so this is I minus K so that means that the upper here is our 1 right and then J plus K that c2 so the upper so it's a it's the same column but the smaller row so it's the row is R minus 1 right at 1 and the column is the same 1 so C 2 but since we are doing the prefix some is plus 1 here now for the fourth place that's the left portion right so the left portion is also prefix some as we said and its position is it's this position here so it's the same row which means it's the same row as 2 so it's R 2 plus 1 so R 2 plus 1 and the column though is this column here right so the same so it's that column so what is that column so that column is just C 1 right that's just J minus K so that is C 1 right that's the J minus K now the fifth one that we added twice which let's call it left upper because it's on the left upper side so that would be prefix some of what are the positions there so it's the same column as left so we know that the column is C one and it's the same row as the green portion right so it's our one and so now our formula you know the final result for the formula it's pretty much it just so it's the sum of the region so the answer for after computing the prefix M is equal to prefix sum for our 2 + 1 C 2 plus 1 plus prefix sum for our 2 + 1 C 2 plus 1 plus prefix sum for our 2 + 1 C 2 plus 1 plus the - this the green portion in the - this the green portion in the - this the green portion in the upper portion which is prefix sample for R 1 and C 2 plus 1 right - the blue R 1 and C 2 plus 1 right - the blue R 1 and C 2 plus 1 right - the blue portion the left's portion which is prefix sum of R 2 plus 1 C 1 and then plus the section that we removed twice the red section which is left upper side so it's plus prefix sum of R 1 C 1 like this and I find it always easier to write them in terms of like their direction upper left upper so that you can understand and for the indices just look at what the what each section has as the same row or column as the other ones so that you could easily write those and this is the final essentially the final formula that we have for answer now let's see how we can now the only thing that is left since we have the formula that we want can just go through the rows and columns and calculate for the answer but we need to calculate the prefix so that's also something we need to figure out it's the thing that we need to write first so compute prefix some how would we do that okay so to compute the prefixes um that shouldn't be too complicated so let's say we have a prefix I'm like let's say we have a matrix like this so I'm just going to draw it as a rectangle right and let's say we have a position let's call it I'd say here right so let's say we have this position I J and the prefix sum that we want to compute is essentially just this section right starting from the position zero right so what does that one considered in terms of the previous prefix on that we calculated right so that's what will help us compute it like because of for an array to compute the prefix sum at this position we just take the prefix sum at the position before it and just add this element right so the same thing for the matrix we will add the element here which is the element add matrix so prefix sum at I'm just going to do I plus 1 J plus 1 here as I said earlier the position here is IJ but just in the prefix um I would add an extra row just so that I don't have to compute a special case for I equal to 0 and J equal to 0 and so it would be of course first the matrix at position IJ right that's one in the case of the array we would add array I to prefix some of I minus 1 right that's what we do for an array so we'll do a similar thing for the matrix here so we will need I J but we will need to add the rest so what is the rest so the rest is first disagreeing portion here which is this here right and then the other section is this blue would like to blow here so this is what's called disagreeing 1 and then we'll say this blue light blue one is 2 so it's just the section that doesn't contain the matrix IJ itself so we would just need to add 2 sub 2 to the entire thing to get the entire thing we need to add this one to the light blue section plus the green section but there is the same problem that we had here with the red section because we here we removed it twice so we needed to add it but here we added it twice so we need to remove the trance so essentially this orange section here this portion here we added it twice we added it as part of the blue section light blue section and as part of the green section let's call it this a the ca3 so we will need to remove that once because we added it twice so we need to remove it once right and so what this would mean is that the what I'm looking for is a equal to so this prefix some that I'm looking for is just equal to the well position the matrix at IJ right plus the green section right which loss cause just the upper portion and then the light blue section was called the left section plus the - the section that we added twice which - the section that we added twice which - the section that we added twice which is the orange section so - the section is the orange section so - the section is the orange section so - the section that we added twice so again same thing let's figure these out so one is the upward section which is in terms of matrix it's just in terms of the prefix some since we can it starts from zero so it's just prefix some of the it has the same column right it has the same columns but it has a smaller row and so since this is I plus 1 J plus 1 in terms of prefix some it has a smaller row by one so we can just say it's I and then it has the same column so it's J plus 1 right now the light blue section which is the left section that's prefix some of it has the same row as the prefix M I plus 1 J plus 1 so it's I plus 1 and the come is just minus 1 as the prefix that we are looking for so it's J and then the third one which is we added twice as part of each so we need to remove it which is the left upper section so down you could see the similarities with the region calculations right except here we are going to remove it because we added twice and so here is the prefix some again where we are writing everything in terms of the previous prefix sums so it's the same row right as the green section so it's definitely I and it has the same column as the light section light blue section which is has the column J so that tells us what we need to put here so we will need to do matrix IJ plus the love plus the left the upper section which is prefix some of I and J plus one plus the left section which is the prefix some for I and J plus sorry at the prefix I plus 1 and J right and then we remove once the left upper because we added twice so it would be minus prefix some for IJ and remember these indexes are plus 1 IJ plus 1 if we had use like if you wanted to we could just have a special case I equal to 0 and J equal to 0 and at that point we could just make this predict some IJ and then this would be matrix I minus 1 J minus 1 predict some I minus 1 shape i UJ minus 1 prefix some I minus 1 J minus 1 here is just because I want to avoid having to special do special cases for I equal to 0 and J equals to 0 because I minus 1 and J minus 1 does the four zero it would which wouldn't work right yeah but we now have our formula right so now I have our formula for both prefix sum and for the region here so we could just pretty much right now write our code right ok so let's get into the code here so the function that we are going to write is called matrix block some so we have a matrix and then we have K value right and so actually since we have this okay let me just write it I'm sorry about that so I thought that maybe it's better to write don't let Calvados just write it here so we would have the rows and columns just representing the length so we have the length of the matrix and the length of the matrix at position zero and then we need to initialize prefix some right I'll do that later in the code because this is just initializing with zero both rows and columns and then now computing the prefix some that's what we are going to do here so that would be going through the rows so for I in range of rows and for J in range of rows the range of columns right and here we will just add this for this here so let's call this maybe be role be computation being us about this computation a so what we will do here is just exactly just a just be right can we change the prefix son right and then after that to compute the so it's just plug in the formula in there the exact formula right for computing the answer will initialize it in the same way with zeros right I'll do that later and then we will go the same way through rows and columns so range of rows and for J in range of columns and now the same way except here we need to compute L 1 and C 1 as we did here right as we did here except there is one thing we need to do extra thing we need to do here so L 1 is we said earlier it's I minus K and C 1 is J minus K and R 2 is I plus K and C 2 is J plus K there is just one thing we need to take care of here what if I equal to maybe equal to 2 and K of 2 4 then we would have minus 2 as an index and that's not valid so to avoid that we are going to say the max we are going to a low here is 0 so 0 and I minus K and the same thing for the column we can run into the same case so we do max of 0 and J minus K and the similar thing happens but in the other direction for the rows because maybe the rows can be only 4 values and then let's say we're at position 2 and we had a cape or so forth and that's 6 so that's out of the bounds and so we need to make sure we don't go out of the bounds here so that would mean taking the min of the last row as possible and I plus K so if it's if this is bigger and still not reach at the last position then we can still use it right and here a similar thing but for the columns so that would mean so here that would mean a men of columns minus one and the J plus K and after that we can just plug in the formula that we had here which is this a here this a formula since we have our 1 and C 1 and L 2 and C 2 and then at the end we can just return answer right and that's pretty much all there is to solving this problem so just computing the prefix sum and then computing the regions for the sum for each region for the answer and they're returning that so using these formulas here okay so now let's cut this up and see if it passes amplicor test cases okay so now let's cut this up quickly so I just I'm not going to try to everything by hand but yeah we just saw so this is the what we are over there for the rows and columns now for the prefix um it's going to be initialized with the zeros right so that would be zero for the range of rows plus one since as I said we want to index adding by one to avoid having to special treat by rho0 and column zero and so that becomes plus one here and after that we will need to go through the rows and columns and that would be just to compute the range prefix um so that would be for iron range of rows which a and range of columns so this portion here is computing the prefix son and as we said we it's for its prefix sum of I plus 1 k plus 1 this is the special handling the this we can do that because here we set sir to bureaus plus 1 into columns plus 1 so that would be matrix at that position right side position IJ plus the prefix some so the left side right so I J plus one and then the upper side could be some of you know it's easier to write prefix instead of physical sums that was just stick with prefix here so prefix of I plus 1j right and then remove this section that we added twice which is predicts I J right so that's pretty much all there is to computing the physics and now we compute the answer and that would be doing the same two follow-ups and computing R 1 and C 1 so that's I'm just going to copy it here that we did in the overview so just handling the main thing is handling the boundaries here so that we don't go over them and then after that just plug in the formula for the value at position imj which is the entire portion for the bigger position which is up 2 + 1 C 2 + bigger position which is up 2 + 1 C 2 + bigger position which is up 2 + 1 C 2 + 1 this is again just because prefix sample I J is really stored at I plus 1 J plus 1 and then we will need to remove the left and upper portions which are 2 plus 1 and C 1 and prefix some of our 1 and C 2 plus 1 and then we will need to add the section that we remove twice which was prefix of our 1 and C 1 and at the end we'll need to return and that's pretty much all there is to it ok so now what's on this okay so I also forgot to define the answer sorry it's columns here and then browse holes here and I need to close this and then I need to define answer here so this would be answer and we don't need roads plus one you just rose and I need two columns actually so comes here looks like there is a mistake so this is the matrix some IJ plus 1 and then prefix sum of I plus 1 J and minus T that with the area that we added twice here it looks good our 2 is 4 rows and n columns then the answer is for our 2 plus 1 C 2 plus 1 minus the left and the upper sections are 2 plus 1 and here it's the problem it's C 1 and R 1 C 2 plus 1 and then the upper and then the section that we removed twice for this and this is to get them right it's always better to draw it and then from there to write them up okay so there is a an index issue because I forgot here to put columns sorry okay so that passes one thing here in terms of time complexity well this is old frozen and columns also suppose the Roses N and columns is M to easily write this so this is open m and this is a similar thing of an M and so it's over an M 2 times so over all the time complexity is just over m so it's a lot easier faster than what I said initially for the brute force which would have been like to the part to the power of 2 or something similar to that o of an MK essentially it would have got with the bounds of 100 would've gotten us to maybe 10 to the power of 8 here at most it would get us to 10 to the power of 2 and 10 to the power 4 I mean so this is time complexity here in terms of space complexity we are using an extra prefix array and an answer array and those both also are open m and so yes that's the time and space complexity yeah so that's it for this problem thanks for watching and
|
Matrix Block Sum
|
matrix-block-sum
|
Given a `m x n` matrix `mat` and an integer `k`, return _a matrix_ `answer` _where each_ `answer[i][j]` _is the sum of all elements_ `mat[r][c]` _for_:
* `i - k <= r <= i + k,`
* `j - k <= c <= j + k`, and
* `(r, c)` is a valid position in the matrix.
**Example 1:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 1
**Output:** \[\[12,21,16\],\[27,45,33\],\[24,39,28\]\]
**Example 2:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 2
**Output:** \[\[45,45,45\],\[45,45,45\],\[45,45,45\]\]
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n, k <= 100`
* `1 <= mat[i][j] <= 100`
| null | null |
Medium
| null |
478 |
Hello guys welcome to the video naseeb sabko degree with this problem question read point ko iss point subscribe and subscribe the Channel Ko sabsakraib subscribe and don't see the story of the giver and debit the meaning of the center of the subscribe The Video then subscribe to the Page Hello how define random point na sir karo ki let me take this particular point so let's take this point to this Point is defined by distance from this point by road good night even better language select ship i let also decorate circle and let me no deep point a prison and this is the point element considering that define the point in Chinese you need for the distance from this region For a particular point and need another parameter theta so let's call distance from the richest industrialist club point oy give two length subah distance length and you have another parameter file this point to point in the land of the length of the there police 800 will Give The Action Coordination Time Prostitutes Take Money Plant Science Fiction Micro Units But It's Not At All And Finally Bigg Boss Subscribe Now To Off Thanks Software Thi Dhundhili Decorative Elephant Schezwan Us Just For 92.12 302 Elephant Schezwan Us Just For 92.12 302 Elephant Schezwan Us Just For 92.12 302 2nd Id For Rent In Uniform Distribution Of Love Between To to luta swelling rear in electronic function of water length belt length using the same logic in the middle of the distance from a distance between to the function of units between 21 to all problems rating point to quid proof appropriation rating points inner circle etc. Total Space With Respect To The Distance From Central Not So Let's Consider Example Subscribe Now To Receive New Updates Half And This Point To The Front Part And To The Center Of The Ear K Form No Knot At This Point To Uniform Civil Code Is Points And To This Point Length Physical Properties Joint Note Generate Ignore Enemies Generate Point To Length And You Can Operate Point At A Glance With Quality Because You Know This Point Thursday Different From This Point To The Different For Example To Think About This Is The Name Of The President Of United States And Subscribe For Point To Randomly Powder Okay That Even A Cheating The Same Distance Between The Best In This Point To How Benefits Distance Education System And Fail This Editorial On Kids From Zero 2.1 This After Please Like This Editorial On Kids From Zero 2.1 This After Please Like This Editorial On Kids From Zero 2.1 This After Please Like Share Lo That Drops Of Point To Point One Ok Which Were Distances Same But It's Smaller Dr To Generate This After You Know It Surya Doctor Generator Point To The Journey To The Self Belief And You Know Why Simple Minding You Know How To Find The During The Day of a Guru One Security and User Practice for the Area of the White and User Practice for the Area of the White and User Practice for the Area of the White 2.9 Video then subscribe to the Page if 2.9 Video then subscribe to the Page if 2.9 Video then subscribe to the Page if you liked The Video then subscribe to the Difference from a distance between two points 1720 divided into water well different from the property of birth Day To You And Your Family With Little Or No Problem Generate Who Is The Inventor C Plus And Function And This Rate Languages It Eurovision Lettuce And This Rate Languages It Eurovision Lettuce And This Rate Languages It Eurovision Lettuce In Uniform Probability Distribution Widgets Uniform Profit And Distribution Is This Producer Problem Acts And Rules For United Kingdom 021 Monday This Meaning of Distribution in Uniform Distribution System and Random Number Generator Will Give Uniform Number at and Uniform Distribution Function Will You Take Web banner-01 You Take Web banner-01 You Take Web banner-01 Question Elegant Look Android Users Can Find Rs 1000 and Wide 218 Pages Are Decorated Subscribe The Center of the Giver Points 1199 Random Number In C Plus News Youtube That 2077 During WW1 Off Say Double Friend Like Share And Make Sure To Generate Random Number 222 Between Mid-October And Parameters To Convert Fusss But What Is This Particular Random Variables In Between To Slats Naveli Phase Copy Paste Tawaif Mike So Directed That You Will Take Water Treatment Were Getting From Google Oxidant Nadodi Nritham To You Same To You Ok Channel Ko subscribe to the Page if you liked The Video then subscribe to the who was the redmi find the letter y dinner slam equal double Term And Short Circuit Se Zor Circular Central To Reach In So I Will Have To You Need To A FlashPlayer Enabled And Finally Came To The Matter Double Or A Star Kamal Vyas Ji The Students It I Hop Tight Vishudh Play Services Emergency Was Working On Yesterday Morning At the time of Ras Ready Yes Ok So Hai Suno DSSSB R15 New That Bigg Boss Has Defined Arya But Given Date Soul Exchange Limited Gallery Nationalization Ok Khoob Thanda Give Turing Back To Incident You Will Take Off But Not Accepted Thankfully The
|
Generate Random Point in a Circle
|
generate-random-point-in-a-circle
|
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle.
Implement the `Solution` class:
* `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and the position of the center `(x_center, y_center)`.
* `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array `[x, y]`.
**Example 1:**
**Input**
\[ "Solution ", "randPoint ", "randPoint ", "randPoint "\]
\[\[1.0, 0.0, 0.0\], \[\], \[\], \[\]\]
**Output**
\[null, \[-0.02493, -0.38077\], \[0.82314, 0.38945\], \[0.36572, 0.17248\]\]
**Explanation**
Solution solution = new Solution(1.0, 0.0, 0.0);
solution.randPoint(); // return \[-0.02493, -0.38077\]
solution.randPoint(); // return \[0.82314, 0.38945\]
solution.randPoint(); // return \[0.36572, 0.17248\]
**Constraints:**
* `0 < radius <= 108`
* `-107 <= x_center, y_center <= 107`
* At most `3 * 104` calls will be made to `randPoint`.
| null | null |
Medium
| null |
206 |
welcome to september sleep code challenge today's problem is reverse linked list given the head of a singly linked list reverse the list and return the reversed list so we have a linked list now normally if we had just a list we could just reverse it and return it but you can certainly output this into an array and then rebuild the list but let's try to do this in o of one space they give us a follow-up to do it either they give us a follow-up to do it either they give us a follow-up to do it either iteratively or recursively so let's start with the iterative approach what we're going to do is say that we had a linked list like very simple one the last one's going to point to none here right essentially we're going to have two pointers one pointing to the previous node and one point to the current node what we'll do is take this current node actually we'll first store the next node somewhere in some temporary place and we are going to take this current node point it to the one previous so now one is going to be pointing to none and then move our current pointer up to the temp and move the previous pointer up to the current and just continue that algorithm up until the end once we hit our current pointer is now going to be point to none so after that we can just return the previous pointer and that's going to be the new head of our reversed list so we have two pointers right we have to store the previous which is going to be none and the current which is going to be the head so while current let's first store the current pointer's next node somewhere temporarily current next we are now going to point our current on next to the previous node and we are going to move our previous node to now equal current and we are going to have our current now equaling the temp this was the next node but we stored it somewhere temporarily right once we finished this loop we can return previous because the current node will now be pointing to none and the previous one should be pointing to the new head so let's see if that works looks like it is and there we go so this is o n time complexity and o of one space now they did tell us can you do it recursively as well this problem is kind of interesting because the recursive solution is actually a little bit harder to get to than the iterative which is usually not the case but let's try to use the same idea what we're going to do is write a recursive function cursive and we're going to pass in the previous and the current same as we did before but since we're doing a recursion here what we want to return is the tail node right and that's the part that's kind of hard what we'll do is say look if not current then we want to return the previous because remember the current previous one is pointing to the one before and we are going to return here the tail with our recursion we'll say pass in current and current.next and this tail current and current.next and this tail current and current.next and this tail is going to be kind of like stored as we move it up because that's the thing we want to return so we can return to tail at the very end all we have to do now then is take our current dot next and make it equal to previous now what about you know what we did before in the iterative where we had to store that temp variable well luckily this recursion will store it in the stack so we don't actually need to worry about that so all we need to do then is return our cursion with previous being none and the head being the current so let's make sure this works here okay it looks like it's working and there we go so this is the same of n and i'm not entirely sure if this is one space because of the recursive stack i actually don't think it counts as a one this might be of n space as well so i'm not sure correct me if i'm wrong but i think the irrevocable approach is much better so this is just kind of uh for exercise okay thanks for watching my channel remember do not trust me i know nothing
|
Reverse Linked List
|
reverse-linked-list
|
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[5,4,3,2,1\]
**Example 2:**
**Input:** head = \[1,2\]
**Output:** \[2,1\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is the range `[0, 5000]`.
* `-5000 <= Node.val <= 5000`
**Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
| null |
Linked List,Recursion
|
Easy
|
92,156,234,2196,2236
|
125 |
hey everyone this is question 125 Valen palindrome valid palindrome and this is also taken from the neat code.io list also taken from the neat code.io list also taken from the neat code.io list this question is easy rather straightforward so let's just jump straight into the example the question is saying given this string s right here I'm at a planet Canal Panama is it a palindrome or not so the first thing we need to ask ourselves is what is a palindrome and a palindrome is basically a word that can be read from left to right and from right to left and it's still the same word so examples could be Anna right it could be Bob it's also race car is a classic one you can see if I spelled it from the right side here to the left side we have R oops r a c e c a r race car so the way we would think about how to determine if a word is a palindrome or not is to have two pointers the way I would go about it so we would have a left pointer that goes there and we would also have a right pointer that goes here and then we would check whether or not the two characters at the ends are the same and if they are we will just increment our left pointer by one and then we're also going to decrement our right pointer by one and then we're going to check okay these two characters they are both A's so let's continue to increment our left pointer and decrement our right pointer right now we're at the letter c these two letters are the same and we are going to continue to decrement it and at this point L and R are going to actually be in the same place they're going to be right at the same index but our with our we're going to use a while loop and we're still going to say okay that works but as soon as the right pointer index is less than the left pointer index once they pass each other right becomes to the left side and left goes to the right side then we can stop if we can make it all the way through that then we know it is a palindrome so that's one the other thing is if we take a look at this input s right we have to clean the string we have to remove the spaces we have to remove the special characters we have to make it into lowercase so when you're thinking out loud the first step is clean the string remove unnecessary space and special characters then we have to make it lowercase and that we can think of is going to be string.2 can think of is going to be string.2 can think of is going to be string.2 lower case that is a native method in JavaScript then we can just pass that into our palindrome Checker our check and check if it's a palindrome so with these three steps let's go ahead and write the function to check if it's a palindrome first so I'll just say check it takes in a string and we're going to create our left pointer which starts at zero our right pointer that starts at the length minus one now we're going to say while the left is less than or equal to the right while it's equal we're still going to do the check one more time until it's not right so while right here line 23 while this condition is true if our string that left index is the same character as the right then all we're going to do is increment that left and decrement that right counter right otherwise if they aren't the same we just return false return it right away and then right if we can make it through that loop we're going to return true it is a palindrome now we've done that now how do we clean the string well there is a method called us replace so let's go ahead and just say clean and we're just going to call it s dot replace so replace works with strings it just replaces a character or a regular expression pattern and we're going to use regex for this question now replace takes in two arguments right it takes in the regex pattern and it takes in what we want to replace that regex pattern with now that regex pattern is going to look like this well we are going to first actually yeah there we go we want to negate all of the characters here that are not a regular character so basically a space a comma so how can we capture the space the comma instead of saying let's capture the space let's capture the comma we can actually just say let's capture everything that isn't a regular character right so it that isn't a b c a to a through z uppercase and lowercase so this little carrot here represents the negation negate everything that is not that is lowercase A to Z uppercase A to Z and we need one more because if we just did this it would probably only capture this first one the first instance what we need to do is add a g flag and what that tells us is that globally in this string capture everything right so now that we have the clean we can actually go ahead and console log it and see what it gives us so if I just hit run let's see if it removes all the spaces that's going to be the wrong answer look at that our printout is basically this version but with the cases still in so let's go ahead and say two lower case right there right now it's going to give us a lowercased version right look at that now we have it and finally what do we want to put that into our palindrome check all right so let's say check clean and let's just return this and this will just return true or false and from the example here we know it's going to return true it is a palindrome let's go ahead and run it we have the output is up if the output is false why is that let's go ahead and see oh I made a mistake line 24. let's go ahead and do that again true and true let's go ahead and submit it what are we getting zero P all right so now we need to know okay what if there are digits involved right so that was an edge case that we did not contemplate if I went down okay it doesn't say Okay so we've only captured zero and we've only captured letters how do we do numbers as well conveniently we can also just do zero to nine all the numbers from zero to nine Let's ignore that so let's go ahead and submit it again all right there we go we are beating 41 of it and that's how you would do this question let's take a look at the recap we have our check which tells us whether or not it is a palindrome we go we start with a left index and a right index and we are narrowing it down the indexes until they pass each other right until that left index is greater than the right index and then we have to remember to include the 0 to 9 which is just involving all the numbers from zero to nine this is our red Jacks formula our cleaned string which replaces everything that isn't in this chunk with a no space an empty space and then we lowered case that and then we return it there you go that is all for today leave in the comments if you have any advice on my explanation preferences would really appreciate that thanks guys
|
Valid Palindrome
|
valid-palindrome
|
A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_.
**Example 1:**
**Input:** s = "A man, a plan, a canal: Panama "
**Output:** true
**Explanation:** "amanaplanacanalpanama " is a palindrome.
**Example 2:**
**Input:** s = "race a car "
**Output:** false
**Explanation:** "raceacar " is not a palindrome.
**Example 3:**
**Input:** s = " "
**Output:** true
**Explanation:** s is an empty string " " after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
**Constraints:**
* `1 <= s.length <= 2 * 105`
* `s` consists only of printable ASCII characters.
| null |
Two Pointers,String
|
Easy
|
234,680,2130,2231
|
70 |
if you're in a coding interview avoid this common mistake you might have seen this problem before it's called climbing stairs and it's commonly used to test dynamic programming you'd probably come up with this solution where you have two base cases and we build up a dynamic programming array this is called tabulation notice that this array takes linear space except if we look at this line we can see the current value only depends on the previous two values that means we can change it to constant space that's why you've got to change it to this solution where it looks almost identical but we only keep track of the previous two values with this approach the runtime is still Big O of n although it's optimized and the space goes down to Big O of one and that's what's going to get you the job
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
14 |
hello everyone and welcome to Python programming practice in this episode we are going to be covering elite code number fourteen longest common prefix this is another easy problem so shouldn't be super difficult but we'll see what we can do we're gonna start by reading the problem description here the problem asks us to write a function to find the longest common prefix string among an array of strings and then it's giving some examples here if there is no common prefix or turn an empty string there's just two quotes without anything there and here is example one the input we have three strings in a list flour flow and flight and it wants us to output FL as the result because the longest common prefix is FL and it's only that because the third letter is oo but in this one it's I so the longest common prefix here is just these two letters so that's what you're supposed to return now in example two we have words that start with different letters so obviously in that case there is no common prefix like dog and car D and G D and C are different letters so there is no common prefix there so in that case you just return the empty string and there is a note here that says all given inputs are in lowercase letters A through Z so that just simplifies things in terms of not having to do any kind of case conversions all right so let's pull over to the editor here and see that see what we're given to start with we're given an input list of strings called stirs and the expected output is a string which is the longest common prefix all right so start up with this problem we probably want to first take care of a couple of kind of corner cases or base cases sometimes you don't know exactly what kind of inputs you're gonna be given in these sorts of problems and sometimes I try to trip you up by say passing you an empty list or something or a list of length one so it's tough and good to just kind of deal with those sorts of things right away in case they're gonna throw that at you and cause their solution to fail so let's start off by handling empty lists I suppose so I'll say if the length of the strings list is zero which means it's empty there are other ways you could do this but we'll just do it with length we'll return the empty string because that means there's nothing there can't be a common substring of anything and if the length of the strings list is one I mean there's only one thing in there so I mean in theory if there's only one thing in there the hole one thing is a common substring of itself so in that case we just probably want to return the hole first element zero because Python the zero index is the first index now we actually have to figure out what to do with lists that actually have more than one string in that so basically what we need to do here is kind of take the first string we're given and then look at the one after it and see what the longest common prefix between them is save that look at the next word do the same thing and do that for every single word in the whole list and anytime the common prefix is gets shorter we'll have to update what the current prefix is and if we ever reach a point where the prefix length is zero meaning say we saw in the example dog and car start with different letters if we reach a point where there is no the first letter even isn't in common then we could just exit and return immediately the empty string so that's essentially how we can solve this problem so we're going to need to start by getting an initial prefix we can start by just using the entire first word as our starting prefix so I'll say pref that'll be our prefix our starting prefix will just be the first word in our list we're also probably gonna want to know the length or keep track of the length of the prefix that we're working with to start off with it'll just be like the length of prefix but this is something that's gonna potentially get shorter as we go through and chop down to the shortest prefix so we'll just store that so we're gonna have to do now is loop through every other word in the array everything other than the very first one which we already stored as the initial prefix and then for each one we're gonna have to check the current prefix we have and that word and then set our prefix to whatever the prefix they have in common is so as we loop through the words the prefix may get shorter and shorter as we find words where the common prefix is different so do that we're going to start looping through the rest of the string so we'll say for s which means string I suppose in our strings list but we don't need the first one so we'll say I'll start from one and then go to the end so this is looping through the input array except for the index 0 that we already stored as our initial prefix so for each of these words we now need to check whether the current prefix we have in our hand is actually in that string and if it's not we need to shorten our prefix by one and check again and if that doesn't exist in the string will keep shortening it until the prefix is in common if we can shorten it all the way to 0 if we have to shorten it all the way to 0 then there's no prefix in common and we can exit so we're looking for essentially while our prefix is not in first same number of letters in the string we're looking at we need to shorten it by one so we'll use a while loop for this we'll say while our prefix is not equal to the first same number of characters in a string we're looking at so while the prefix isn't equal to the first say zero to the length of our prefix if our prefix doesn't exist at the beginning of the word we're checking we have to shorten it so while the prefix isn't equal to that we're going to shorten the prefix by one so we'll say the prefix is equal to the prefix but we're going to cut off the last character so set it equal to the previous length but minus one so we're just basically saying we want to shorten the prefix by one by doing this and then we'll also subtract one from our length so that we update that and that should do it but we also want to break out or just return completely if we got if the length of the prefix actually hit zero so at this point we would want to say if the length is actually zero now then we just want to return empty string because that means there's no common prefixes at all that should loop through all of the words and as long as this doesn't exit with the returned empty string the final prefix were left with at the end of this loop should be the longest common prefix so at the end of this we should just be able to return that prefix that we kept shortening throughout this loop and this should be a working solution to this problem so why don't we go ahead and it's submit on that one and see what we get here thing pending pull over and see the result all right so it said run time of 28 milliseconds faster than 88% of 28 milliseconds faster than 88% of 28 milliseconds faster than 88% of other Python 3 submissions so we did manage to solve this problem successfully I hope that was helpful in getting you to think about different ways you could go about solving some Python programming problems so keep coding and I will see you again next time
|
Longest Common Prefix
|
longest-common-prefix
|
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string `" "`.
**Example 1:**
**Input:** strs = \[ "flower ", "flow ", "flight "\]
**Output:** "fl "
**Example 2:**
**Input:** strs = \[ "dog ", "racecar ", "car "\]
**Output:** " "
**Explanation:** There is no common prefix among the input strings.
**Constraints:**
* `1 <= strs.length <= 200`
* `0 <= strs[i].length <= 200`
* `strs[i]` consists of only lowercase English letters.
| null |
String
|
Easy
| null |
445 |
hey everybody this is larry this is day seven of the leeco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom add two numbers uh two you're given two not linked lists and you have to add them okay um what if you cannot modify them bliss in other words reversing the list is not allowed okay yeah i was gonna do reversing it's usually a lot easier if you're able to um but i think the annoying thing is just that it is annoying right uh this is a linked list problem and if you watch me enough you know that i don't find linked list forms that interesting it's usually just a lot of edge cases but it does come up on interviews so you know you should practice enough at least on the problem solving so that you know how to do it um yeah in this case i don't think there's anything mathematically difficult or tricky thing for me to explain it's just a lot about being careful and also just you know like taking care of the edge cases and that's what being careful means um how do i want to do this how do i want to solve this it's annoying either way um i think uh i mean and you know i'm gonna do it in a couple of past everything's gonna be linear it'll be okay but we'll do it in a couple of past where uh yeah and we'll just get the length of the things right so n is going to get length of l one m is going to get length of l two and right to the code for the length of the node so count as you go to oh if note i'm just gonna write it recursively because i'm lazy uh though it's gonna incur some space uh but that's okay and then now that we have the length of the two things now we can match them up right so then we just have to skip the min uh a little bit and i'm going to do a quick thing where if n is bigger than m we swap them and this is not that uh interesting or necessary it just makes it um it just makes it easier to kind of handle the edge cases because then now instead of the edge cases being together now we could decouple them so that you know you can handle them differently because from now on we know that n is going to be less than or equal to m right so now that this is our thing then we can kind of solve the problem slightly easier a slightly easier version of the problem don't just maybe uh nope so then now we have to figure out um the offset is equal to m times i m minus n we move yeah let's just have a helper function and you can write this a lot different ways you can write them with while loops i usually actually write them with while loops but today i'm going to write them recursively just to um just to uh kind of practice recursion a little bit because it's been a little bit um yeah so we just add two numbers we have l1 l2 and then an offset say if offset is greater than zero then add two numbers of l one dot next l2 offset um do you need to yeah we need to return the result i'm just gonna yeah i'm gonna be lazy i'm just gonna return the results in l1 say and maybe that'll be okay um yeah so l1 is a smaller one so we'll so we got it mixed up or i got it mixed up speaking for ourselves because uh because l2 is the longer one right because we after our precondition so yeah i don't know why my voice is a little bit weird today uh maybe i just didn't sleep that well but yeah so now we offset by one so yeah also return and now we now that the offset is diff the same then we can just add l2 dot value plus or equal to l1 dot value right well but first let's add two numbers of one next l to the next offset right and why do we wanna do that and of course we should check that out if l one is none or l two is none uh return add two numbers as you go to this so then we so now we want to do it the way that i'm going to do it is going to do it backwards by using recursion because then now we have this thing and we add them together and then now we go and so basically what i'm doing here now is for example we add the three and the four first and then the four to the sixth second recursively um and so that now we could tell that this is a 10 and then carry to the carry so that's basically my idea um and then so carry is equal to l2 dot right is equal to zero if l2 dot next is not none and l2 that value is greater than or equal to 10 l to that value subtract 10 carry is equal to one we carry the one right so now we just have to add l2 and offset and that should be okay except for the case where we have uh the carry bit on the in the beginning so yeah so we're gonna have to take care of it but i'm gonna just test this right now just to make sure that uh you know it's almost like tdd and that if i test it now i could you know see if it's correct and if it's not correct then i could debug what i have now versus if i keep on adding new functions and stuff like that and when things goes wrong there's a lot of places to look right uh and besides the only thing that we don't do right now is just carry the one in the beginning so we should be able to do that we check very quickly hopefully yeah okay so we definitely uh messed up something over here oh whoops this is the next dot value of course see now i don't have to worry about uh you know other things okay hmm oh what why did i do that i mean that was just a brain fought typo okay so this looks good this doesn't look good but it like we said right i know that this wasn't going to be good for this case that's why i put it in there i just kind of put it in there to remind me but also knowing that uh but this is what i would have expected if that was the case um but yeah let me actually add a couple more first though some basic things also making sure that they're symmetric it should be because we is a very trivial check but you never know so that's why i want to check that uh yeah okay mr hmm that's interesting because we definitely the carry definitely happens here on the first problem and the second well this one doesn't do anything i'm not sure why this doesn't get carried forward oh no this is right i mean this is expected it's just that um i mean the code is doing what i told it to do but it's not a hundred percent yet and that is that um because of the offset we don't look at the nodes if it's not an offset so actually we have to uh add some code here as well all right so now that the offset is zero um let's check again maybe we should we could dry ourselves a little bit but for now let's focus on getting it right so this is carry it's just l2 dot you has one right cool uh so this is now what we expect a little bit better and then at the very end we can just check if l2 that value is greater than 010 and again yes some of this is a little bit hacky to be honest um but new head as you go to what's it called list note of one new head time next as you go to l2 return your head all right i mean this is a little bit hacky we could definitely figure a way to clean it up but now you can kind of see how i break it down different pieces and do it one at a time uh and that said these things and that's why i find it annoying is that you never know um or not you never know but i feel like i'm never confident about it however and yeah i mean this looks okay so i'm gonna submit but you like i wouldn't be surprised if i get a wrong answer but okay that's good um yeah so what is the running time complexity so the running time is going to be o n because we look at each node once or twice or something like that um but the space compact is going to be of n because we essentially use the stack as uh as we use the chord stack as an implicit stack to kind of put push things on top uh so linear time linear space uh it's a little bit messy we can definitely try things up here uh we could figure it out how to do that at some point but yeah and there are ways to do it but i'm not gonna do that here you can up solve it at home if you like uh let me know what you think let me know how you did let me know if you like these linkless forms i surely don't be okay but uh but yeah i will see y'all tomorrow bye
|
Add Two Numbers II
|
add-two-numbers-ii
|
You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
**Example 1:**
**Input:** l1 = \[7,2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,8,0,7\]
**Example 2:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[8,0,7\]
**Example 3:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
**Follow up:** Could you solve it without reversing the input lists?
| null |
Linked List,Math,Stack
|
Medium
|
2,1774
|
1,696 |
hello so in this video i am going to explain the lithgow daily challenge of 9 7 2022. the question is jumpcamp six way in this question they give us zero indexed array nums and it is a k if you are initially standing at the index 0 in one move you can jump but 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 from i plus 1 to minimum of n minus 1 or i plus k okay inclusively so you want to reach the last index of r a and your score is number of sum of all num j you visited okay so you want to get the maximum score by jumping to reach the last index for example you are initially starting at this position now you're going to jump into the first cell and from first cell you can jump to the next two cells okay you are designed to jump to the third index sorry fourth index the third index so from third index you're going to jump into the fifth index okay so in this part you scored maximum of seven points okay your sum score is seven okay this is the maximum of this uh array it is the maximum way to reach the last point the same way also in this example you are standing at this position so the score is still and next you're going to jump into the fourth index because you can up to jump free cells okay we jump next to this cell with value 4 so now the score is 10 plus 4 14 and next you're going to jump into this okay this is 3 so total sum is 17 so this is the maximum answer so this is the question we want to find the maximum value by jumping into uh by jumping into cells to reach the last cell okay in this problem we can start using uh dynamic programming easily okay you can say you may start many different many type of question this many this type of questions so but there is a twist in that okay i will explain the algorithm section okay now move on to the algorithm part okay now i take the example which is given the question okay now the input array is this is okay the first minus one a one minus two 4 minus 7 3 okay now i'm currently standing at this index okay i'm currently standing at this index now uh to reach this indexes i can only go so i'm directly present is that so like a maximum score i can get this one because i'm currently standing on this point next to reach the second in the first index i can came from a zeroth index okay so this is one of the possibilities uh so maximum score i can get is one okay one plus minus one so this is the one only one way to reach this first index okay so maximum score is zero okay now i am currently in the person in the second index okay to come into second index may i can come from zeroth index our first index so this is the two only two possible ways okay whether may i come from zero to two or one to two so now i want to choose the answer greedy because i want the maximum score so the maximum value is in this two point is this okay so one is the maximum value so one plus my current cell value is minus two so one plus minus two it gives us minus one okay minus one is the maximum value i can get to reach the second cell now i want to third index okay intercell to reach this cell may i can come from this first cell or this second cell where only two possible ways because my window size is two only i cannot jump ah max your two so now i want to choose again greedily so which is a maximum only zero okay zero plus four is four so maximum value to reach the third cell is four again i move on to the fourth sun to reach the fourth cell may i can come from first cell or third cell so which is a maximum one in this for two points so four is a maximum one okay so my maximum one is four so four my uh four plus minus seven is minus three again i move on now to reach the fifth sub maybe i can come from third cell or fourth okay which is the maximum value the third cell which is value is four so now update the fifth cell value so four plus three is seven so the maximum score i can get to reach the fifth cell is seven okay so now we have a question so the problem can be easily solved using this way but we want to find the maximum of the window size okay for example to use this uh to reach this cell i want to find a maximum of this window values and also to reach this cell i also want the maximum of this window six to reach this cell i want to maximum of this window okay how am i going to find this value maximum very less time so this can be solved using mono queue so maybe you are of the monocult if you're not i don't worry i will explain that okay now how we can solve this problem uh problem in using mono queue let me explain okay let's say it is all okay now i am going to solve this using dq so to this first again i am going to start from the zeroth index so i am currently at the present at the zeroth index so this value is one okay now i'm going to update this dq because now dt is empty i'm going to update this uh zeroth index okay now i move on to again move on to next index so to reach this first index i may come from zeroth index okay instead of checking directly in dp i'm going to check this in dq okay i can come from this index because dq always store the this mono q always store them maximum well maximum value i can to reach the first way to this index okay so this is working to store the maximum value uh to reach the index okay so i've like if you move further you cannot understand okay now i reach the first index with value one okay one plus minus one is zero again i'm going to push that into now i go before pushing into q i'm going to check condition okay whether the last element i inserted into the dq is okay inserted element last element present in the dq is smaller than the current element are not okay the current element is zero you can see the last element which is the dq is the zeroth index by 12 is one i want to check whether it is greater or not so it is greater so i will do nothing i just inserted this syntax into dq and back okay you can see the front of the degree is the maximum value to the okay this is the maximum value you can see this is the main concept of the monocule now i move on to next index okay now i am currently moving in a second so to reach the secondary i can come from zero around so to choose our maximally i going to check within dq so which is present in the dq first so zero is present in the dq first so this is a so i can now i can know this is the only way to reach the second it is maximum value so i can come from zero index so this value is one so one plus minus two is minus 1 okay now i'm going to again going to check with uh dq i'm going to i want to update the dq so if you see the dequeues current value is minus 1 but dq front this first index which is value of 0 so which is greater than so 0 is greater so it is smaller okay i so i going to do nothing i'm going to show it is your condition space so i don't want to so i just added this index in the last objective okay now two is added to the entire queue okay again i move on to third index so before moving to third index i can see the window size is reached okay because this is the two size window okay now the window size is more okay we move more than so i want to remove the zeroth index from the window so you can see so before removing this zeroth index i want to check whether it is the current max of not okay i'm going to check the dq dot friend it is like a so it is the current max so i want to remove that okay so if i uh so i'm going to remove the dq value okay so i'm going to remove that okay because the window is more okay to reach this level may i can only come from one or two so if i choose the zeroth index so it is not the optimal one so this is not a correct one so now i'm going to so now i want to reach the third uh third index so i want to check again dq dot print so which is the first index so which is value is 0 so this is the only one which is have maximum value so 0 plus 4 is 4 okay i again i'm going to update this so before updating i want to check that whether it can be so in third index the value is four again i'm going to say checking dq dot back so in back there is the second add x y which is minus one so which is smaller than the current value so indeed i'm going to delete this okay i'm going to delete this value again i'm going to check with the dq dot back it's okay in back there is again one so in one first index there is value zero so which is also smaller than this so it is also not optimal to further results okay again so for this car i again i will delete this now this q become empty now i going to insert this third index into the cube okay now by going to fourth index to reach the fourth index now again before we move into for two reason for the next i can come from two r3 okay this is the two possible ways okay so now i'm going to check again dq the dq is uh so before checking the dq i'm going to check whether the uh dq dot front is less than this second attack because we cannot reach the second before from one cell to four which is not possible so again try to check this whether the particular trend is less than the window size okay it is not because this is just third index so now i'm going to update this fourth value so the if only we can come from come to this service third index so 4 plus minus 7 would be minus 3 okay again i'm going to update this dq okay now i'm going to update the fourth index again i'm going to check in the dq so dq value is 4 the d2 is 3 so which is 4 which is greater than this so i'm going to now do nothing i just add the push the current index into the last of the queue okay four again moving to fifth index so to reach the fifth index i going to push the from the front so three plus five so in third index the value is four so four plus three is seven okay so again i'm going to check to remove that uh so seven is my current maximum so i'm going to check the fourth index is my like a less than this so again i'm going to remove this from the dq again i need to check this uh third of thirdness and start into the value is four so it is also less than that so again i'm going to remove that so now we cube become empty so i'm going to push this index to dq so now the max so we reached the final cell so it's the solution to our problem so this is the maximum value i can be i can get by jumping into the last cell okay so this is the concept hope you can understand that if you did not understand please try to write and pronounce the note and paper note and pin okay you can clearly understand the concept okay now move on to the problem uh move on to the uh code okay i so initially i found uh declared that dq double entered queue so now uh what i explained with the algorithm it's the same way i'm going to sorry trade from the first zero index to last index okay if the dq is empty just i will instead of dp i going to directly store the value in the given array because it will reduce the space but you can also use the extra space to db but it's not necessary because we don't going to reuse the nums value again so i directly store the dp value into the nums okay if the leak is empty i just literally 0 because in first index you can see uh in first index are something sometimes the dt becomes zero so that time there is no previous cell so it is zero uh if it is not um i'm going to add the i had the dp had the value which is the present in the digital trend okay i'm going to add the dedicated front value but after that i'm going to check that i want to update the monocule okay it monitors the if the queue is now while the dq is not empty and the current value is better than the molecule last value so i will remove that from the mono queue until the current value is greater than the la monica's last value because it is the only way to you can update the so it is the basic structure of the monocule you can uh read more about molecule internet okay after that i going to push the current element to the last of the queue okay if the last if the first element is uh less than our window size which is when degree difference is less than or equal to i minus k which means this is not going to uh that cell must not be should not be present in the our answer so we're going to remove that finally we return the nums.back value last value present in nums.back value last value present in nums.back value last value present in the numbers okay let's submit this problem submit this solution okay it's accepted okay the time complexities we can see the we it is only one time again everybody you can see there is another loop within that but it's not so it's just it visit the elements only once again this loop also we see the only elements only once so it is just two interior so it's the time complexity could be order of n and the space complexity is also order of n because we use the double entered q okay hope you enjoyed this session if you have any doubt please kindly ask in the comment section so let me see in the next video thank you
|
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
|
57 |
this is the 57th leco Challenge and it is called insert interval you are given an array of non-overlapping intervals an array of non-overlapping intervals an array of non-overlapping intervals called intervals where intervals I equals start I and I represent the start and the end of the IELTS interval in intervals is sorted in ascending order by stardo you're also given an interval new interval equals start end that represents the start and end of another interval insert new interval into intervals such as intervals is still sorted in ascending order by start I and intervals is still does not have any overlapping intervals merge overlapping intervals if necessary return intervals after the insertion so if you have 1 3 6 9 then input is 2 5 that fits into this one so it goes one five and six nine and we have one two three five six seven eight ten twelve sixteen and the interval is 4 8 that fits in this one and this one so guys one three then three 10 12 16. all right let's get started so I guess we'll start off again with creating a list like this so then we can quickly add them in and return output dot to list or to array so what we'll do is for uh into I equals zero I is less than intervals dot length I plus actually what we'll also do is bull uh found so what we'll do is if intervals I zero is less than new interval zero and intervals I actually we could just do it like that intervals I want is less than new interval zero I'll put the ads intervals I then we will do else if so we don't need found we can just do it here else if intervals I zero is greater than new interval one so we'll just add this into here don't need to have a second statement so I think these are the only situations we need to look for so if pray for these are false so that means interval actually does this mean it's all good so if interval one is less than new interval actually I just want to run that just to make sure the condition is correct okay so output for the first one six and nine that's correct because this fits into this one and then if you go to the next one yep so it has one two and twelve six which this 4 8 doesn't fit into and it fits into these three okay so we have this working correctly so what we'll do int Lo equals negative one actually we shouldn't do negative ones low we'll just see int Max int High equals min sorry if this is false actually I just noticed I will have to do second if statement because there is a if the new interval doesn't fit into any of them we then need to add it in here so if it's greater than we do if not added equals true then we'll have to see if load is less than intermix value we then output dot add new int below higher otherwise I'll put a add new interval okay so let's get getting a bit of a bit ahead of ourselves so back to here what we need to do is low equals math dot min um actually if low equals into max and slow equals math min terval zero or intervals I zero else this but actually we don't need to do anything else because it'll only be done once but what we need to do is for actually with this it can just be like equals intervals I because the new interval will either be equal to that or higher than it although we will just do it as low equals into max value what we're going to do here is high equals math.max equals math.max equals math.max this will be the new interval one like that okay so let's run this and we can see it worked here but not here that's probably because I forgot to do continue here and then also here so now that should work and it did we can see 310 there then one five here okay so let's copy this code put into leak code and that is all good so now let's submit okay so we didn't consider if intervals was empty which didn't know was possible so I guess we can do a new interval dot length it's less than two or use this test we will add that into here run this oh actually that's the other way around so we can do if intervals.length intervals.length intervals.length is equal to zero return new int Ray new interval like that so go back to here we'll remove this and we will put that back at the top so run on the test one there we go that return the expected output so Nelson it Okay so we've got a wrong answer it outputted nothing when it should have returned one to five hmm Okay so it did all this but then it just didn't go back to the top to actually add it so I guess if I plus one equals interval's length we will add this in so add that to the bottom here use test case run that now it works sorry hopefully that's all that's had to be changed nope not the wrong one okay so that makes sense need to change it so actually we will do this if one plus if I plus one equals length and not added and that's when we add interval tool so we'll add that part to here use test to run on that now that one's accepted so hopefully that was the last one and it wasn't okay why okay yeah I assumed that the new interval would always be lower but that's definitely not correct so low equals math dot min new interval zero so we'll copy that add that to here now surely that is the only thing that we need to test for now so run the test once that's accepted and submit there we go we finally got our solution accepted so that's the 57th leeco challenge cool insert interval if you like this video make sure to like And subscribe
|
Insert Interval
|
insert-interval
|
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.
Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return `intervals` _after the insertion_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\]
**Output:** \[\[1,5\],\[6,9\]\]
**Example 2:**
**Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\]
**Output:** \[\[1,2\],\[3,10\],\[12,16\]\]
**Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\].
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 105`
* `intervals` is sorted by `starti` in **ascending** order.
* `newInterval.length == 2`
* `0 <= start <= end <= 105`
| null |
Array
|
Medium
|
56,715
|
1,604 |
hello welcome to today's video we'll be looking at lead code problem number 1604 alert using same key card three or more times in a one hour period in this problem we are told that each time a worker uses their key card a security system saves their name and the time it was used and the system will emit an alert if any worker uses their card three or more times in a one hour period we're given a list of names and a list of times where each index corresponds to a name and when they accessed the building and we want to know how many workers access the building three or more times within a one-hour three or more times within a one-hour three or more times within a one-hour period we're also told that the times are given in a 24-hour time are given in a 24-hour time are given in a 24-hour time format with the hours coming first followed by a colon and then the minutes represented as a string and then the final thing to note is that we will not be looking at a 24-hour time period 24-hour time period 24-hour time period where it overlaps so what that means is if we are at 23 hours and 51 minutes and then zero hours and two minutes that would not count as part of the same hour because that would be part of a different day let's look at what this problem means in this example i have six entries i have three entries for person b and three entries for person a if you notice that b checked in at nine o'clock nine thirty and ten o'clock this means that over these three entries there were three times they entered the building within a one hour time period nine o'clock to ten o'clock is and then 9 30 that all takes place in one hour but if you look at person a they entered the building at 11 o'clock 12 o'clock and 13 o'clock these entries did not take place over the course of one hour so they did not emit any alerts there was an alert sent out for person b because they entered the building three times within one hour which means our result the thing we returned to the calling function would just be a list containing the element b now wouldn't it be really nice if there was a data structure that would map names to the a list of times that they entered the building so it looks something like this if i knew all the times at which a entered so say 11 12 and 13 and if i had to sorted this would make this even nicer like it is now and then b enters at 9 30 and 10. i know this is an abbreviated list but this makes my life a lot easier because then i can just look at every particular key in my map if my keys are here and they map to a list of time like this then this problem becomes a lot easier i can just look through every element in the key section and then figure out if they set off an alert if they did set off an alert i'll add them to my result now if you find yourself saying wow there would be that would be sweet if i had a data structure that did that or it would be really nice if the input was like that well you can just make the data structure yourself and transform the input so that's what we'll do in this problem what we'll do is we'll take these names and then we'll map them to times then we'll look to see if there's an overlap to see if there's three consecutive times within an hour period and if there is we'll add that to our result and if there's not then that person didn't set off an alarm and it's okay really the hardest part of the problem i think then becomes how do you know if somebody set off an alert so if i'm looking at b with 0 9 30 and 10 o'clock i know that these three times happen in a one-hour period a one-hour period a one-hour period by the following i really don't need to look at the middle time so i'm going to cross it out because if these times are by sorted input i have a i can choose a starting position and an ending position and if these two times are within one hour then i know any time in between is also within an hour what i'm going to end up doing then is if there was more times here like 11 and 12 etc what i'm going to do is i'm going to look at two particular times say like this nine here and this ten i'm going to see if there's a one-hour i'm going to see if there's a one-hour i'm going to see if there's a one-hour overlap there if not then i'm going to look at the next two i would look at 9 30 and 11 see if there's a one hour overlap and then i just continue until i can no longer compare times there's two cases to consider when you're looking at these times to know if they appeared within the same hour the first case here is when the hours are the same what we're really looking at is the hour value if i have a and b down here remember when i'm comparing three times to know if i have three within the same hour i can ignore the middle value if a and b have the same hour in this case 10 then they definitely appear within the same hour all three of these must be within a one hour time period the second case is when the hours are different remember i can ignore the middle value here so i'm really comparing 14 30 to 15 20. if i can add one to a my a is going to be 14 30 b is going to be 15 20. if a plus 1 equals b for the hour and a's minutes are bigger or equal to b's minutes this is for the hour and this was for the minutes down here then i know there's an overlap let's see how this looks in the code i'm going to take more of an object oriented approach at this problem i'm going to make a time class to represent the times i'm doing this because we're currently given the time as a string and that's really hard to read it's really hard to parse the hours and the minutes so what i'm going to do is create a time class to represent that it'll have an hour and it will have a minute the constructor will take in a string if i can spell it and what i'm going to do is i'm going to split the string on a colon and i'm doing that because i know that every time is going to have the hours then a colon and then the minutes like this now i know that the hours are going to be whatever the first item is in the tokens array and i'm going to be converting this to an integer like that and then same with the minute i'm just going to convert whatever the minutes are into an integer so they're easier to use later on i'm also going to create a compare method i'm going to create if i'm given another time object i want to know if this other time is within one hour of the current time i have so if the other time is within one hour of the current one i have i will return true this is pretty easy to do if they have the same hours then i know they are within one hour of each other but if they're not then i want to know if i add 1 to my current hour does it equal the next hour it's going to need to do that and the minutes my current minutes are going to have to be greater than or equal to the other minutes this example would be like if your current time is 10 30 and the next time is 11 20 10 plus 1 right here would give you the 11 and the 30 is greater than the 20 which means that 10 30 and 11 20 are within one hour of each other now let's go to the actual code now that we have our time class to play with a little bit i always like declaring my return variable at the top just so i don't forget and then as soon as i do that i like to remember to return it at the end now i'm going to need a data structure to map names to all the times at which that name clocked in i'm going to call this times and we're going to make it a new hash map it's going to be a map from names to a list of all the times at which that name checked in this is what the first step is it's creating your data structure the next step is populating the data structure and we're going to do that just by using a for loop key name and key time have the same number of elements so i could have done keytime.length but i could have done keytime.length but i could have done keytime.length but i just did keyname because keyname is the first parameter doesn't really matter though i'm going to grab the name from key name at index i and i'm going to grab the time from key time at that same index i'm going to do a quick check if i don't already have this name if i haven't seen this name before i want to add a new arraylist to that key just an empty arraylist times.put times.put times.put name and we'll make just a new arraylist like this and the reason i'm doing this is because at the end here what i want to do is i want to get that name and then just add on to the existing arraylist a new time on what the current time is if for some reason that name didn't exist i would get a null pointer exception here so this if statement helps prevent that from happening now i have my map populated with everyone's name to a list of all the times at which they appear one subtle thing is that the times might have not been in a sorted order what i'm going to want to do is make sure that as i'm doing the computation here what i want to do is make sure that the list of times is sorted before i run through the computation i'm going to iterate through everything in my map i'm going to do the map dot entry make this a little cleaner and we're going to do of times dot entry set i'm going to grab the list real quick and then i want to sort it i could make a compare function on the time class um i decided not to though just for brevity's sake but it looks something like this if ada hour is less than b dot hour we return negative one that means a comes before b otherwise if a's hour comes after b's hour we know b comes first otherwise they have the same hour and i just want to compare their minutes what this does is it converts all of the times for a particular entry in sorted order from smallest to largest and now if i should alert on that list i'm going to create that method later on but it just kind of makes sense to write it before i have it then i want to add that name to my result.add and then i'll get the key result.add and then i'll get the key result.add and then i'll get the key remember the key represents the name of the person that has the alert what i'm going to do real quick now is write that should alert public boolean should alert this takes a list of times and what we do is we look at one time and then we look at two times ahead of it and see if they're within the same hour and we're going to continue doing that through the whole array so from i equals 0 to time dot size i'm actually going to call this times because it's a list of multiple elements and i'm going to subtract 2 because i'm looking too ahead so i'm going to say time a equals times dot get whatever index i'm at and time b equals well just two ahead of me and if what was that method i had called it was called with i wanted to call this within one hour if b is within one hour of a i'll just return true if i never return true from the for loop then i will return false and that means there was no overlap and that user should not be alerted finally the last thing i want to do is return the list sorted without however many names i have in my result i want to make sure that they come in alphabetical order it's pretty easy to do i just call collections.sort let's see if everything collections.sort let's see if everything collections.sort let's see if everything compiles okay yep and it looks like we got the expected answer here and if i submit the problem yeah we got a successful run here if i look at the runtime complexity let's do that real quick key name and key time have the same length we'll call that length n i iterate through that one time so this is an o of n operation here however in the worst case scenario i have one name only in my list with all the times associated to that one name which means if i sort this list i'm sorting n items which is an end login operation should alert is also an o ofn operation but that's only being called once per name inside of the array and then finally we're doing another potential n log n operation here so the time complexity is o of n log n because we're doing all that sorting let's look at the space real quick i'm creating a list for the result here and i'm mapping also creating a map and then another list here but these are all of n spaces i'm not doing any squared or n log n spaces so that means the space complexity is just o of n for the time let me fix this big o of n for the space if you have any questions about this problem please let me know or if you have any video suggestions please let me know in the comments and i'd be happy to take a look at it thank you
|
Alert Using Same Key-Card Three or More Times in a One Hour Period
|
least-number-of-unique-integers-after-k-removals
|
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period.
You are given a list of strings `keyName` and `keyTime` where `[keyName[i], keyTime[i]]` corresponds to a person's name and the time when their key-card was used **in a** **single day**.
Access times are given in the **24-hour time format "HH:MM "**, such as `"23:51 "` and `"09:49 "`.
Return a _list of unique worker names who received an alert for frequent keycard use_. Sort the names in **ascending order alphabetically**.
Notice that `"10:00 "` - `"11:00 "` is considered to be within a one-hour period, while `"22:51 "` - `"23:52 "` is not considered to be within a one-hour period.
**Example 1:**
**Input:** keyName = \[ "daniel ", "daniel ", "daniel ", "luis ", "luis ", "luis ", "luis "\], keyTime = \[ "10:00 ", "10:40 ", "11:00 ", "09:00 ", "11:00 ", "13:00 ", "15:00 "\]
**Output:** \[ "daniel "\]
**Explanation:** "daniel " used the keycard 3 times in a one-hour period ( "10:00 ", "10:40 ", "11:00 ").
**Example 2:**
**Input:** keyName = \[ "alice ", "alice ", "alice ", "bob ", "bob ", "bob ", "bob "\], keyTime = \[ "12:01 ", "12:00 ", "18:00 ", "21:00 ", "21:20 ", "21:30 ", "23:00 "\]
**Output:** \[ "bob "\]
**Explanation:** "bob " used the keycard 3 times in a one-hour period ( "21:00 ", "21:20 ", "21:30 ").
**Constraints:**
* `1 <= keyName.length, keyTime.length <= 105`
* `keyName.length == keyTime.length`
* `keyTime[i]` is in the format **"HH:MM "**.
* `[keyName[i], keyTime[i]]` is **unique**.
* `1 <= keyName[i].length <= 10`
* `keyName[i] contains only lowercase English letters.`
|
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
|
Array,Hash Table,Greedy,Sorting,Counting
|
Medium
| null |
42 |
Which improves the interest in the liquor shops and the working committee's consumption. Are there traffic problems in these areas and is a very common problem. I have worshiped this many times but a very good collection is mandatory. That is our agro processing, preprocessing and in you. You must have understood that while processing, we looked at the quality, we were looking at the names of less buy and sell staff, then we once thought of a way, behind the preprocessing and similarly, Bhim must be doing something here. They used to think that the problem is caste, that is the typing problem in it. It happens that you should be kept from multiple buildings where box say anything about their height then if you are ok then from different inactive heart her husband is 58 height here is two height here flight is zero height front Aishwarya After removing it from the block and these are standing one after the other standing on the ground all standing above in full detail and you pour water from above then it is raining inverter pour water from above okay so railway contra voucher here When the rain will end, there will be three cups of water. Kunjanamon Meeran, I have to tell you how much water will be accumulated here. Ticket, how much rain water is getting spoiled here, then the name of the inverter tree will be counted from here. More than people, this much water will be accumulated here. Tight in the area, two soldiers outside this, water will spread from here, we will place it on top of this, some water will be collected on top here, two water will spread, water will always be collected wherever there is space, okay here water on one box for one plot. Here also there is water and water, yes, everything will get trapped, if there is any water here, then I have taken so much water that I have forgiven the red, so tell me how much water you will get in the electricity box or if you go, it will also tell you the answer like. There are 123 boxes here, the time and how much is this deposit, 1234 out of 500, ours comes to 25, at total our 8 units of trap water and will be received, so how would you like to tell us, okay, so this is a quite unique problem, this is quite an interesting problem, keep solving it. Play Sheela, I have opened it that the problem will be found here, meaning you will have to select a hair apart from this for free and follow it and you will have to do it. Okay, so this is very deep, if you do Aishwarya Rai, then move ahead. You must have thought, then first of all, where is water possible here? Okay, if we come and see on any of these dresses, water will accumulate on the tracks only if the one before it and after that there is suicide water higher than some box. It is possible that water can be stored at this place, why can't water be stored here because before this there is no block bigger than this, after this there is this one but from the box, before this there is some broking, this is some height, this is some building, if this is big then on this index. There is no harm in water, you can try everything, just like why is water necessary here because before this, somewhere in life, there will be a building taller than this one and on the right side of it, there will be a building taller than this. Water is accumulating here, if you go anywhere else, the water is going to circulate here, neither on the left nor on the left, there are bigger buildings than this, there is definitely water here, there is traffic, there is a bigger building than this, but there is no bigger building in the night. Apple is a building, here also water is a decline in youth, is it a building, so let me tell you one thing that if we try to find out where water is being born, then those children will see that it is not just left, it is not just Lakshmi, there is no building bigger than this. Is it not and there must be some big person in its entire right, so this behavior is to find out how much water is happening and for how much time, then he can't find out when he was switched off, then you won here and there. How will I mix each element, I am taking each element, which is the bigger building on the left, okay then I will do it on July 15, oh wow man, it is okay, I will hit these on the left, tell me by which I will hit this on the left with any neck on that on the left. Which is the biggest maximum site, okay or marginal, so before this, any big thing, before this is its hi-tech free guests place, you this is its hi-tech free guests place, you this is its hi-tech free guests place, you wear this, Laxman had done it in both of these and make something big, there is one before this too and one Building, its height, additional effect, take place three here and from two and three, there was a building of height even before this, now we will read here completely, kevda to dahi vada, here it is in 1404 or bada to for means before this. There is a building whose height is full battery saver off or bigger then 4G big share for gift big and to perform is also four if it increases then we have made this bloody winner this gatherer will make that set because we have to do it from both the sides Finally Garima, I will give it in the name of Ali, I will start rifling it, there is no problem that who is the biggest here on this side, the biggest one is this two, so this Gattu Battu and films should be increased by ithari and CO2. The mole is the biggest on the right side, whose mole is the second biggest, then this mole will come here now, which one is bigger than 114, so now there is a thing in it, then it is not a ride, it is a building, whose height is free, okay, now here it is zero and is facing the chest. The second one is bigger so basically whatever value is there on the green next side, it was telling that on the right side it has the name of English saree like, so on this right side the height is the highest, why is it the gram flour, which one is the one which has increased from which Bhringraj and the maximum is now here. But let's come immediately, how is Jio 4G bigger than films? Later, two and for, big blood, clean and bad, game for Devnagari and more, ticket tumne two yaar, here left and right, this is different like this, okay, give us extra. And celebrated oven special is being used here okay so we have made this now our job is to tell by going to the link how much water can get spoiled here so here we will put a normal and we thought so it will be that any Express means any question. Now do we laugh at this? Left Mughalsarai, which is the maximum height of the building, the smallest of them can be washed with the same amount of water. How is this you are here at this place and here see the fight back in this loot. Height in hypnotized reel and right, that f4 is fine, this is a mud building and this building for wally which is on the rent side, these two will be small, water, coriander leaves, this question is tight, 14% is small, three is small, so only this much 14% is small, three is small, so only this much 14% is small, three is small, so only this much can be punjab, I am ignorant. Ca n't collect feet of water or it will be full water, 1.5 will go from here, okay after washing water from here, it 1.5 will go from here, okay after washing water from here, it 1.5 will go from here, okay after washing water from here, it is 14% and for 15 minutes it will tell in is 14% and for 15 minutes it will tell in is 14% and for 15 minutes it will tell in 14th - is free, this much water, just go down but 14th - is free, this much water, just go down but 14th - is free, this much water, just go down but in the building below, this bill is fine that So, there is so much water, it is a building, there will not be as much water as the height of the building, so what we have got is, hold whichever is smaller on the right and left and from that, the height of the building is given to the giver. - But it will height of the building is given to the giver. - But it will height of the building is given to the giver. - But it will tell us how much water, how much block and how much unified is being stored in any net pack, so for basically what is made of gram fennel, then if we look at the formula, what is the amount of any next husband on any ditch, that is wap. .in what is the amount of any next husband on any ditch, that is wap. .in what is the amount of any next husband on any ditch, that is wap. .in team's minimum of left and right pen drive traffic - and right pen drive traffic - and right pen drive traffic - say the height of the left side, then the form is being made for any index eye that whatever is the minimum of left and right side, take it and from that - say of this building. Height of Paani Maa - say of this building. Height of Paani Maa - say of this building. Height of Paani Maa Jayega, as you see, Saunf is 11 smaller in size than Sanjay, so she was coming for this and Chhota is also smaller than 483 other films, 393 miles will do the second incident, so it means this Paani is youth of Rathi. The water is clean, water is getting accumulated here, it is zero, it is okay, there are animals here, zero, they come here for free, which one is small, three is small, it is okay, where is the height - 57, so the treatment for height - 57, so the treatment for height - 57, so the treatment for witches has studied at this place, two, if you see this, then from the east. Only a small head is small, sir, maybe 2392, from this lineage, there is water once more, Dhruv and Lok Nirman is for them, the whole is small, 410, here this 14th of zero may be small, take 3103, so there is 350 water accumulated here, see one. Block 2 block lion cursed how much platinum and if there is then small person from for free 3 - 122 small person from for free 3 - 122 small person from for free 3 - 122 here kumkum and one this absolutely stop here let's see protein vitamin soft 1042 vitamin rich small 2920 so if you enter pin number then five from proposal Plus one 6 plus 208 that here our next 1 glass of water is getting accumulated here so it is very simple to show you the code is going to be very simple so I fold it after this you must have heard from people by the way People who are very simple will have one right against two American rappers and after that we have been able to achieve it for both of them. If this seems like a trap, then you people who are afraid of being very simple can also try it. If anything, then I have recorded a much bigger code than this. This is a good teacher's place on the left. I have written the silencer here after Korea. I have written the same logic here after everyday life. I have written the same logic here. I am getting it in the first career. This is what you have to do for hydration, basically the box is this, which is its length, so this is I have one left and one night witch, both of them with sampling, we replaced the left 080, okay, which is the first portion, the one with apps. We accepted that as the average and in this way I refilled the left one, then the left eye basically got contacted with any postal ballot, tell me the left join thumb is just and the current elements will be Jogi maximum, the place channel here, right left or right and political. Situation means inside the side of the last which option it will be equal to the light of the element and from the back side IS retired for remedy the soil filling is white till 2018 that till the time I get 1000 comes then the right IS basically will be micromax of wife means just the next one There will be a maximum associated with the element and the current element, it is of white color, so our left and right A program is off, now we will move ahead, we have made the answer which will be our final answer and I have given it the same problem, is n't it Bigg Boss? For the same index, with the coming of age, a film Kahar is basically running from I to 1000, what are we doing Next9, be it any network, this network has kept so much clock off in hotels, for that we have got laptop and right only. If you have less then take them out and from that - this math has to be done - we will do it from that - this math has to be done - we will do it from that - this math has to be done - we will do it and the whistle tiger will give it an answer plus and finally done from here and our work will be done here, okay so this is a big code but Modi Old men, I will show you, okay, you can fold it easily in 2 minutes, so this interesting romantic ending, with this, we have got more confidence, after this, we are doing Amazon shopping, so I hope you would have liked this video. And you must have liked this video. If you liked it then like the video and subscribe to the channel now.
|
Trapping Rain Water
|
trapping-rain-water
|
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.
**Example 1:**
**Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\]
**Output:** 6
**Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped.
**Example 2:**
**Input:** height = \[4,2,0,3,2,5\]
**Output:** 9
**Constraints:**
* `n == height.length`
* `1 <= n <= 2 * 104`
* `0 <= height[i] <= 105`
| null |
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
|
Hard
|
11,238,407,756
|
400 |
Jhal Loot Problem Loot-Loot Norms On Jhal Loot Problem Loot-Loot Norms On Jhal Loot Problem Loot-Loot Norms On Loot And Aspirations Hai To Bhi Aap Kar To Kuch Kafi Tikamgarh Movie Aa Jo Arm Hai Tu Bijli Ki Problem Before Approaching We Have Heard That Pyar Kam Raha Tha Roop Bring also, if you ask, victory will not be subordinate time-tested, killed, remaining time-tested, killed, remaining time-tested, killed, remaining tomorrow, if I tell it to make it bigger, to reduce tension, you see, if you take it, do we have any MS Word whose The answer is that it should be taken by 2030 third year so that before that, December 2012, one photo must be given, which space planet is it an extended one, has to go to a movie today, Bluetooth is the last date, for foreigners, this means this. Hey Ajay, hurry up tomorrow morning, Dubai is not our thing, so if number 203 is going to be found because of the red number, a Muslim girl like share and don't do it with others in New Delhi, turn on till the year before that. If you take it directly and tell me that it contains your nine dates, put whatever I have and after that, whatever lights are switched off, do it twice - I am from the village, it twice - I am from the village, it twice - I am from the village, hey, what are these thoughts, which ones are kept in the sales counter. Have seen till the number, start seeing high court setting, can By By By adding a 2nd cat, antonyms, place, blood, Jai Islam, improves, I ignore, what is the informant, tomorrow has not come, now what should I do, for the same I am going to store it in a vessel, nine to power and Bluetooth settings - Bank Bluetooth settings - Bank Bluetooth settings - Bank holidays 2019 have improved. Okay, if you see, the first one is the first, I am single, watch the video of a group in it. You will get 132 Indian options. Nine to Go team's power one. Tootne ki dishoom is here And after that we will deepen it so much that I will only follow those who apply will get what I am Sunil Shetty movie khush nadiriye national ki loop discussion I had come to Ajay that why should he laugh that Hanuman is the episode number and that my balance is number 19, he should go away and give me a blue film video bank account public, I will loot the public account. After MP3, Vikramaditya to bring Indore Lok Sabha elections. That if I calculate in the right way, I will give my one plus that how many numbers do I need, then here we have looted one, really thank you YouTube light that the time has come for this Marathi that now the current satire has also happened and here But Yo Honey's trick is that you will get that last meaning, this curd of firecracker has reached here to loot, let's take a minute, Google me, give me that good kind of music, loot and with that loot, I will do it. I am in the company that romantic and will bring me this SIM in 202 How to do Kishanlal Shai Ghar, which number is it that I should turn on our channel Pluto, it is very small here, after that send as many photos as possible to the people of Amethi. The temple minute is 20 December 25, its a that I multiply that number in the office, don't take so much tension, return the loot, what is the simple thing behind Bihar Blue Film Part-2, meaning, you understand, what is the simple thing behind Bihar Blue Film Part-2, meaning, you understand, what is the simple thing behind Bihar Blue Film Part-2, meaning, you understand, give me the number 432 19. I will do a Jo man full song should be in Bhojpuri if there is some romantic hero that laundry will have to be created against meghnad hai then I am here if in note MP3 I will get the video blue film Facebook kiss photo is not correct Health limited on small score Font It came to know that loot is loot that 24 li is here now so we mobile is not appropriate New Delhi - Drama of and strong Rajendran New Delhi - Drama of and strong Rajendran New Delhi - Drama of and strong Rajendran completely emptying him and oh and happiness here what are we going to do He is saying that from 10:30, whatever you have written, it has to be done that from 10:30, whatever you have written, it has to be done that from 10:30, whatever you have written, it has to be done on torch light bill, modern periodic table in Hindi, if the number of activities is there, then trend - subject was made is there, then trend - subject was made is there, then trend - subject was made a boy, short time is half from power two, then the horoscope is updated. Pyaar Mile MP3 The Power of Film Comedy Show Loot Film Click on every like button Thank you Haryana Sunny Leone is the officer of Indian players that you are intelligent Hello viewers Hum village maintain ji achha Yagnik So if you loot then he will not be happy I will meet you in the next video and I am
|
Nth Digit
|
nth-digit
|
Given an integer `n`, return the `nth` digit of the infinite integer sequence `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]`.
**Example 1:**
**Input:** n = 3
**Output:** 3
**Example 2:**
**Input:** n = 11
**Output:** 0
**Explanation:** The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Math,Binary Search
|
Medium
| null |
1,375 |
hello everyone in this video I'm going to explain to you the solution for the legal problem both Witcher 3 so basically in this way given n bugs numbered from 1 to n arranged in a row from left to right initially all the bugs are turned off so we're given an integer array light having values from 1 to N in any order and if K ranges from 0 to n minus 1 the light has a size of n which is also the number of bugs so at any light of K will be turning on that positions light so suppose K is equal to 0 then light of 0 is 2 so at moment 0 we'll be turning on the second light bulb and K is equal to 1 we'll be turning on light of 1 so we'll be turning on the first light bulb and so on so we're given with an array of array called light having values from 1 to N and that gate position of light will be turning on light of K it but now what we have to do is first there's a condition given a bulk will change color to blue if it is on and all the previous books all the bulk suits left are turned on too so we need to return the movements in which all the turned on bulbs are blue so let's understand with an example first so here light is 2 1 3 4 5 so the maximum number of bulbs are 5 so the webs are 1 2 5 initially as given in the question and this is our light area so at movement 0 light of 0 will be turned on second world is turned on it is it does not change to blue why because 1 is not on then at moment one light of one bug is turned on which is the first bug verse 12 is turned on it changes to blue why because the preceding it is Noble so at any case light the first light bulb will be will turn to blue and then to also turns to blue because 2 is already on and now the Bell preceding it is also on so both of them turn blue no at I K is equal to 2 at second movement light of 2 which is 3 is turned on and it also turns to blue why because all the bulbs is hearing it W now at moment 3 light of 3 bulb is turned on which is v so v bulb is turned on but it does not turn blue why because the bulb is hitting it is not on then at moment for light of 4 is 4 to the 4th bulb is turned on and now all the bulbs are on so all of them turn into blue so there are 3 movements at which the burbs are all blue which are 1 2 & 4 as you can all blue which are 1 2 & 4 as you can all blue which are 1 2 & 4 as you can see by these images so the solution for this is very easy and the most basic idea that people get for this is using off n square using to loop my token square here will give time leave it exceeded so we can do it in of n time so how are we going to do that so let's see first we will maintain an integer little keep track of the right-most bulb which keep track of the right-most bulb which keep track of the right-most bulb which is on and let's take it as initially as minus 1 now we'll be looping through our given array so integral to 0 I less than light dot length I plus no there's one thing you need to understand at ayat moment light of I it bulb will be turned on now what is I what is the significance of I if you see closely I plus 1 is basically number of birth I plus 1 is equal to number of perks we have turned on number of both turned on so as you can see at the at I it position suppose I is 3 then that I is equal to 3 we have turned on four light bulbs or when I is equal to zero we have done on one light bulb so after turning on the light of ayat light books the number of light bulbs which are turned on or I plus one and let's keep a counter set to zero which will keep track of all the moments at which all the light bulbs turn to blue so right mash is initially minus one and then if we find anything to the right of it meaning greater than it that will change so if light of I greater than right max then simply right max is equal to light of five now this is the most important part so at right max or changes to right max anyway job so right max is keeping track of the rightmost bulb which is turn on so at any moment suppose that the right max is equal to the number of bulbs which are turned on meaning that all the bulbs which are turned on will be blue let's look for example so here at moment one I is 1 and the bulb which is turned on right max is 2 so 2 is equal to 1 plus 1 I plus 1 2 so both the bulbs are turned on look at this example here I is 2 and light of I is 3 and the right max is 3 so right max is equal to 2 plus 1 so all the bulbs are turned on right look at here I is 3 and the right max is 5 so 5 is not equal to 3 plus 1 4 so this is not a moment where the all the lightbulbs are blue so basically what I'm saying is if right max is equal to I plus 1 then we have found a moment where all the bulbs are true all the works are blue and I took a Dixit this example is well the moment is 4 and the right max is 5 and so 5 is equal to 4 plus 1 si is 4 and so this is again a moment where all the light bulbs are turned blue then simply add then we can return count so in a nutshell what we're doing is we're finding out the rightmost bulb which is on and if that is equal to the number of well which are turned on then all the bells which are turned out are turned on or to the left of it then we've got a moment where all the bulbs are turned on and all the wells are blue so only if there is a sequence of births on the left so that all the bulbs are on then all the pulse will be blue let's try to run this seems okay so as you can see this is run time 1 m/s faster than 100% of Java online 1 m/s faster than 100% of Java online 1 m/s faster than 100% of Java online submission because we did it in row of n so the approach is a little difficult to get but once you get the idea it is very simple thank you
|
Number of Times Binary String Is Prefix-Aligned
|
find-palindrome-with-fixed-length
|
You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith` step.
A binary string is **prefix-aligned** if, after the `ith` step, all the bits in the **inclusive** range `[1, i]` are ones and all the other bits are zeros.
Return _the number of times the binary string is **prefix-aligned** during the flipping process_.
**Example 1:**
**Input:** flips = \[3,2,4,1,5\]
**Output:** 2
**Explanation:** The binary string is initially "00000 ".
After applying step 1: The string becomes "00100 ", which is not prefix-aligned.
After applying step 2: The string becomes "01100 ", which is not prefix-aligned.
After applying step 3: The string becomes "01110 ", which is not prefix-aligned.
After applying step 4: The string becomes "11110 ", which is prefix-aligned.
After applying step 5: The string becomes "11111 ", which is prefix-aligned.
We can see that the string was prefix-aligned 2 times, so we return 2.
**Example 2:**
**Input:** flips = \[4,1,2,3\]
**Output:** 1
**Explanation:** The binary string is initially "0000 ".
After applying step 1: The string becomes "0001 ", which is not prefix-aligned.
After applying step 2: The string becomes "1001 ", which is not prefix-aligned.
After applying step 3: The string becomes "1101 ", which is not prefix-aligned.
After applying step 4: The string becomes "1111 ", which is prefix-aligned.
We can see that the string was prefix-aligned 1 time, so we return 1.
**Constraints:**
* `n == flips.length`
* `1 <= n <= 5 * 104`
* `flips` is a permutation of the integers in the range `[1, n]`.
|
For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome.
|
Array,Math
|
Medium
|
9,564
|
252 |
hi everyone today we are here to tackle question 252 meeting rooms so we're given an array of meeting time intervals consisting of start and end time we want to know if a person could attend all meetings okay so first i like to think about some of the clarification questions and understanding the input and output that we're given so first of all we want to know how can we determine if you know two meetings don't work with each other well i guess another way to think about it is if our meetings actually don't overlap but how do we kind of determine if it's overlapping so let me give you an example in this case if we have one two so this is our first meeting and you know second meeting this is considered overlapping um we have the same end time as the start time of the next meeting so to figure this out in a meeting like interview setting we would ask our interviewer um i think some other questions we might want to ask is you know if our time intervals actually represent the hours in a day or are they actually times or the are they more like an abstraction just integers and um how big can the input get so that's sort of some considerations we might have um in this case lead curry doesn't give us any more clarification so i like to figure this out by just kind of typing into my console and see what answer we get all right so we know that this will be true so we are allowed to have overlapping endpoints okay so how will we figure this out well when we think about actually attending meetings i like to think from the earliest to the last meeting that i'm going to attend and chronologically i would look at try to attend the first meeting and see if the end time kind of clashes with the next meeting right in this case we want to see if our end time is larger than the start time of the next meeting if that's the case we know we have a problem and we will immediately terminate and return false and sorting the intervals we would need uh n log in time complexity and kind of checking if things overlap or not after the sorting that would be a linear time so i think if you think about it this way another clarification that would have probably like to ask is our intervals already sorted is it given as a sort of input but as we can see from the input here it's clearly not sorted so yes so now i think we're ready to get started so first i like to always kind of do a sanity check um and also there are cases that we know that we can terminate early so there's less than or equal to one we of course can attend all of our meetings right now we want to sort our meetings so i like to sort by end times because i want to know that these are the meetings that i'm going to attend and end first and leave first okay now i'm gonna keep track of our last end time and kind of initiate that to our first meeting in time because we know for sure that our first meeting will be able to attend it and then we want to go through the rest of our meetings so now we want to check if our last end time is larger than the current start time if that was the case it would immediately return false so otherwise if it succeeded will update our last end time to be current event anytime right so that's sort of our algorithm here it's going to quickly scan through it um in interview setting i like to kind of walk through each of the test cases that i kind of laid out previously to make sure that my code works before i tell my interviewer that i'm ready so in this case i think the card is pretty clean and straightforward so we'll just submit and okay um typos always get us so make sure to watch out when you don't have like syntax highlighting things yeah so that's our solution for today see you next time thanks for watching you
|
Meeting Rooms
|
meeting-rooms
|
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** false
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** true
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 106`
| null |
Array,Sorting
|
Easy
|
56,253
|
443 |
hey everyone this is Alex welcome back to my videos on solving lead Coke problems and now we're solving problem 443 sting comprehension string comprehension given an array characters charge compress it using the following algorithm they could begin with an empty string s for each group of consecutive repeating characters in charts if the group length is one append the character to S otherwise a Penta character followed by the group's length okay I get it compressed string should not be returned separately but instead should be stored in the input character array charts not that the group length are 10 or longer will be split into multiple characters and charts after you download Define the input array return the new length of the array you must write an algorithm that uses only constant extra space so if character this is a b c should be a 1B 1 C 2. no C3 now A2 of course A2 B2 C3 returns six and the first six characters 2b2c3 okay cool so compress so number of final jars equals zero and current counter equals zero I guess so and current chart equals hmm no so for chart in charts um experts are is one then third jar equals char and current counter plus equals one uh no current counter equals one I guess if it's none else F charge is different then current chart then um number of jars plus equals two other pens if um counter because one number of file character is plus equals one and current chart equals none else twice equals to and let's just keep the value that we have so um modified index zero so charge of the modified index equals current chart and then modify index plus equals one otherwise what this will ruin itself I need to move this one down um this is there's like no secret I'm just like iterating and modifying things and then characters have modified index coming Char characters have modified index plus one is care counter and modified index plus equals two and the third counter is zero and same here so we get to the end and well current counter is not known current countries needs to be one you can shower is not done current Char is sharp because it's already counting the next chart yep so at the end we just pretty much do the same thing uh would be great if we could add just another ridiculous Char in the end like a Char that is never a current char would be nice if we could have well let's do that let's cheat I think it's okay if we do that chars no I don't think I can modify it though um let's just do this for index in range length of Charles plus one char equals Charles of index if Char is different than current char or if index equals negative charge so if this already went to the last one no it is already went overboard if um X is smaller than length of charge else let me just do a doesn't matter so return um return number of final jars I'll put ABC could this be I'm putting ABC first of all we're turning something up in this week else says the current counter always one is that a problem wait current counter is one so when it iterates again I'm never oh yes I've never seen that a flying index or index else I'm not doing the if else parents counter plus equals one a A2 b2c free of these ones Need to Be Strings okay train current counter yeah this is it's the only one two the grooves like there are 10 or longer will be split into multiple characters and charts a b one two Okay so I guess I'll just do train um accounts there's this so modify index charge of modified X plus one all the way up to index plus length of string and count is a string of count I don't think I can do this now I need to do something different I need to do a for Loop there so plus equals one plus the line of string okay I don't okay so now so I was doing this equals that so for uh in enumerate string of count charts the modified index plus one Plus y i equals modified index size two yeah that's not true so I add one plus ninth string of count I should run this luckily let me just create a new file okay solution Dot compress and let's compress this our number of final characters yeah this is not true here is plus one Plus is this a problem it might be oh yeah done runtime 57 memory not so good well I hope you guys enjoyed it I'll see you later
|
String Compression
|
string-compression
|
Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`.
After you are done **modifying the input array,** return _the new length of the array_.
You must write an algorithm that uses only constant extra space.
**Example 1:**
**Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\]
**Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\]
**Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ".
**Example 2:**
**Input:** chars = \[ "a "\]
**Output:** Return 1, and the first character of the input array should be: \[ "a "\]
**Explanation:** The only group is "a ", which remains uncompressed since it's a single character.
**Example 3:**
**Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\]
**Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\].
**Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ".
**Constraints:**
* `1 <= chars.length <= 2000`
* `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.
|
How do you know if you are at the end of a consecutive group of characters?
|
Two Pointers,String
|
Medium
|
38,271,604,1241
|
872 |
Hello everyone welcome, the question of my channel is lead code number 872, okay, Goldman, Amazon, Microsoft, okay, now by looking at the input and output, let us understand what the question is, okay, see in the question it will be given that you have been given two trees, okay. So the question number is simple, it is just said that if you look at the sequence of the two leaves, if six comes first, then we have to return true and if it is not equal, then we have to return false. The sequence should also be the same, the number is also ok. It should happen from, I am saying that it should happen in sequence, okay, so the question seems quite simple, that is, what you have to do is, you just take all the leaves, this is your tree, okay once. Let's draw it and number it 3 5 6 2 7 4 9 18 Your tree was not a tree, it is your van, you don't have to do anything, you simply sell it in order to the driver, you only need a leaf, no matter how you want it. You can do it Driver Saali, if you want to do it then you need all the list, okay then I give you these orders, okay return true, return false will also be accepted, instead of vector, you take spring, now instead of vector, take string, S1 is okay. And as you come closer to delete, in this string you append the string form of those numbers. Let us now take the string s one is empty so let's take main. First I came to six. Okay, so what did I append in S1? Given 6, appended it, okay, after that it came to 7, okay, so in this I have opened the seven. Nine four nine eight is making a string, we are not making a vector, it will take more space in Victor, obviously we are storing integers, here we are storing strings. We are doing fine but we will compare the string later. If string S1 is equal to S2 then return true otherwise false. It's ok. Just one thing to pay attention to is what is the key of one corner. Let's take this tree of yours, what is it here? If 21 is two then both are equal otherwise false should come. Answer is yes but if I take it and convert it into string then what will be its string. So two and 12 will also be equal to 212. 21 and two then it will be equal. Our answer is that if it has gone wrong, then there is nothing to be done, what to do to fix it is that after each leaf note, add one character, add two symbols, put something like man lo tu, after that add a ten, after that Have you put 12? After this, 21 have been put in 32. One ten, group two and two group two. Now see, you can make it either by stringing, both are up to you, I made it by string, okay so it is simple, they have to do traversal and all the leaves. You have to keep appending all the leaves you are getting in the string. Okay, so let's put it in the story code. Okay, let's do the coding like this. Okay, so the question is quite simple, you just have to check whether I have done it or not. I told you the example, okay, so don't waste much time in reading the question, it is a simple question, let's code it directly, okay, the story is exactly like I told, what did I say that friends will take the string, right? Will take one okay and will take the string S2 right and then what will we do I said that in both of them we will call in order In √1 I will in both of them we will call in order In √1 I will in both of them we will call in order In √1 I will call in order and will populate S van and similarly we will call in order Root is for you Na and S, you will populate, what will be there in S1 and S2, we will append the lip sequence of both in the form of string and will return in the last, right, so let's do this, let's take tree no testis root S man, okay. And we know the code of inverter. If A for root = null then we would return D. root = null then we would return D. root = null then we would return D. And what I told you is that whenever we get a leaf, we will append it to S, that is, if the left side of the root is equal. You are equal, you are null, and the right of root is also null, right of root is winner, what will I do with s, we will add s plus it is equal, you converted the value of string root into string, what did I tell you, make a ten head. Let us do that how to save and we have come to the leaf then we return from here and if it is not leaf note then what did I say, we go to the leaf note and call from the inverter place, you know what to do first. You go left and then you go right, it's as simple as that, okay, so let's run it, let's see the example, see you gas in the next video, thank you.
|
Leaf-Similar Trees
|
split-array-into-fibonacci-sequence
|
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._
For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`.
Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same.
Return `true` if and only if the two given trees with head nodes `root1` and `root2` are leaf-similar.
**Example 1:**
**Input:** root1 = \[3,5,1,6,2,9,8,null,null,7,4\], root2 = \[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8\]
**Output:** true
**Example 2:**
**Input:** root1 = \[1,2,3\], root2 = \[1,3,2\]
**Output:** false
**Constraints:**
* The number of nodes in each tree will be in the range `[1, 200]`.
* Both of the given trees will have values in the range `[0, 200]`.
| null |
String,Backtracking
|
Medium
|
306,1013
|
154 |
okay let's talk about find minima in rotated sort of rate too so this question is simple so uh you're given a rate but the array is somehow sorted but not exactly because it will rotate it and you just have to find the minimum based on these uh in array so you can do linear search but i'm not suggesting to do that level waste of time because the array is already somehow sorted right so you can actually use a binary search so if you use the binary search you need a low pointer and high pointer and once you have this you can find out the middle pointer and this is the formula so you use this to find out the middle pointer is because you don't want to have a problem for step overflow so the idea is you compare the middle value with up against your high value if the mid is less than height you do something right if the mid is greater than height you do something else right else you do something else right so you have three cases right so if the mid is less than height which means height is too big right but we have to finally meet the minimum value right return the minimum element so i need to change my height to middle value so in this case let me find another pencil so height will become mid and i'm just keep doing the binary search what happens if the mid is greater than high which means high is small meaning speak right so i can actually change my low pointer to mid plus one right i'm not going to say equal to me because mid is already high me plus one is unknown right so maybe i can change to me plus one so what's the uh the last case you can actually just decrement the height right because you actually return the height pointer so just high minus so that will be the solution so let's just look at the probe so i have the low and high pointer so it starts from beginning and end if the low is actually less than high just return the value at low and if not then i have a well low situation so low less than high and middle value is equal to low plus five minus load divided by two and if the middle value is too small then i know the height should be rearranged right if the middle value is too big then i just have to rearrange the low pointer else i just decrement height and return the height and that would be my situat uh solution and they just run it so it shouldn't be a problem so uh let's talk about time and space so what do you think about time uh you have two pointer and you all you always cutting the half so the time is locked on right and the space is constant you're not using any space so that will be the solution and if you like it just press like or comment or subscribe and peace out
|
Find Minimum in Rotated Sorted Array II
|
find-minimum-in-rotated-sorted-array-ii
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,4,4,5,6,7]` might become:
* `[4,5,6,7,0,1,4]` if it was rotated `4` times.
* `[0,1,4,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` that may contain **duplicates**, return _the minimum element of this array_.
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[1,3,5\]
**Output:** 1
**Example 2:**
**Input:** nums = \[2,2,2,0,1\]
**Output:** 0
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* `nums` is sorted and rotated between `1` and `n` times.
**Follow up:** This problem is similar to [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/), but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
| null |
Array,Binary Search
|
Hard
|
153
|
142 |
Hi welcome question series and here we are going to attend question number 142 which is the second part of the linkless cycle. We had seen the first part of this where the question we had was that we have to detect the linked list cycle that a link Does it do cycles in the list or not? Okay, now there is the second part of it. If I tell you here, consider it as the first part, once the first part is cleared, then in the second part only something extra has been asked, so I have done it here in the first part. That is, if you have a link list suggested here, okay, here you have to detect whether a cycle exists in a link list or not, okay, like here you will see, there is a cycle in this linkless here. And then like this it will go to the cycle here, then you have to remove this cycle here. The normal link list here is something like this. If there is no cycle here, then this is your next note. It is pointing to your tap but there is no tap here. Okay, so there are infinite cycles here, so you had to detect in this question whether the cycle which is in a linked list exists or not. On this question, to do this question, we did it here, okay, it is the fluid cycle dictation algorithm, it is the fluid washer cycle dictation algorithm and it is also called breaktoise and every alcohol thumb because here we do it on the fast painter and How is this question of slow painter, once we understand this, then the next question depends on this. How do people do paste tense? If you like, I will take a second and see the code written here. If it has happened, then how is it pecking here? We have two points here, one was slow painter, one fast point, there are 10 slope painters of fast quantum, both start from your place, both are starting from your head, this is yours here. Pay is the head which is your life, here is the head, take the first element of D, first note of D link, it is called head, okay, what you have to do is fast, so you have to move by doing a painter step, that means the move that will be fast is that. Two points will move, okay, the slow one will move, it will be a painter move, so slow, your mouth will come here, okay, whatever is near this will skip it and it will come straight here, so the fast painter will skip one road. The slow painter will move there, it will come to your next note, okay, the slope painter will then come here, your fast painter will go here, okay because it will skip it, after that there is your slow point, your fast point will come here. A point would have been reached here, okay slow painter will come here, your fast point will come here, Raju's point will come here, then you will be slow here, he will be equal to you, if there comes a point where your slow and fast are same. We are pointing to the element, we are pointing to the same note, how can you tell that the linked list here has a cycle axis in it is okay because the one who is fast will keep rotating here only, fast is yours only. But your slow motion will also keep rotating at the same place, a point will come where both of them will come and meet each other, so if they meet each other, then it means that a cycle exists in it, right. It was a simple question here, if you look at the question here, we took one slow for fast, we put a condition here so that it does not go into the tap and for fast slow, we made one point, for fast we took two intermediates, here we gave one V. It is a bicycle, it is ok. If I show you this question here, then we have already attempted this question. You will find it below here. This question is ok. You can find the link of this question in the description of the video. Here's the question 141 Legless Cycle You will get the link of this question in the video description Now here's a next question What is telling us Next question What is telling us here Life D Head of D Link List It is not asking us this Whether this cycle is there or not, we are being asked here that the head is given here and you have to tell from where the cycle actually starts in the link list, like if you look here, this note is that. This is where your link cycle starts, so you probably have to return the index of this note, as far as I am concerned, let's take a second This is your first index, so you have to return the first index here. So what you have to do here is to simply tell that in this question which is the second part of the link list cycle, where did your cycle start and where did this cycle start from, you look here. From here we came here, there is no bicycle, but your bicycle has started from here, this is your note here, it has the address of this note, so you have to check here from where it is starting. What is the way to do this, first of all you have to detect here whether your link is cycle or not, if it is not cycle then you have to return -1, not cycle then you have to return -1, not cycle then you have to return -1, then you have to use the code that we had written in Linked List Cycle One. Well, you will need sir code here, you have to detect here whether the cycle exists or not, if the cycle does the axis here, then after that you have to take out the note from where that scientist started, then you look here. If you notice one thing here that your slow and fast quantity is found on this note and I will show you the mathematics of this thing which I am going to talk about here and it is mathematically proven, they had done mathematics on this thing. If you have to find the starting point of the note, then for that, wherever your fast and slow painter will meet, your distance from there to here will be the distance from your starting to here. What I have said here is that wherever you will meet, If here you have to calculate the distance from your node from where your cycle is starting to that point which will be equal to where your slower fast quintal will meet from the starting of D link list to the D cycle where your cycle starts. So it means if this length is your length here and this proposal is a distance of yours which is from the proposal, then here your Pa L and K will be equal and you can also see this thing that here if you have this one. On the note and you have to go to this note, you will have two notes here and if you have to go to this note, here also you have two examples. If you look here then slow will come to you here and fast will come to you. It would have been done here, again your slow will come here, it would have been done here, okay, so you look here, if the store fast point is found on the note at your place and the address from here to here, which is your The distance is from that is from here to here The distance from here to here is both and from here to here only two notes exist Okay, so what is the way to do this question The way to do this question is here This is the only thing you have to test here, where are these notes of yours found here, like you have found the fast point here, then what you have to do is set the slow one back to the head. Have to do it and move the fast control one by one, it will go here, and here also your slower fast will meet again, that is your starting point here. If there will be a point then this is the question which I have heard from you a story, okay this thing can be proved mathematically, many people have proved it mathematically, they have also explained how you can do it, how it is proved mathematically. So you look here, mathematically, the proof of closed cycle dictation algorithm, what to do here, is it all cycle or not, they did it here for slow painter which is increment by one, they did it for fast quantum which is increment and then they did it here. But I checked that the cycle is being detected. The cycle is being detected here. Look here, Slope Painter and Fast Painter have been found at your intake point. They have put a cross here, meaning they have come and met you at your intake point. Which is the length, this is equal to yours, which is here, this is this C, and this is the length, this is equal to yours, so how did they approve this, you can see here that the total distance covered by the slope of fast. How much is the point, so there is no value here, it is based on some supposition, it is not mathematically that you have taken A plus B whole square, you have proved it by multiplying A square plus B square plus you A B. The total square of a + b is equal to your total square of a + b is equal to your total square of a + b is equal to your a² + b² + 2ab, there is no such thing a² + b² + 2ab, there is no such thing a² + b² + 2ab, there is no such thing but here they have taken assumptions on the basis of which they have proved this thing, like if you see here then it is complete, okay? I am assuming that it will be this much will happen, then if you look here, they have proved this thing here, lol, so if you look at the story also, it has been proved, I show that this thing is here. How to do the question, first of all you have to reduce it from there, whether there is a detector here or not, then you will have to get it from the person who will point your head, after that you will have to get a fast painter from here which is available at your place. It will point to the pay head, after that you have to enter the pay condition here. While checking the tap, you have to enter the tap here and enter the fast pay key. If your fast should not be equal to the tap and your next fast should be equal to your pay head. Nal should not be equal. Okay and very correct. If it is not so, then you have to give pulse to Slava here, next to Slope and you have to give pulse to Fast, next to Fast, this will happen by coming to any one point. That your slow will be equal to your fast, it is okay if your slow is equal to your pass, that means you have a cycle here, in this you set the slow here back to the first point, dog on the first note, you set it here. given and you will check here till your slow becomes equal to fast, how to do it, what you will do here, you will move the slope forward by one point and you will also move the fast forward by one point here, okay if any Then if it happens that slow and fast will meet at one point, it is okay that whatever you meet, that is your point here on time, that is your starting point of the after loop, okay, that is the starting point of the cycle. So friend, how can I make it so that you can return it fast, both are pointing to the same element, if there is no cycle detector then you will have to press the button here, then this question is clear to you. In this way you can find out from where your cycle is starting. Okay, so this is the complete part of Flood's second deduction algorithm, you can read it. Okay, our question has been accepted here. Valentine's Day is here from zero to 100%.
|
Linked List Cycle II
|
linked-list-cycle-ii
|
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**.
**Do not modify** the linked list.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** tail connects to node index 1
**Explanation:** There is a cycle in the linked list, where tail connects to the second node.
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** tail connects to node index 0
**Explanation:** There is a cycle in the linked list, where tail connects to the first node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** no cycle
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Medium
|
141,287
|
1,952 |
hey everybody it's peng here so today we're talking about question i did yesterday in contest 252 question one is called three divisors it's question 19 52. so given the integer n i want to turn true if n have exactly three positive divisors otherwise return false so integer n is device of n if there exists an integer k such that n equal to k times m so let's look at an example so for four if anything is equal to four output should be true because four of three divides us you know one times four equal to four two times two equal to four times one equal to four so three different divisors and then basically i figured out that if a number needs to be device of and so my approach is for example if okay so let me explain to you my approach so okay so if n is equal to four right how can we find out how many devices number n had so i used four number four so basically i try i would try from number one to four you know and then for each number i use the number n and use the module operation and try on each number so in this case if equal to zero it means the number i'm trying is a divisor of n so if we keep trying right so f4 modulo operation two equal to zero also in this case much of a three is equal to one so it is not a part of division so four modulo four is equal to zero also so in this case i keep count of how many times it can be add up to zero i mean it can be when the number n divided by each of the number from one to n if the result is zero is one of the divisor so here i create a divisor cap you know to keep track of how many devices total devices for n so i look through from one to n and see i check if the number n can divide can be calculated by module by i is first at one so if it's equal to zero i add it up at a count i went to the count if it's not i don't add it you know so at the end i have the total count of how many devices and since you know the question is asking okay so have exactly three positive divisors so yeah so i check after that after we look through everything here after we loop to from one to n and we get the total count of how many devices we check if the number if is if it is equal to three return true if it's not written false so let's see it should be good yep okay so and that's it the day
|
Three Divisors
|
minimum-sideway-jumps
|
Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explantion:** 2 has only two divisors: 1 and 2.
**Example 2:**
**Input:** n = 4
**Output:** true
**Explantion:** 4 has three divisors: 1, 2, and 4.
**Constraints:**
* `1 <= n <= 104`
|
At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane.
|
Array,Dynamic Programming,Greedy
|
Medium
|
403
|
1,887 |
hello so today we are going to solve lead code problem 1887 it's today uh daily problem so the problem statement is like uh reduction operation to make the array element equal so basically they will give us a array and we have to make all the element of the array equal with some constraint we have to apply sub operation after applying those operation do minimum operation and make we will try to make all the element of the array zero so uh once go through the problem statement given an integer array nums and nums your goal is to make all element equal to complete one operation follow these steps so we have to perform some operation the those operations are first thing find the larg value in the nums let it index is I and value that value will the largest so first we have to find all the first we have to find the largest element in the array after that if there are multiple element with the largest value pick the smallest one that mean to uh eliminate the confusion they have said that you have to find the smallest largest element with smallest index after that find the next value in the nums is stly is smaller than the largest that mean after that we have to find the next largest element and reduce the largest to next largest that mean we have to reduce the maximum largest equal to the largest value and return the operation to make return the number of operation needed to make all the element into the nums are equal so uh let's understand the question so in question we are having some array we are having one array and in Array we are having some element like 1 3 4 7 6 3 5 it see like that so our task is first we you have to find the largest element so here the largest element is seven and then we have to change the largest element into next largest so here the next largest is five so after performing this operation our next array will be 1 3 4 5 3 and 5 so we have performed one operation let's decide we have performed one operation after performing that one again we have to find the largest one so now we have we are having two largest five and five so first we will choose this five and we will change this five reduced to the next largest is four so after that our array will be 1 2 4 3 and 5 and so on again we will five the largest one so again we will five find the largest one is five and we will change five into four after that our array will be 1 2 4 3 and 4 now so in this way we are performing two more operation so two after that again we'll find the largest one the next largest is four here we are having three fours three time fours and three time we have to change the each four into three first we will change this four into three again we'll change this 4 into three so we have observed one thing each step we have to count how many largest element at that step and we will need that much operation to make that largest element to change in next largest one so we got one idea first we have to check number of largest element so here we are having number of largest element is five so one largest element is one then after that we have to find after making this largest it will become to equal to sorry uh first largest is seven so first we'll make 7 into 5 after that we will get two largest this seven become five again this five is also five so again in next step we will go two maximum element this five and this five so then we will got we have to oper perform two largest operation so the each step we are con we are adding previous largest one in next largest one we are getting the sum of largest and second largest in next step we will get firstar largest plus second largest plus third largest so we'll get three operation here so on each step you are adding the what are how many largest element plus previous largest then next largest element and we will add the number of largest element and we that much operation we will need to convert previous all the largest element till the that point so suppose uh we will understand this 1 by one diagram let's understand this AIS is x-axis and this understand this AIS is x-axis and this understand this AIS is x-axis and this one is y axis so suppose the y axis representing the how many what is the value of largest one and X is representing how many numbers we are having at that stage so suppose we are having three number at very largest one again we are having three number at second largest one suppose three number is having value of s five number is having value of five number is having value uh three number having value of five and two numbers having value of three so first we have to make all these uh seven value equal to five so H uh at each step we will make we'll make one uh we'll convert 5 17 into 5 so one operation need to convert this 7 into five again next one operation we need to convert this 7 into five again next one operation need to convert this 7 into 5 so we need three operation to need to convert three uh three operation need to convert 7 into 5 at Next Step we'll got 3 + 3 so we'll need six operation to 3 + 3 so we'll need six operation to 3 + 3 so we'll need six operation to convert this five into three so we have to count how many stages we are having and at each stage we are we will count how many number are greater than that St and that is the operation to convert that many operation we need to convert greater element at to that stage so first we'll need three OPP to convert 7 into 5 again we need 3 + 3 6 op to 7 into 5 again we need 3 + 3 6 op to 7 into 5 again we need 3 + 3 6 op to convert this all five into three so we need total six operation after six operation we'll get all the element equal to two that will the answer 3 + equal to two that will the answer 3 + equal to two that will the answer 3 + 3 so what will the approach of solving this problem so uh the first idea is first we have to count how many number we are having at each stage so for that we have to sort the all element so we first we will sort we will salort suppose we are having three 3 4 and five so we will sort the element into ascending order then we'll convert we will count at each stage when whenever number is changing we'll count how many number are greater than that point so if you go through to the left to right after sorting so here number is changing so we get one element is greater than four so first we will add one after adding at this stage we'll get how many element are greater than three so we will get three element is greater than three so we add three here and so on we will add the all element at each step and we'll get the answer so let's C quote this problem so first sort the all elment sort nums do no do begin ns. end and we don't want to Travers from back to end so we want to sort it in descending order so for that we have to call Greater function here greater in Greater we have to pass int because we are having all the value in form of integer and it is function so for uh int IAL to 1 2 I less than nums dot size and after that we will increment the I value and whenever the value of integer uh whenever I value will change whenever we got the a value which is lesser than the previous one that mean it is The Changing State so at that stage we'll count how many we how many value we are having greater than that point so whenever F nums I not equal to nums IUS one simply We'll add into answer is equal to I and let's return the value return and I hope it will run learn so oh compile notal to sorry we have not declared any answer variable foral zero I hope this time it will be run yeah so all test case are fast let's submit it so it's submitted now it's time to discuss the time complexity of that approach so uh we have performed first we have performed the Sorting operation so it will take time of n log in after sorting we are just iterating the all elements it will take end time so B of n log n plus n that mean it equal to order of log n logn thanks
|
Reduction Operations to Make the Array Elements Equal
|
minimum-degree-of-a-connected-trio-in-a-graph
|
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`.
3. Reduce `nums[i]` to `nextLargest`.
Return _the number of operations to make all elements in_ `nums` _equal_.
**Example 1:**
**Input:** nums = \[5,1,3\]
**Output:** 3
**Explanation:** It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\].
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** 0
**Explanation:** All elements in nums are already equal.
**Example 3:**
**Input:** nums = \[1,1,2,2,3\]
**Output:** 4
**Explanation:** It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\].
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 5 * 104`
|
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
|
Graph
|
Hard
| null |
246 |
hey folks welcome back to another video today we're looking at question 246. trobo chromatic number uh the wave will be solving this problem is by using a hash map which will be used to map these numbers that look the same um at even if you flip down 180 degrees so let's get started um to be able to do that obviously we need a hash map so let's uh create one uh let's and let's draw a card with the card we could also do something like um integrative integer but since like the parameter that's given to us is ensuring you could just like extract each of the digits as a character without doing any kind of conversion so I'm keeping it this way but I'm sure those methods are fine as well all right um so you need to once you have the hashmap set up you need to add the characters as well so let's call like a okay helper function uh you don't really have to uh just so that the coated cleaner so private void helper doesn't really take any arguments all you're doing is you're adding uh the values of the care about so map dot put so let's start with all of the digits from the beginning right so zero looks the same how many flip it 180 so let's do that for all the digits so we have that for one and then we and so two doesn't matter three doesn't matter four doesn't matter neither does five six matters as on like six and nine look similar when you put them upside down and then um seven no eight matters so let's add eight and then the last one is nine and six wait so I think that should be all um when you're creating I'm adding characters to a map you could possibly as I said like have it here as well but um when it comes to like coding during interviews it's nice to have like a um like division of responsibilities for each method and it looks cleaner as well so it's better to have it this way um once we have that set up uh we can go through the main problem itself so uh what are the things that you need the first you need to get the length of the or the string that's provided to us so let's get that so I think like the one base case that we need to handle is if length is equal to one so let's do that so if um l equals one there are a couple of things that we need to take care of um so if uh so I think there are two test cases so if uh map so if the map doesn't contain the first character obtains key let's just say and just extract the character right here and let's call it char a current char and since it's this one we need to look at just one letter which is num dot character zero right so if the map doesn't contain the current character that we're looking at so basically it doesn't look the same um so you just return false we're done false and the other test case that you need to test for is that even if it exists right you need to make sure that um the character that it matches to is the same so that they look the same when you flip it on like 180 so map.get you flip it on like 180 so map.get you flip it on like 180 so map.get current character should be actually equal to the current character so in this case it works only for characters like if it is not equal um you return false otherwise you return to we could actually like simplify this as in like only if it is the same it could return true um but that's fine actually yeah let's just do that so only but we need that check that it exists or not so let's just have that track so I think we could possibly simplify it as in library checked map contains K current key and the first condition that we need to check that it does exist and um and even if it does exist you want to make sure that um the character that is that it matches to is the same as in if it is zero then it's fine but if it is um a six I think that's fine too uh yeah I think it's fine actually um all right so let's get back to that so if this is we're done true I'll suit it on salts and now that we've handled the uh the base case uh we go for like the meat of the problem which is um actually looking at all of the numbers let's use a while loop here that looks at like so we have two pointers that go from right to left and we compare digits and then we have integer J equals seven minus one and then for the while loop you need to have while I is less than or equal to J uh one obvious question is why do we have needed to be equal so the string that could be given to us is it could be like an odd could be an odd length as in like the middle digit could be five right but that wouldn't be a string that we care about we would have to return for false in that case that's the reason why we need to check the middle digit as well so uh I think it's the same case here as well so if map contains key uh can so there are two checks here um so let's say character e is equal to I'm not character at I and this is J right um okay so if map contains key current character actually let's do it all the way if not doesn't contain a um actually let's just simplify this one like R if map doesn't contain v as I'm like okay so those characters both of those characters should exist because they need to match right so if it is not the case that they both of them don't exist in the map you would return false and then after that so map dot get a should be equal to uh B actually so the second character so if map dot get a is not equal to B you return false right and in the end once a while loop is done if we haven't returned false yet that means everything matches and then in the end we return true right so I think that should solve it so let's revisit this case don't think we need this part I don't think we actually need this part so if as long as it exists I think we're okay so this can actually be simplified to return map that contains key yeah and we can just remove this so basically for something with one length what you're checking is that if it does if the one letter uh character exists in the map as even if you donate like uh 180 degrees like it should still be fine um or should be the same that looks the same okay now that it's fine it looks the same so actually I think we do need that check yeah so we do need that to check so basically since we rotate it by 180 degrees and it should be the same number uh if we rotate six and nine it won't be the same nine and six won't be the same sorry we actually do need that check okay awesome so let's try compiling this and see if it's okay I don't know why I made code has been super slow today huh oh of course I haven't like so you increment um I and the command J so let's try that again obviously it's a while loop you need to implement and decrement from both the pointers all right so the first few test cases pass um so the output is false it should have been true uh wait okay so yeah I think that was the missing part so again get characters equal to the current character yes so let's try that again okay that's awesome cool so let's talk about the space and the time complexity of the entire solution the space complexity of the uh of the solution is of one since we aren't taking a lot of spaces like the constant space that we're taking and this won't in uh like increase in size at any given point of time and the time complexity is off and since we are using a while loop and we have to iterate through all of the characters on the string awesome if you have any questions please let me know in the comments below if you can think of a way of simplifying this problem also let me know in the comments below um I would love to hear your thoughts and ideas uh please don't forget to subscribe to the channel and like the video I would really appreciate that it keeps me motivated to make more videos thanks so much and I'll see you folks in the next video peace
|
Strobogrammatic Number
|
strobogrammatic-number
|
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_.
A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down).
**Example 1:**
**Input:** num = "69 "
**Output:** true
**Example 2:**
**Input:** num = "88 "
**Output:** true
**Example 3:**
**Input:** num = "962 "
**Output:** false
**Constraints:**
* `1 <= num.length <= 50`
* `num` consists of only digits.
* `num` does not contain any leading zeros except for zero itself.
| null |
Hash Table,Two Pointers,String
|
Easy
|
247,248,1069
|
946 |
hey everybody this is larry this is february 26. uh hit the like button in the subscriber and join me on discord a couple of days left uh and let me know what you think about this really long one for me even though it's only 28 days uh okay so today's problem is validate stack sequences um okay so yeah distinct values aren't true if this could be the results push and pop on an initially empty stack what does that mean or like what is oh yes i usually stop these live so it's a little bit slow just fast forward or something like that i'm just trying to understand what uh this is asking more than anything okay so you get pushed you have popped push one two three four five four pop four five and then pop three five whoops oh you pop to get to five you pop to get to three about to get the two pop to get to one okay um is it some sort of greedy i mean it's gonna be some sort of greedy but i'm trying to think about how to think about it uh and maybe some sort of stack as well right because is either that or this like one in radit uh configuration and we have to figure out how to calculate that invalid configuration um okay so what does it mean well when one is pushed well one could be popped as well right so we have something like yeah one two three four five pop could be one two three four five we just push one pop one right um so what does this mean when one is here right well one is here it means that is this some sort of um almost like um like almost the right encounter or something like that because okay if one is here then what does it do to the popped right that means that everything after this has to be either before or after right is that true two three four five right i think so because you know going from push to push um the contradiction is that i'm guessing i'm just still trying to figure out how to prove this um i'm guessing that if like there's a two that comes after the push that means that um what has to be you know when one gets popped it has to happen either afterwards or before right um and all of them has to be consistent so you basically that means that given a push it has to be either at the beginning or the end is that true i'm still trying to think whether that is true yum though um i think to be honest if this was a contest i would just jolo it but i think i mean it's it sounds reasonable but reasonable doesn't always mean you know like uh i get greedy wrong greedy algorithms wrong all the time so um okay yeah i think so let's give it a try i mean i maybe this would be a proof by ac type problem so yeah so we're going to come up popped into a deck so we could remove from the now i guess we'll just keep track of i mean i've been doing i've been having a tendency to convert everything to a deck instead of um yeah let's do it because so my warning is that if you want to do this queen you just have a pointer on the popped and then another pointer on the left okay fine let's do it that way uh i just wanted to keep it uh really simple but level 0 right is equal to length of pop minus 1 and then for x and pushed if x is equal to pop of left we in command left if uh else if x is equal to popped up right minus one and assume that if you got length otherwise then this would be wrong but your elbows return false return true and of course this is because they have distinct values as well um because otherwise you could have you know one in the beginning and the end and then you have to make a decision and right now there are no decisions it is some sort of greedy as a result because there only could be one place where it's happening um okay so this looks good that doesn't have any confidence because there's a true force but let's give it a go oh wrong answer okay so at least i know that's not true or like my answer's not right okay let's take a look in here then because i didn't really spend that much time disproving this either but okay so this is a pop and this answer is oh so you can't get here so okay so my assumption was wrong so you push the two on the stack um push the one on the stack pop the one pop the two and then get to zero okay so i was wrong on this one then um i think there's a combination of but i don't know how to do it like here i only looked at one direction but you can just do a while loop for you know the fun you goes to front the back equals the back or maybe those two um okay i mean again you can do this with pointless but for easy purposes i'm just gonna convert this to um to a deck and then just again yellow this while link of push is greater than zero and of course they both should have the same length so i again i don't know that this is true i mean i know that this would solve this one but i feel like that is part of the invariant and that's why um and that's why i'm doing it this way but i think my marion was a little bit incomplete the first time for sure but oops i'm just like have to do it okay so let's go okay and if this is still wrong to have to really think about what's going on uh okay wow huh and to be honest i didn't really spend that much time on this problem uh thinking about counter cases usually for a contest i might but at least after the first one but uh but today i'm just really tired and it's been a rough day um but okay so here what's the answer oh i'll put true but the answer is force because two cannot be the last okay so i'm wrong again wow okay because i assume that we can get rid of the two and then one and the zero is easy right but in theory you have to do the one and then there's zero um and then the two to get the two and then zero and the one okay i think there's now i kind of see them wearing a little bit which is that which is i have to figure out in variant i think that's the biggest part of this problem and the biggest problem or the tricky part about this problem is that there's some or i know that there's some ordering with respect to uh here that has to be true where um where okay um is this one of those problems where you can only sort by swapping the front or something like that see what are the answers for this i forget what these inputs i mean uh did i put this in there yeah okay did i just remove the code yeah okay um because now you can swap these two but then here there's no way to output to swap them um i am actually stumped by this one a little bit today maybe i'm just a little bit off my game oh i think i'm just being too clever too smart um i think we can just simulate it um in a greedy way uh and if you've been watching up to this far i apologize this is a long video for that but i think you just keep on pushing stuff on a stack you see a full you pop you see a five no popping so you keep on pushing and then just simulate that way i am i don't know maybe today is just not my day uh or this week has not been my week but uh okay so again for lazy reasons i'm going to convert them into uh decks so we can just pop instead of using variables but of course this will add to the complexity which we'll talk about in a bit so yeah um so while pop i think to pop is greater than zero so we want to make sure that for every character that we pop uh yeah oh actually i guess this doesn't have to be no it's fine though yeah okay actually i guess this one didn't have to yeah it's fine because this could be a full loop fine let me do it that way then um for x and popped we want to get from push while we can right while uh push of zero is not x we append it we append uh push to zero and then push up uh push dot pop left right so then we keep on going until this is true okay and also length of push is greater than zero um now let's say that they're they are equal to zero then well we can push that pop left or if length is pushed is greater than uh is equal to zero we return first otherwise we just pop left and we don't have to push it to the stack um yeah um well now we have to look at the stack first hmm right i am messing it up today okay so look at the you go one two three four or you four um yeah and you keep on pushing until it is in the stack otherwise yeah i think this is roughly what um and then the next number is yeah if x is equal to stack of negative one the end of the stack and the length of stack is greater than zero uh stack dot pop and we continue because then we just go on um okay otherwise if we're able to go for every number then we are done uh is this right okay i mean this is correct for this so let's give it a submit it's cool yeah so i don't know i think i was just a little bit i don't know and again for this you can just use the pointer to keep it in all one and if you um however it's still going to be all of uh and space because we have a stack right here um can you use an impressive stack not easily because then you have to point to the i mean so you could if you're able to modify the input you can do it in place i guess with no extras with or one extra space um but otherwise since that's not you know you could implement the stack on top of pushed the variable but since we're not going to ignore that uh this is going to be off and space because we have a stack and off and time because well we just go further away and for each number and popped uh we either push or pop each number and push once so that means that for each number here we're going to use the stack once and for each number and pop which is only going for it once right so dim though uh and they both are length and so it's gonna be off and length uh even though it looks like an n square looped uh you have to advertise the time average it out so that you know that each item here looks gets looked at once each item here gets looked at once so as a result um it's n plus n which is all of n um cool um i'm gonna cut it short today uh or as sure as i can because i need i'm i uh not feeling well so hope y'all do okay and i will see y'all tomorrow bye
|
Validate Stack Sequences
|
smallest-range-ii
|
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._
**Example 1:**
**Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\]
**Output:** true
**Explanation:** We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
**Example 2:**
**Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\]
**Output:** false
**Explanation:** 1 cannot be popped before 2.
**Constraints:**
* `1 <= pushed.length <= 1000`
* `0 <= pushed[i] <= 1000`
* All the elements of `pushed` are **unique**.
* `popped.length == pushed.length`
* `popped` is a permutation of `pushed`.
| null |
Array,Math,Greedy,Sorting
|
Medium
| null |
1,750 |
hey guys welcome to a new video in today's video we're going to look at lead code problem and the problem's name is minimum length of string after deleting similar ends so we given a string s which consists of only characters a b and c you are asked to apply the following algorithm on the string any number of times so we have to pick a non-empty prefix from the string pick a non-empty prefix from the string pick a non-empty prefix from the string s where all the characters in the prefix are equal we have to also pick a non-empty suffix from the stringers non-empty suffix from the stringers non-empty suffix from the stringers where all the characters inside that suffix are equal and now both the prefix and suffix should not intersect at any index and also the characters present inside the prefix and suffix must be same if these conditions satisfy then we can delete prefix and suffix from the input string s and we can apply these steps any number of times so all these five steps constitute one number of time and our final task is to return the minimum length of string after performing the above operations any number of times you can also perform them zero number of times so let's take a look at these examples and see how we can solve this question so let's take the three examples the first example we have to implement the five steps so prefix is the starting part of the string so we can consider this as a prefix or the entire thing also as a prefix and suffix is from the end so this is a suffix and the entire thing will also be a suffix now we have to pick prefix and suffix and both of them should not intersect and the characters present inside prefix and suffix should be the same so since we have to deal with both ends the idea which comes into your mind is to place two pointers in the starting and the end let's take the first example so start is in the beginning and end is in the end and now I'll consider this as the prefix and this as the suffix both the characters are same no so we can't move forward and we end the iteration we can't delete them so we end the iteration and what is the length is equal to end minus start so this is the index position end + one end this is the index position end + one end this is the index position end + one end minus start end is at one and start is at0 0 + 1 is equal to 2 so 2 is the at0 0 + 1 is equal to 2 so 2 is the at0 0 + 1 is equal to 2 so 2 is the length of the string and that string is c a so 2 will be your output now let's take the second example so start is in the beginning and end is in the end now we have to check if both the characters at start and end are same yes so don't delete them we just have to find the final length right we just have to move the pointers so ignore this only check if the characters are same so we checked these condition both the characters are same this condition is satisfied now we have to check if the characters in prefix and suffix are same so we move the pointer so our task is to move start will move from left to right and end will move from right to left so until start is less than end we keep iterating now we check if we can still move start so we check this character and this character both are not same so move forward now again check if end and this character are same no both are not same so move end forward now again we have to check if these two characters same so start with this condition first yes both are same now we have to check if you can still move start we check these two characters both are not same so now we check if this and this are same so they're not same so end is moving forward now we again check if these both are same yes now we check if start is equal to these two characters no now we check if this and this are same no so end will move forward now we check if these two characters are same yes so start will move forward and end will move here so now as you can see here this condition is failing start has crossed end so we end the iteration and now we have to calculate the length is equal to end minus start + 1 length is equal to end minus start + 1 length is equal to end minus start + 1 so calculate the index positions first so end is at 3 and start is at 4 + 1 is so end is at 3 and start is at 4 + 1 is so end is at 3 and start is at 4 + 1 is equal to 0 so 4 - 4 is equal to 0 so 4 - 4 is equal to 0 so 4 - 4 is equal to 0 so length is 0 so it means we deleted all the characters and the final length is zero now let's take this example start and end now what is the current character we check with the beginning CH is equal to a now check if start and end are same yes now we have to check the prefix if we can still move we check if this character a is still equal to the character which we are comparing yes so move start forward now we have to check if we can still move start forward start will move forward now we check if this character is equal to C no so we end the iteration now we have to check for the suffix now check if this character and a are same yes so move and forward now we check if this character and CH are same no so we end the iteration now take the current character where start is pointing to B so CH is B now check if start and B are same yes so move start forward now check again if we can move start check if C and B are same no so start will stop now we check if this character at end and CH are same because now we are checking for the suffix yes both are same so end will move to the left now check if this character and B C are same yes so end will move to the left now check if this character and CH are same no so end will stop now this one was the first condition to check right in every iteration we are checking if first start and end are same only then we are checking this condition second and this condition third so first this condition is only failing because start is pointing to c and end is pointing to a both are not same so first condition is only failing so end the iteration Now find the length is equal to n minus start + 1 so end is equal to 5 and minus start + 1 so end is equal to 5 and minus start + 1 so end is equal to 5 and start is equal to 3 + 1 is equal to 3 so start is equal to 3 + 1 is equal to 3 so start is equal to 3 + 1 is equal to 3 so length is equal to 3 and what is the length is equal to b c a now let's implement the same steps in a Java program coming to the function given to us this is the function name this is the input string is given to us and the return type is an integer and that return type is the minimum length of s so let's start off by creating the two pointers start and end start is going to be pointing at the zeroth index position and end is going to be pointing at the end of the array now we have to move the start pointer and the end pointer start will move from left to right and end will move from right to left so using a y Loop until start and end don't intersect so until start is always less than end and now we have to also check the characters pointing at start and end are same so we check if character at the start index position is equal to the character at the end index position so if this is the case now we have to extract the character so for example we are here we are extracting that character and we have to check if that character which we extracted is same as start and end so I extract a character CH which is pointing at the start index position now we have to implement this condition we have to check the prefix so prefix is being pointed by the start index position so until the start is less than or equal to end you keep moving forward and now we have to compare this character which we are currently pointing at if it is same as the character pointing at start so if s do carat of start is equal to the character which we're currently pointing at CH then we have to keep moving the start pointer so this is a while loop right so start will keep on moving so here as you can see first we are going to compare if these two are same yes these two are same so start is here and end is here yes both are the same now CH is also the element pointing at start right because we are pointing at the start so we are comparing if start is pointing at the CH yes a so move start forward now start is here check if start is still equal to CH yes so move start forward now check if B is equal to the character CH no CH was initially a now it B so we break the loop now we have to do the same for end so end will move from right to left right so until end is greater than start and the character pointing at end s do carat of n is equal to the current character only then we keep moving the end pointer to the left so this is a y loop again and we'll keep moving forward until this condition is same now outside this y Loop so finally let's take this example here you're left with this string so start is here and end is here now you have to find the length of this so the length of this is start minus end + 1 so to calculate this you have to do + 1 so to calculate this you have to do + 1 so to calculate this you have to do end minus start + 1 will give you this end minus start + 1 will give you this end minus start + 1 will give you this length + 1 because of the index position length + 1 because of the index position length + 1 because of the index position so we have to return the Min length so I calculate the length let me name it Min length so it will be equal to end minus start + one and finally we're going to start + one and finally we're going to start + one and finally we're going to return Min length now let's try to run the code the test case are being accepted let's submit the code and the solution is accepted so time complexity of this approach is of n because we're iterating through the input string one by accessing all the characters present inside the input s and the space complexity is of one because we're not using any extra space to solve this question that's it guys thank you for watching and I'll see you in the next video
|
Minimum Length of String After Deleting Similar Ends
|
check-if-two-expression-trees-are-equivalent
|
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times:
1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal.
2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal.
3. The prefix and the suffix should not intersect at any index.
4. The characters from the prefix and suffix must be the same.
5. Delete both the prefix and the suffix.
Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_.
**Example 1:**
**Input:** s = "ca "
**Output:** 2
**Explanation:** You can't remove any characters, so the string stays as is.
**Example 2:**
**Input:** s = "cabaabac "
**Output:** 0
**Explanation:** An optimal sequence of operations is:
- Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ".
- Take prefix = "a " and suffix = "a " and remove them, s = "baab ".
- Take prefix = "b " and suffix = "b " and remove them, s = "aa ".
- Take prefix = "a " and suffix = "a " and remove them, s = " ".
**Example 3:**
**Input:** s = "aabccabba "
**Output:** 3
**Explanation:** An optimal sequence of operations is:
- Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ".
- Take prefix = "b " and suffix = "bb " and remove them, s = "cca ".
**Constraints:**
* `1 <= s.length <= 105`
* `s` only consists of characters `'a'`, `'b'`, and `'c'`.
|
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
1736
|
55 |
all right this lead code question is called jump game it's just given an array of non-negative integers you are initially non-negative integers you are initially non-negative integers you are initially positioned at the first index of the array each element in the array represents your maximum jump length at that position determine if you're able to reach the last index so the first array is 2 3 1 4 and the output would be true because there is at least one path that could get us from the beginning of the array to the end one of those paths would be if we only jump one position from here so now we land on the number 3 and from the number 3 that gets us all the way to the end of the array for example 2 the output would be false because there is no way to get from the first position to the last we always get stuck at the second-to-last position and stuck at the second-to-last position and stuck at the second-to-last position and we'll solve this problem using the greedy approach all right so when I first saw the examples in this question I saw that in the top example we could get to the end but in the bottom we could not the main difference is that in the bottom example we can't reach the final index because when we get to the second-to-last index we don't have any second-to-last index we don't have any second-to-last index we don't have any steps we can take because it's the number 0 so my first thought was why don't we just look for the number 0 if it contains the number 0 the answer is false but if it doesn't the answer is true but then what if we come upon an array that looks like this in this example there is at least one 0 so using my previous logic I would think that we could not reach the end but what about this path we're at the 0th index and were allowed to take two steps that would indeed get us to the end so using that we know that just checking for zeros is not the appropriate criteria so another approach we might take is to just check every permutation in the array so doing that we would do something like we start the first index and we go the maximum number of jumps so 1 2 3 but now we're on the number 0 the number zero is invalid because zero means we can't take any more steps and since we're not at the end that means this is not a valid path so then we'd have to start over and say well instead of taking the maximum number of steps which is three why not take two so we take two steps and we'd end up at the number one all right so we have one more step to go from one we go to zero and now we're blocked again okay so now we'd have to start over again let's not take three or two steps let's take one so we start at the number three and we take one step that puts us at the number two so now we can take either two steps or one let's say we take two steps that's not a valid path because again we're at the number zero instead let's take one step that's valid so far because we're at the number one but since we're in the number one the maximum number of steps we can take is one but now we're again at the number zero so none of these paths are valid as you can probably tell by now this is not the most efficient solution we've checked each number multiple times so we've checked the number three one two three times we've checked the number to about four times which is about the same number of times we've checked the number one this is not a great solution because this leaves us with a worst case time complexity of N squared this means that we may check every index in the array n times there are five indices in the array and we might end up checking each of them five times that's not very efficient so is there a way to check each index only once instead of starting on the first index and seeing if we can arrive on the last index why not start at the last index and see if we can arrive at the first one we're basically saying if we're on the last index can we get to the last index well of course we can if we're already there of course we can get to it doesn't take any steps at all now we look at the indices to the left of this and see if there are any that have enough steps to get us back here if there are any and I know in this example there aren't but let's pretend this one could get us there then this one would become the new target index our goal from that point would be to look to the left of this and see if there are any numbers to the left that could get us back to this point and our hope would be that we eventually end up at the first index if we get to the first index it means we have found a path that we can take to go from the final index to the first one so what we're essentially saying is this given a target index what is the leftmost index that can get us to that target index so let's say we're at the final index this is our target index if the leftmost index that can get us there is this one now this is the target index so the question again is what is the leftmost index that can get us here so let's say the leftmost index that can get us to that point is here the question again is what's the leftmost index that can get us here let's say this is the leftmost index if that's the case we now know that there is a path that can get us to the first index to the last that's because we know that this index can get us to this index and this index can get us to the very end all right so how do we actually know what the leftmost index is that can get us to a target index well let's say we're at the first index which has the number 4 and our target index is the final index can we get there the answer is yes what you're actually doing is taking the index you're on which is index 0 and seeing if you can get to the target index which is index 4 so you're actually doing some math there you're saying I'm on index 0 which has the number 4 so 4 plus 0 equals for now can I get to the target index which is again the index floor well we know that we can get to it because this number is greater than or equal to this number so we're checking to see if the index were on plus the number it contains so four plus zero we're seeing if that's greater than or equal to the target index which is four in this case it is if the index were on instead had the number three could we get to the final index three plus zero which is three is less than the target index so it cannot get there you can only go one two three to the second-to-last index all right so let's second-to-last index all right so let's second-to-last index all right so let's use the first example that we were given in the question at this point our leftmost valid index is here that is index four all right so now we're on index three from index three can we get to index four well for an index three it contains the number one it's 3 plus 1 greater than or equal to our target index which is four yes it is so this is also a valid index so with that we know that our leftmost valid index at this point is index three so now we're in index 2 and we ask the same question can we get to index 3 well 2 plus 1 is greater than or equal to the target index of 3 so yes this is another valid index at this point we know that our leftmost valid index is 2 so we'll update it now we're in index 1 can we get to index 2 well index 1 plus the number it contains is indeed greater than or equal to the target index so this is also valid let's update the leftmost valid index to 1 now we're on the final index from index 0 can we get to index 1 well 0 plus 2 is greater than or equal to one so yes this is valid so the leftmost valid index is index 0 all right so now we know that we can get to the last index from the first one we can get to index 1 from index 0 index 2 from index 1 index 3 from index 2 and index 4 from index 3 and let's just do one more really quick example just to make sure we understand so the array here is 2 0 we know at this point the leftmost valid index is index 2 so you move over to the left one is this a valid index can we get to index 2 from index 1 well 1 plus 0 is not greater than or equal to 2 so this is not a valid index let's move over one more at this point our leftmost valid index is still index 2 on this index our question again is can we get to index 2 from index 0 well index 0 has the number 2 which is greater than or equal to our target index which is 2 so yes this is a valid index and since our leftmost valid index is index 0 we know that we can get from the first index to the final one all right let's get to the code well each code has given us is a function called can jump which accepts an argument gnomes and numbs is the array that we want to determine if we can get from the first index to the last all right so let's start off by creating the last valid index variable so we'll say let last valid index equal gnomes dot length minus 1 so we're saying at the beginning that the leftmost valid index will be the final index in the array so last at this point will be index 2 because this has the indices 0 1 & 2 all right now we have to iterate & 2 all right now we have to iterate & 2 all right now we have to iterate over the array from right to so we'll say for let I equal numbness one go until we get to the first index so eyes greater than or equal to zero and then I - - then we need to check to and then I - - then we need to check to and then I - - then we need to check to see if the index were on is the leftmost valid index so we'll say if I plus nums I is greater than or equal to the last valid index then we need to update the last valid index to be the index we're on so that will look like this it will add the index which is I to the current number which is zero and see if that's greater than or equal to the last valid index in this case it's not so it goes on to the first index at this point it adds zero plus two and checks to see whether or not that's greater than or equal to two and it is so then it would update the last valid index to be zero so now all there's left to do is to return whether the last valid index equals zero all right let's run the code see how we did all right looks good let's submit all right so our code was faster than about eighty percent of other JavaScript submissions as usual the code and written explanation are linked down below in the description below you'll also find other resources for algorithms see you next time
|
Jump Game
|
jump-game
|
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position.
Return `true` _if you can reach the last index, or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** true
**Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[3,2,1,0,4\]
**Output:** false
**Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 105`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
45,1428,2001
|
1,921 |
Problem of the day of Hello Lit code is medium level question of Eliminate Maximum Number of Monsters. In this we are given two arrays of distance and speed so basically what is saying in this is that one is playing a video game and both the arrays are Each monster has a whistle. The distance array of the monsters is denoting the distance of the monsters from that whistle. This is the distance of the monster from the city. Like if we see in this example, if we talk about the first monster then it is 1 kilometer from the city. This distance is given in kilometers, so the distance of the first monster which is from the city is in kilometers and the speed of the same monster is in kilometers, so what is happening in it that you have a weapon, you have to move away from the weapon. How many maximum monsters can you kill? Count them and tell how many monsters you can kill. So what is the first one? Like in this example, if you look at the first one, then what is the distance in kilometers and yes, one point. And that is, after every shot, the weapon and pod gets discharged, it will take you a minute to charge it, which means it will take one unit to fully charge, so now let's talk here like 1 kilometer is 1 kilometer distance. And if the speed of our unit is one, then it means neither kilometer nor not, so what will happen in the beginning directly, what will be the charge, then what will happen in the other unit after eliminating this one unit, our distance is but one. If one minute of time passes then its distance will become ours, still if it is still far from us then we can kill it by charging it and at that time what will be the distance of either ours or the third monster, how many kilometers will the time pass like. As time goes by, the muster will come closer, yet Y is still kilometers away and its speed is KM, so according to this, if we could kill all three of them, if we could kill all three, then what could be its approach? Approach or toy, you can find it either like this that every time you hit a monster, update the distance of the array in the distance array and keep checking every time where the distance is becoming zero. So where our distance is becoming zero, what will we do with the weapon charge there, will we lose it or what will we do, we will find the distance of all the monsters, sorry, we will find the time to reach of all the monsters so that we can reach from CT city to city. How much time will it take and according to that we will keep checking all the things and see how many monsters we can kill where our condition will be this time to reach if we have time to reach if it is greater then it will always be greater as long as it is greater it means this That is, we still have a lot of time to eliminate the muster, so what do we do when we find it? First of all, what do we do? First of all, we will write down and first take its length. Okay, what is the distance of both the arrays, sorry, the size is there, both are equal. It doesn't matter if we find out the size, it will work. Dot length, after that we will make an array. By doing time to t, it will take time to reach. Let's make a monster city and what will be its size. Our distance is equal to that. Now what will we do in this, we will calculate the time of all the minutes. Okay, now what will we do? Time T Time U Ch I Time U Kya Distance Sorry Time Se Distance Apne Speed So what will we write Dis I Divided Speed So what will we write Dis I Divided Speed So what will we write Dis I Divided by Divided Speed Aa This value will come What will come If the fire is in double then first of all, what will we do by converting it into double and type cast it as double and what will we take from it, we will take the selling value, it means no, take this and after that, take this, now what has happened to us, every monster? What will we do now, we will shorten it so that the time of the monster is the shortest, what will we do first of all, if we kill it, then we will shorten it at the time to reach, time to time two. What will be the one who will take the least time to reach the whistle? So if we kill him first then we can kill the maximum. Otherwise we will keep killing anyone at random, then anyone from anywhere will be whoever and will be whoever is the maximum. If there is less time that means it is taking one minute, then first of all we will kill it, then in this way, we will do it, after that, now we will put a count variable, how much count, net monster eliminate, how much percentage, we will keep it at zero , time charge, this is also ours. What will happen, if it is more than this, time to reach means that we have to charge the weapon. Our minister is taking more time than it is taking to do it, then we will not be able to do the task and what will we do after killing one, we will make both of them count plus, make both of them plus from here, plus or minus. If this does not happen, if this does not happen then what will we do in check and lastly what will we do in counting the total minute count net. Once again let us see that first of all I have taken the distance size and then an array. We made a list of all the monsters which monster is taking how much time to reach the CT, after that we sorted the array and by doing this we found out which monster is taking the least time. First of all, we killed it and then we controlled it. We will keep on hitting the apple and it will keep on increasing and the count of our total time taken to charge will also keep on increasing. Then we again put a loop on which we checked that the time to reach the destination is more than the charging time. So we will be able to kill him. Arwaz will not be able to kill the monster. If we are able to kill him after time to charge weapon and then we will increase the count. If we are not able to kill him then we will lose on Y and will break B and B will come and last. What is our chance? We have to return whatever we can net. Ongoing Accepted Tire
|
Eliminate Maximum Number of Monsters
|
eliminate-maximum-number-of-monsters
|
You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute.
You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start.
You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon.
Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._
**Example 1:**
**Input:** dist = \[1,3,4\], speed = \[1,1,1\]
**Output:** 3
**Explanation:**
In the beginning, the distances of the monsters are \[1,3,4\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,2,3\]. You eliminate the second monster.
After a minute, the distances of the monsters are \[X,X,2\]. You eliminate the thrid monster.
All 3 monsters can be eliminated.
**Example 2:**
**Input:** dist = \[1,1,2,3\], speed = \[1,1,1,1\]
**Output:** 1
**Explanation:**
In the beginning, the distances of the monsters are \[1,1,2,3\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,0,1,2\], so you lose.
You can only eliminate 1 monster.
**Example 3:**
**Input:** dist = \[3,2,4\], speed = \[5,3,2\]
**Output:** 1
**Explanation:**
In the beginning, the distances of the monsters are \[3,2,4\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,0,2\], so you lose.
You can only eliminate 1 monster.
**Constraints:**
* `n == dist.length == speed.length`
* `1 <= n <= 105`
* `1 <= dist[i], speed[i] <= 105`
| null | null |
Medium
| null |
443 |
Hai gas welcome and welcome back to me channel so today our problem is sting compression so what is given in this problem statement, you read it once and understand what is the problem statement. If you still do not understand then no problem we What will we do with this problem? Through the example, we will understand what is our problem and how can we solve it. Okay, so what have I done here, sir. I have taken an example. What do we do? If we understand it through the example, then we will see ourselves here. What is given, one character is given, okay, what do we have to do with it, basically, if we have to compress, then how will we do the compression? So here you see, what is there in this, whatever characters have been given, it is repetitive, right, it repeats. BB is getting repeated, when is it getting repeated, right, so what do we have to do with it, do we have to compress it, how to compress it, then what is its count, only one here, you are looking at 2, how much is B's, you are C's. How many is 3 right then how can we write it A Tu B Tu C Tu Basically what we have to do is to compress it and what will be its size we have to return it and give it in the answer so what will be the total size here 2 + 2 + 2 what will be the total size here 2 + 2 + 2 what will be the total size here 2 + 2 + 2 Total is six, so if six is here then Total is six, so if six is here then Total is six, so if six is here then these 6 have to be donated along with the sting, neither is she an actress, nor is this also to be given by motivating it is to be given in this form, it is okay if here. In your example, A Rahat B Rahat C Rahat is only in the character of Are, what is your relief, these are the three elements, so here you are seeing that A is account one, B is one, C is one, so we do not need to write here one. How in this, if the account of any of our characters is one, then we will not have to write it like A1, do not write b1, do not write C, don't write C, okay, we just have to return ABC here and its How much size to run? Three means what do we have to do with our character array of characters? Convert it to ABC and what will be its size. Here it will be one because its frequency is one. We will write A1 otherwise what do we have to return here only one. If you want to return, then here you will do only one turn. Now look here you have given only one frequency one and the frequency of B. What is the total? 12. What is the frequency of B? 12, so which we are here. We will modify this, wo n't these characters? How will we modify this AD? We will not write 'Van' of 'A' because not write 'Van' of 'A' because not write 'Van' of 'A' because we do not need to write 'Van', in the case of 'Van', ' we do not need to write 'Van', in the case of 'Van', ' we do not need to write 'Van', in the case of 'Van', ' A' today it will remain 'B', we will write 'B' and the A' today it will remain 'B', we will write 'B' and the A' today it will remain 'B', we will write 'B' and the frequency of 'B' is 12, so we frequency of 'B' is 12, so we frequency of 'B' is 12, so we We don't have to write 12, we don't have to write in the form of one element, we have to compress it too, so how will we compress it, we will write it differently, you will write it differently, okay, so in this way, what you have to do is to give it by turn, so I hope you understand. It must have been that the problem is that we basically have to see the count of all the characters and compress it. Okay, so here you are seeing what is its size, has it been compressed? What was its total size? 2 Here The total was 7 but what have we converted it to? The total size has been converted to six. So here, in this way, you have to modify this factor, these characters also, what you have to do is to return the size which is final, you press [ __ ]. We have to size which is final, you press [ __ ]. We have to size which is final, you press [ __ ]. We have to return its size and after modifying it, now how will we solve this problem, so now we understand how we can solve this problem, so what you are getting here is that you have to account for all the characters. Keep in mind, right, so what we do is first volume, let's solve it with extra space, then without extra space, we will see how we can solve this problem, so we will just do a little teenage, we will first look at space together. Okay, so you are getting the question here, you will definitely have to count here, you will have to count everyone, so what you have to do is to take a variable, so what do we do, let's take the Kant variable. Okay, this is the initial one. We keep one because yours is a constant, what will happen to you from one to 2000, then one will definitely be yours, okay, so you take one here, count ok, you have taken it, now what do you do? Answer Name What will we do now? We will also modify it, we will keep it here, then we will assign it here, we will know, okay, so now we will pay here, will we start from the count van and take a loop from here, okay from here, we will start from this van 1 2 3 4 5 6 Which is our look, it will last from the van till where will it burn, it will last till the intake, okay, it will last till 7. Now what will we do, look here, what will we basically do, we will compare from here, is this equal to the previous element? Is yes A, this is equal to A, so what will we do with the count here, you will do it, okay then we will move I, we will come here, bring the icon on you, so we will check whether these two are from the character, what do you mean? The character which is there in the pay index and the character which is in the van index, is it from both or is it from neither? So what will you do now? In this condition, here you will check that the value of your account is how much till now and how much account has been withdrawn. The value of your count is here, that is, it is > 1. is here, that is, it is > 1. is here, that is, it is > 1. Right, whenever we give a greater van, only then what will we do, we will sign it with a tractor, otherwise what will we do here, science, we have come here, I have come here, we have a So we have to do it for this, we have to do it for A first, so I - 1, insert it first, so I - 1, insert it first, so I - 1, insert it here, inserted A to 1 and what is its count, the count is yours, if you are here, then you What to do if there are more than you in it, if 1 is digital then it is true that 1 is digital, so today we will insert this and this here, after changing it you will insert it in this, okay you have inserted all these, now you are here. Right, now you will come here again, what do you have to do with the account, okay, you will compare it with its previous character, are these two equal, are they equal, then what do you do with the case, then you do it, you did it, then you are here. A will go to this character. If you go to A then compare whether both are equal or not. If not equal then now we will see the count. Is ours greater than one? Is yes ≥ 1 ours greater than one? Is yes ≥ 1 ours greater than one? Is yes ≥ 1 then what to do. Right now you are on this index which is in the previous index. The character is there, insert it here right and what is its count. This is your WAN digital, so next to 1 digital, we will insert it here. Okay, now we are here, we will proceed here, now again link these two accounts to WAN. We will do it, we have done it, now what will we do, will we compare these two, is it equal, then do this again, you do this, then you will come here, then you will see whether these two are equal, yes, if they are equal, then here What to do, now make it three, okay then if you come here, then tomorrow you will not get it, we will not even check for this, so see what we will do in this way, we got our account 3, now what will we do here We are fine, our A here must have been done, now what will we do here, we will see which C is on the previous tractor, then we will take C here and what is its account, it is of Van Digital, so we will insert three on here. Look, now you must be thinking. Why did you bring Aai here you have got three accounts, so I will tell you a test case, okay, then you will understand why we are doing this, so in this case, whenever you check your account, people will Is the size of character 1, is it WAN, then simply return WAN because there is no need to modify it, its size is the same and when you will make notification, it will be the same, so why should we do so, then in this condition you simply check. Tax people, if the size of cactus is 1 then look at it upside down, now look for it, you know for it and B's is 12. Okay, so here you start counting from one. Okay, so here is the account, is it not equal, then what is here? Account, what is its count, here you have got only one, so in this method, what you have to do is not to insert integer. In this method, you only have to insert the character which is on I-1, you only have to insert the character which is on I-1, you only have to insert the character which is on I-1, no wait. We have to do it because we don't have to do it in the first one, so it's done, now we will increase I here, so you know, count again by one, people, you are okay, for now you are watching, so what will you do here. You will compare these two, they will be equal, yes, you will do the same, then you will come here, are both equal? Tax people, then you will come here and see what is equal, six tax people, then you will come here, you will see that it is equal, 7 tax people, then you will come here too, look, it is equal, tax people will come like this 9, 10, 11 and here, 12, what is yours? 12 is digital, then what will we do? First of all, we will change it into a string and select one character at a time, here we will select so van, then we will insert van, then we will place this tu here, so what we will do in this way is this. The answer is this vector which we have created, we will take extra space and what will we do with it, we will sign equal to this cactus, okay, what will we do with this, we will give the answer, look, you have been modified, now we will modify it, okay and We will return its size, what will it be if it is four, then make it 4 meters, because your function is not of waiting type, so what do I do, I show you four, then we will see the extra without extra space, just a little. You will have to make some changes, okay, so we are ours, look at what we have done here, look at us, wait, look at what we have to return here, we have to compress the original as well, okay, so return type here will be waiting for you, but You have to compress also, you have to keep this in mind, so let's take count one, take a testing answer or take a vector, both will work, okay, so here we have taken this, I have taken the sting, so what will we do here? Where will we start the loop, we will start from one and how far we will go, okay here, after that what we will do is check here i, now connect it, dot should be of size and cactus i = = = i - 1, so Do count plus. Okay, i - 1, so Do count plus. Okay, i - 1, so Do count plus. Okay, this way your less plus will keep on increasing as long as you keep getting other vice. Now you will see if its count is one then how to convert it, what do we have to do, we just have to insert the character, so where do we have to insert the character. Rectangle of rectangle or rectangle of rectangle-1 Rectangle of rectangle or rectangle of rectangle-1 Rectangle of rectangle or rectangle of rectangle-1 because what is the meaning of rectangle page that you will go that yours will not be equal, so for the previous one you have to insert right, first we will do i-1, okay right, first we will do i-1, okay right, first we will do i-1, okay what will we do after that. If our count is > 1 then what will we do after that. If our count is > 1 then what will we do after that. If our count is > 1 then what do we have to do in it? We have to insert the count along with the tractor, then we will first set the curtain and first change the count in string, we will change it in string and then one- A we will change it in string and then one- A we will change it in string and then one- A character which is a number in our string may have changed, if it has multiple digital then what will we do. We will consider the multiple digital as capital and insert it. So here what will we do in the answer and each digital character. After making it, we will insert it in it, okay and again we will sign the count van because now for the new one, you will do it, then the count should start from van, either keep it here or keep it here, both the things will be equal. Okay, now what you have to do is to modify the cactus, you have just created the answer, if you have not modified your character, then what will you do? After modifying the blue people and characters, the dog is an actress, I requested you will answer and here finally you If you return the answer dot size, then yes, it will be submitted, but here in the description, what you have to do is to write such an algorithm in which you have to do constant extra space, do it, then there is nothing in it, just we point it. Okay, so what will we do in the semi characters, aroma, we will do the modification, whatever, let me show you, how will we do that modification, okay, how will we do the modification, how will we just make a slide change in the code, whatever we will insert there in the head. Now we have to do it in the actress only, we just have to keep in mind that where we have to insult, okay in what way we have to do it, so look, okay, we are storing the right in the answer, we do n't have to give an answer, we have to do modification in this cactus. If we have to do this, then what will we do? Okay, now whatever we are taking from the for loop, we will start from here and compare, what count do we have to take, what are you reducing from, you have to take the count van. And what do you have to do here, you have to compare these two, if the comparison is equal, then what will be your count, here you will be counted, now if it is not equal, then for A, we will have to do the same for one, so what will we do at zero? What will we do? This will be equal to this. What will we do here? You are here. For one, if you want to do a notification, then A, you will do it inside. Okay, look, you will do it inside on this eye, that is, here you will have equal. Not found till here you have got the count. For the first one you have to do so only in characters. What we will do at this place is we will insert a and what we will do at the next index will see the count is ours ≥ 2 is yes the count which is ours. ≥ 2 is yes the count which is ours. ≥ 2 is yes the count which is ours. ≥ Sorry, there is a van, so what will we do, we have to ≥ Sorry, there is a van, so what will we do, we have to ≥ Sorry, there is a van, so what will we do, we have to insert its count here, so what will we do in place of this A, we will insert the count here, that is, A will be here and this will be here, okay, now where is yours? A will go here, what will you do now, I will come here, yours is fine, what will I do, I will count both of them, there will be van for B, who will be Suman first and when it comes here, both will get equal then What will he do here, you will count, you have counted, then what will happen here as if you have counted, now when he comes here, what will he get, if he will not get equal, then for this you have to insert for B and yes, we have you. You know that 'A' has already been and yes, we have you. You know that 'A' has already been and yes, we have you. You know that 'A' has already been here. Okay, 'A' has been here. So here. Okay, 'A' has been here. So first of all, what will it do in place of If we insert the value of I - 1 here then it will value of I - 1 here then it will value of I - 1 here then it will become B and move forward to K. If we want to count I here then what will we do to count Tu here at this place. You will do the count, okay, now I have come here, our account will start again from the van, okay, now what will you do here these two, you will count, you will get equal, you do the account, people, you throat, you have done it, then you will come here again. Then you will get account three, then you will come here. Okay, so your this is over, so what do you have to do on this and here you have got three, so what to do with three, here you have to insert it. Okay, but it will not be removed from here, there is no need to remove it from here, it is this far, so what you were expecting, a2b2 c three, this is till now you have freed the body, so if you take the size here till six, then the answer is Okay, that's it, let me explain you a little about this example. Look, yours will start from zero. Yes, yours will start from zero. Now you are starting to count from here, this index. From here you will see that you also have to start the count from the initial one, right from here you will see, okay, it is not equal, no problem, so what will you do now, you will see what is your count, so what you have to do in this method is integer. So you don't have to insert, so what will you do in this will be the value of i minus van i.e. you are value of i minus van i.e. you are value of i minus van i.e. you are here, what will be the value of i - 1, here, what will be the value of i - 1, here, what will be the value of i - 1, what will be the value of this one, this will be a, so you will do this at zero, which is the same. It will remain the same, do it again, to tell you, I am telling you, so it will be here, now this is your van, where has it been on the van, now you will come here with it, okay so here. Again the count will start from your van, so you will be equal here, where will you be van, then your I will increase here, you will become three. By doing this, you will keep consolidating by doing like this, if you go till A, then what will be the count, you will get total 12. Okay, now look at your here, this is your here, okay, your van is here, so what will you do, insert the value which is on I - 1, i.e. insert this B here, value which is on I - 1, i.e. insert this B here, value which is on I - 1, i.e. insert this B here, then which is B. So we will let B stay here, now your count is 12, now you pick it up here and put it here, you will bring P, you will go to A, now this is your 12 account, now what do we have to do, 12 have to be considered separately. You have to consider it differently. You have to change the van by cutting it. You have to do it in the character. What will we do with this van? We will insert it here on this. Okay, then we will move K to here. We will bring K to here. We have brought K to here. This is three pe a gaya, now what will we do here? Okay, this way you have modified till this far, you have not done it here, so the insert return we will do will be four, so this is only from here till here. Consider it won't even look here, okay, so what will we do in this way, without using the accept space, we will modify the characters. Okay, so I hope you have understood this, so what do we do? Look, here is the code for it. Let me show you what we need, we will definitely take it and check here that if you have given a single value or you have given only one value, it is ok for that, after that yours is blue, see that it starts from van. And equals you are going up to the active dot size i plus now we will keep count van we are ok now what will you do here till you get equal count plus do i plus ok now on the plus of characters what will you do You will do Cactus I - You will insert 1. what will you do You will do Cactus I - You will insert 1. what will you do You will do Cactus I - You will insert 1. Okay, you have done it. If your count is ≥ 1, that is, whenever our count is wan for how many days, ≥ 1, that is, whenever our count is wan for how many days, ≥ 1, that is, whenever our count is wan for how many days, then we will have to insert its wait value also, not just how much is its grouping, then what will we do with that. First we will change the string and we will start inserting characters anime g plus in this string, whatever we get each actor, okay, so what will you let us do in this way because this is the size of yours as far as yours is concerned. This will go only as far as you need, you also need the right factors, if you return this then you can solve this problem in this way, so I hope you have understood this. If you like the video, then please like and share. Thank you.
|
String Compression
|
string-compression
|
Given an array of characters `chars`, compress it using the following algorithm:
Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`:
* If the group's length is `1`, append the character to `s`.
* Otherwise, append the character followed by the group's length.
The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`.
After you are done **modifying the input array,** return _the new length of the array_.
You must write an algorithm that uses only constant extra space.
**Example 1:**
**Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\]
**Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\]
**Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ".
**Example 2:**
**Input:** chars = \[ "a "\]
**Output:** Return 1, and the first character of the input array should be: \[ "a "\]
**Explanation:** The only group is "a ", which remains uncompressed since it's a single character.
**Example 3:**
**Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\]
**Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\].
**Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ".
**Constraints:**
* `1 <= chars.length <= 2000`
* `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.
|
How do you know if you are at the end of a consecutive group of characters?
|
Two Pointers,String
|
Medium
|
38,271,604,1241
|
301 |
I'm looking at it, and now let's take a look at the tender cer problem. This is a very difficult problem for me, but I'll try to raise it step by step. First, I wrote down what I know. 4 First, you will understand the problem. The input value is in the myth. Please tell me the problem. The hospital bed Zao is using. It is given as a combination of conditions. Among them, the parentheses have already been built once to create the bell id 1 combination. When that combination comes out, in all cases, the valley dan is blurry in nature, and most of the time, the legs are raised and s If you think that it was given this good and look at it again, the wall is now 1 inch wide on the right as a whole. That means that the right side is somehow erased and Felid 1 is talking about the table where those memories were made. If you get rid of the translation and get a job, this is a combination. This and this combination becomes a Billy combination. Then, it becomes a chicken compared to it again. Then, it appears for the second time. Let's try moving it to the right and erasing it. Then, the Chuhap becomes like this, and this also becomes a combination for Belly, so do one of the next ones. It can be done. And there are two answers. When solving this problem, I think there are two key parts. The first is how to judge whether the seed given as input is like this meli. The important thing is, the second thing is how to build it to create beautiful memories, or you have to erase one thing and consider it. We will look at how to do that. If these two things are solved first, the remaining 4 are the solutions that I want to find a solution to. I think there is a place to solve the problem. Then, let's take a look at how to determine that s is not able to do the Berith. First of all, the balance that is basically talking about fur is the number that represents the balance. bl is written without the human body tactic and the pass given as the input. When given like this, try random order with the index child. If it comes out on the left and , increase 2b by 1. If it comes out on the left and , increase 2b by 1. If it comes out on the left and , increase 2b by 1. If it comes out on the right side, this blood is 1. Thank you. And it is judged that it is 1 to 1 smaller than the salt of b. For example, child I'll add more. At first, it was Teo Myeong at the beginning of the week. I walked to the left. This seems to have come true. If you look at the entire stock price, it 's just one time. Since the left and right are paired, the variable goes into Byeongwoo. And when I often go like this, it says to go to the right, so if I take 's just one time. Since the left and right are paired, the variable goes into Byeongwoo. And when I often go like this, it says to go to the right, so if I take 's just one time. Since the left and right are paired, the variable goes into Byeongwoo. And when I often go like this, it says to go to the right, so if I take out one grain, it's all Bern. It becomes smaller. In fact, even if you look at this letter intuitively, it is judged to be difficult to read. The problem is that in this case, it has become so easy to open it and find out. It's me. If it comes to the left part, it increases again, and if it says to the right, it's 1. In this case, it's not smaller than Bern Yeom. So, you can't judge it by saying that this kind of cultivation power is heard? 4 Here, I have to use a little trick. I turn the s over once. If I do this, it's normal, but it's like this. If you flip it over, it will be displayed here once, and the current will appear to the right, and then the side will appear, and then the number will bounce as it is. Adapt the same algorithm to the reversed version, and judge the embedded valley once. For example, i'll start from here. But if it says slightly to the left, it increases the time, but this time, if it says to the right and , it increases the foot. Then it will be this time, if it says to the right and , it increases the foot. Then it will be like that. If it says to the left, then minus 1, it also comes in English, and this is what I made. It looks strange, but if it comes to the left, it goes back to the sky. Subtract. In this case, it is lower than the barrier, so it is judged that it is already high resolution. In this way, if you consider this at once, the overall enemy is smaller than the number multiple. If you judge that it is not pushed back, now the fourth mesh is The logic that can determine whether the first album is opened by listening to Imbelly is completed. Then, let's do that. After making the judgment, the meaning of this child is jig. Now, when you meet the subject of the first removal and the object of removal, stop looking at the air. When something has to be erased from the beginning again using a different index, you make that judgment and erase it, and now you keep considering it all. After erasing, the combination of the string is a pellet, no, how are you going to do it? How are you going to build it? As I said at the beginning, we will use the index number one more time. For example, let's start from the beginning with the child here, and we will also start with water. Well, since we used that boat earlier, there is no side. If we meet on the left, we will have 1. If we meet on the right, we will have something. Let's try it. If you do this, the ego will explode. Isn't it the left side? Yes, the right side is 0. But now - 1, so now the answer has already been answered. At right side is 0. But now - 1, so now the answer has already been answered. At right side is 0. But now - 1, so now the answer has already been answered. At this moment, the meaning of the right side and the child teaching is the object of removal. I am the object, so I have to erase this now. How should I give it to him? If you go around again and come across the same correct thing that this child is teaching you have to put it away and think about it again. If you start from the beginning with such a suggestion and come here like this, you have to erase it and think about it again. Put this away and ask again. If you multiply it and multiply it is the same. If we take it all away and pull out the rest, it looks like this. We looked at it before and we saw it. In fact, if you look at it intuitively, the valley is complete right now. Yes, but we don't end the judgment of the valley sweet here, so we have to turn it over and examine it one more time. Of course, even if you look at it intuitively without seeing anything. It'll be especially good when you turn it over. That's the answer in advance. So let's start from where I am. [ __ ], this guy isn't the target. Let's say the in advance. So let's start from where I am. [ __ ], this guy isn't the target. Let's say the in advance. So let's start from where I am. [ __ ], this guy isn't the target. Let's say the child is pointing. It's the same here. But this time, let's take this one out and consider it again, right? It has to be Illidan Yam. Deleting it in January is the same. Here, I expressed it like this again. Even if you intuitively open it, you say that you are shaking now. But it doesn't end there. You have to turn the example over and look at it again. If you just do it like this, it is the color of seaweed. Now, if you look at it in a position, you can delete one and see if you can hear the belly again. There was a second conversion during the luggage. So this time, based on the core algorithm that has been done so far, we will actually work on the problem for the first time and try to solve this problem. It's a complete search problem. So, we have to try all the cases, and what do we do in all cases? For each case, we have to search once for all the cases that can be created with our work, because it's not an index. So, it can be said to be a typical TEPS host installation. Let's define the defense parts of the couple's problem and try to solve it like a book. Then, you have to design the program first. Usually, in my case, I use search method 2 Dexter, so I write the name of the problem cleanly. I decided that there is nothing else to do with the L type voice. I am dragging the doll once. It is important to know how rock executives design, but it is important to say that it is a Jeju questioner. I am now a Weleda Zipel, and I have to judge the target prediction as the first pair of characters. You have to match it. Then, if s is done, you have to put it somewhere. Leave a list ring to actually store the answer, listen to the short answer, and as mentioned earlier, let's do a fancy walk with 2 indices. Then, how does the child's 9 body end up? I will receive the index for the third and fourth times as many as this, and the concept of reversing is now in, so I will increase the ban variable to Gwangwoo 5 b. You can turn it over, so you have to turn it over, right? 9 Solve it like this and make the blue design. When the actual woman is drawn out, how will the entire tree be drawn? I've drawn Mizel Cream, but Hyunseong is omitted here. I did it and it has been like this since it was published. df 3 Jesus string Now, each of these is different from talking about each other. This type of input appeared when I gave ms. stein is the first, so it comes in as 00. Then, I still turn on the flipping of the characters, so I concentrate when I'm there, so it's Dyne Seal. 9 Top PC That's it, then I will give you the stock price. So, when you give it to me, if you try 10 nations here for a moment, now with Si, if you go once like this for the first time, the comb chain that went to Air when you are looking for Sog Valley Diaz Botan Karon is 6 circulation from the beginning and is tired. Each part is positioned. Then, if you bring the offer to the first point, you have to consider it at 4 o'clock, excluding me. Then, again, with the defense high and charged, try to think of something. If you write it down here as well, the second evil is Hunt. The base is adjusted here, and the parent dfs above is a folded point that is missing two points. And the second is, if the second point is missing, it is given like this. Of course, going intuitively, the first baby is also given as an improvement. But here, the stars are displayed. I'm leaving Iago and giving my index to ancient times because there's nothing to look at in that condition and it means I'm going to come back here again and it's not overturned yet because I haven't found the thing that took me from beginning to end. 2 The diagnosis is the story here. When it is confirmed that there is no problem with s, it should be turned over. Until then, we will consider it again based on the glass diamond blast j. Then, let's take a look here. Now, the first suggestion was made by substituting it like this, excluding , and Now, the first suggestion was made by substituting it like this, excluding , and Now, the first suggestion was made by substituting it like this, excluding , and then it is the initial style. It's okay to brush it, but it's normal to check again here. I watched China from beginning to end with the child and there is no question. If so, you have to take a picture like this. Now, in the countryside, I'll do it like this, then recursively call my pass again and give dps. As for steel, you have to start from the beginning, so the area comes. Then, flip the P in C partition and come in. There was no problem doing this. Then, eat this again. If you walk this again and wear this again, it will become a pod, so add the fire star as well. It's the same here. Even if you use it intuitively, it's now the commissioner. If we had solved the pass on d here, there would n't have been a problem. Then, turn es over again and consider it, give it the same thing, and compare the right and left sides like this in opposite directions. Well, intuitively, there's no problem. There is no problem with this 4, so there is no problem with this either. Now, turn it over again and go back to the original. In the end, after receiving all of these, the 2-point hand is that the quarters in the dot square per time are the next week. Let's see. First of all, as a sub pro, I will write down what I said earlier during photo time. It will continue like this without any 5, star, 2, last sieve, 2, and 5. There is no need to squeak at the pie. In other words, first of all, there must be a list swing type encoder and on summit. Are you going to save that value? So, when you call the pass, you will give Jody news on the girl's wall. Then, write the correct answer and then the last scene of Castiel that you thought of at first is the hero. This is also the first time to start here, so if you really want to add a man to the left and the annex and not go up, you can cover the stomach, and the old greed ou seconds stout Then, now you have to turn off dfs, but this is the end of the batch marker cv side. It's usually ours. Guaranteed, this base is big, and I am going to law school, but this function is unusual in that it does not have this shape. The first thing to do is to do the other variable first. Then, using xi, a rope appears from esti to the end. The child starts by stopping alone. Ah, this sl xl is not possible. When the child is smaller than m, it is increased one by one until the end. There is now something in here that is causing a problem for the child. If you have found that right, do not call it again in here. I will give it in this blog, and then it is over. If you come out of this convex, it is an experiment that shows that there is no problem here. There is no problem up to this point, so there is no problem trying. But I said earlier that it will work, but if there is no problem with s, you have to turn it over and think about it again. I wish Iden Story was written in life because I died in the story field, and I will reverse the reverse recommendation like this. Sting is known, and that two sticks are unfair. If Mr. Grasping left and Tak, he did not lose Rouge, and now 4s are all 3. Isn't it the back of the yarn? Then we need to consider it one more time. Let's consider the SM that has been turned over. We can't, so we will consider it. It's true that rs5 is not big. Here's the Glaster from the beginning - g00 and then you are this important. SM that has been turned over. We can't, so we will consider it. It's true that rs5 is not big. Here's the Glaster from the beginning - g00 and then you are this important. SM that has been turned over. We can't, so we will consider it. It's true that rs5 is not big. Here's the Glaster from the beginning - g00 and then you are this important. DC is going. Jesus has changed Deb. When you go in, the story is about applying the core algorithm that we looked at the beginning. Please look back. But if Mr. Pi is not on the left, that story is because he received money in the pot and saw the reverse Dan S. It's back 5 and the tannin is no problem, so it's the answer. Then, the second house is the case, so the number came in at the beginning, so I'm going to turn it over again like this and congratulations. Now, I have to complete this part. The important thing here is to keep writing down the child until you find the lead. If you found the answer in advance, then now you have to use Yes, Pine Shana land 4 is a bit like that. But now, if you look at it as pie tc, it becomes a sashimi. 4 And if all of the berries were dark, then it is a court. Because coming here from below means that it is smaller than the area, so when you get indelivery, you always get it. When you find that right away, until the child has meat, he will be in a key position here. Koto will now be the place where this will be built and done. How are you going to handle it? Now, it will be a master, so it will be a short show. Because we use it and we are IOT, we can't attend the DPS subsidy here because Jay has to do something like a kid's baseball. But there is one important thing. For example, when I am here, I wear No. 2 and wear armor. Say it like this, but when I have one more job to do, if it says something like Jane Earth, there is no need to look at it. Because this is the same shape now, it has the same shape. Nowadays, this is the name of the country followed by the number. It is not the Koran, and should be considered only when the conditions are met. When? First of all, s j, the corresponding overwork will be # the same j, the corresponding overwork will be # the same j, the corresponding overwork will be # the same because you will try to do it. And 5 If this position is the same except for the rest, this is just a rest. The Empress's will now start at the beginning. When you really like it, there is no need to consider j-. is no need to consider j-. is no need to consider j-. Yes, so now you are just doing it, or you can get it in May and take a look at the seeds only yesterday. Then, I did it. Extract it. I also have to look at it if I don't have this power DC. It's a lot like that. Then, there is no need to consider it. Let's eat already. Since I've seen it, now it's done by me, so only if it happens like this, it's 9. 5 At this time, I'll forget it. In the case of Coral, um, if I have to delete the corresponding character of the second, I guess I lost. I feel like it's not a special feature of the software. If I do this, from there to j, now I'm indexing this. The current Nex Fendi index does not include the Ai went to Ai. I think immediately. Ta in #5 pot 50. Ta in #5 pot 50. Ta in #5 pot 50. It should be seen as a festival that made a small wall. And now it is being turned over, so if you do this, it means that you have found the age in the middle of the y-star sc le. It will be taken into y-star sc le. It will be taken into y-star sc le. It will be taken into consideration by leading from the state. If you do that, when the curse is leaked, a request will come here now. Now, since this context i j comes in, let's do one of them and consider it again. There is no need to look. Since we are already continuing from the call here, the Turkish detection is sufficient, so we only need to check it once. Here, we just have to cut off the lock, so we have to add Eri. Then, we can see that 4 because Billy's answer or sleep is. You have to search deeply until the build is reached and resolved. If you lose more heat here, you will have to look at the file again from the premise, and if there is no problem at that time, it will come down again and you should avoid that because what if you find something that is missing? This is the line here. You have to repent in the test first touch. Now the implementation is like this. You are looking at the game that you want to test once. It is true. 4 In other words, the answer came out, and once, two pockets.
|
Remove Invalid Parentheses
|
remove-invalid-parentheses
|
Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return _a list of **unique strings** that are valid with the minimum number of removals_. You may return the answer in **any order**.
**Example 1:**
**Input:** s = "()())() "
**Output:** \[ "(())() ", "()()() "\]
**Example 2:**
**Input:** s = "(a)())() "
**Output:** \[ "(a())() ", "(a)()() "\]
**Example 3:**
**Input:** s = ")( "
**Output:** \[ " "\]
**Constraints:**
* `1 <= s.length <= 25`
* `s` consists of lowercase English letters and parentheses `'('` and `')'`.
* There will be at most `20` parentheses in `s`.
|
Since we don't know which of the brackets can possibly be removed, we try out all the options! We can use recursion to try out all possibilities for the given expression. For each of the brackets, we have 2 options:
We keep the bracket and add it to the expression that we are building on the fly during recursion.
OR, we can discard the bracket and move on. The one thing all these valid expressions have in common is that they will all be of the same length i.e. as compared to the original expression, all of these expressions will have the same number of characters removed.
Can we somehow find the number of misplaced parentheses and use it in our solution? For every left parenthesis, we should have a corresponding right parenthesis. We can make use of two counters which keep track of misplaced left and right parenthesis and in one iteration we can find out these two values.
0 1 2 3 4 5 6 7
( ) ) ) ( ( ( )
i = 0, left = 1, right = 0
i = 1, left = 0, right = 0
i = 2, left = 0, right = 1
i = 3, left = 0, right = 2
i = 4, left = 1, right = 2
i = 5, left = 2, right = 2
i = 6, left = 3, right = 2
i = 7, left = 2, right = 2
We have 2 misplaced left and 2 misplaced right parentheses. We found out that the exact number of left and right parenthesis that has to be removed to get a valid expression. So, e.g. in a 1000 parentheses string, if there are 2 misplaced left and 2 misplaced right parentheses, after we are done discarding 2 left and 2 right parentheses, we will have only one option per remaining character in the expression i.e. to consider them. We can't discard them.
|
String,Backtracking,Breadth-First Search
|
Hard
|
20,2095
|
63 |
in this video we'll be going over the brute force recursive approach for unique paths too so a robot is located at the top left corner of a m times n grid marked start in the diagram so here the robot can only move either down or right at any point in time the robot is trying to reach the bottom right corner of the grid mark as the finish in the diagram below now consider if some obstacles are added to the grid how many unique paths will there be so we have the obstacle here this means the robot cannot step into the cell with an obstacle and space is marked as the one and zero respectively in the grid so the obstacle is going to be a one and any of the other cells is going to be equal to zero so in this case we uh we have to find the total number of unique ways to reach from the top left corner to the bottom right corner while avoiding obstacles and avoiding going out of bound so the total number of ways is twos because we go this way downward and then this way downward to reach two now let's go over the dot process we will need to keep track of our current position of the robot we will need to keep track of the current position of robot which we will denote as rc so initially rc is going to be at 0 because we're at the top left corner then at each of the cells we have two choices we can either go rightward or downward when we reach the bottom right corner we have found one possible way to reach the star here um we should know that every time we go out of bound or we step into obstacle the number of ways is going to be equal to zero or the number of paths will be equal to zero if the robot steps out of bound or steps into an obstacle the total number the number of unique paths will be equal to zero and this in this case we have two choices we can go either right where or downward this means we will need to find the total number of paths on both choices now let's go over the answer so we're going to implement the recursive approach now what parameters do we need it's going to be r the current role of the robot and c the current column of the robot and then we'll have our obstacle grid which we'll just call grid the input grid and then we also have the m the number of rows and n the number of columns now what's the base case if the robot is outbound if rc is out of bound or grid rc is equal to one that means the robot step into an obstacle then the number of paths is going to be equal to zero so we're going to return zero then if robots if rc is at the bottom right corner this means we have found a valid path then we can return one we have found one path so in each of the recursive call we're going to recursively find the number of paths by going rightward of going rightward so if we're going rightward that means our column increases to c plus one and then recursively find the number of paths of going downward number of halves of going downward now we're going downward we're going to increase our um row then we can return the sum of the two recursive calls because we want to take the total number of paths from going rightward and the total number of paths of going downward now let's go over the time space complexity so the time complexity is equal to of 2 to the n plus n where m n are the number of rows and columns this is because in each of the recursive call we have two choices and with a depth of m plus n now the space complexity is go to of m plus n this is the recursive call stack memory now let's go over the code now we'll first create our recursive method keeping track of our current row and column which initially start at the top left corner so it's going to be zero and then our input grid and then the number of rows in the input grid and the number of columns in every red one thing you want to make sure is if the input grid is empty oh the immigrant is never empty so this will not er will not give us the error the since the input grid is never empty so let's create our method keeping track current column our current row current column input grid the number of rows and the number of columns so if now we first need to check if rc is out of bounds so if r is greater than or equal to m or c is greater together n or if the current cell has an obstacle so grid rc is equal to one then the number of paths is going to be zero because we have failed to find a path then if grid rc actually if rc is at the bottom right corner where i found one path so r is go to minus one and c is equal to n minus one then we'll find one possible path so return one now we want to find the total number of paths of going first we want to go rightward so c plus one and the total number of paths of going downward so r plus one oh this is the message so this solution is not efficient enough so this proof force solution is not efficient enough we will need to optimize it using the memorization approach in the next video so this approach is not efficient enough and we will need to optimize it using memorization let me know if you have any questions in the comment section below as we move toward the memorization approach of unique paths too you
|
Unique Paths II
|
unique-paths-ii
|
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.
Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The testcases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
**Example 2:**
**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1
**Constraints:**
* `m == obstacleGrid.length`
* `n == obstacleGrid[i].length`
* `1 <= m, n <= 100`
* `obstacleGrid[i][j]` is `0` or `1`.
|
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0
|
Array,Dynamic Programming,Matrix
|
Medium
|
62,1022
|
760 |
Hello Hi Friends Welcome Back Today We Are Going To Solving Code Problem 830 50 Grams Mapping Sunidhi Chauhan Of The Google Interview Questions Vacancy So Let's Will Go Through The Description Of A Given To Least He Ended And Devotion And Places Of Grams And Means Of Graph Being Made Here And Amazing The Order Of Elements In Case You Want To Find Out Indexed Mapping Peeth From The To B S Mapping Peeth To J Means Height Element They Appear In B.Ed Means Height Element They Appear In B.Ed Means Height Element They Appear In B.Ed In Deposit Is This List And B In Content Duplicate That Late Night Multiple Answer Output Bank How to Bank Income Tax 100 Days Benefit Example Show Latest and Example Over Clear So Come and Will Discuss the Problem and Solution 100 Grams One Day at This Stage Program for Dalits Left to This Element in Letter for Example Issues Everyone Atithi Right It's The purpose is to randomly own this element anywhere in the beatles pair subscribe randomly if position 3220 element of presenting basically so what do you do the element half the wealth in located in the questions page in a good work in located in 108 index i20 diesel and back location in And Output Right Services So Mapping Of This Element 208 Location Of Beach That Is What Will Have To Point Out Some One Is So Brute Force They Invite You All To Leak And Drivers The Amazing So And You Can Have To For Lots Of Love You Will Travel To Follow Current For Look For A Doctor For BHU 150 And When You Are Traveling Love You When You Are Travels In Life You Will Read 12th And You Will Search 2016 ADIZ Wherever Your Point When You Will Forget And Share Suwan Here You Taste 20 * Find And Share Suwan Here You Taste 20 * Find And Share Suwan Here You Taste 20 * Find Hey Completely From Starting Wherever E 520 New Update Index Hair To This Vansh Remedy Cute Govind Solution This Order Of Inch Compound Gorgeous Traveling Tourism Minister Direct So Am Back Solution Over His To Find Its An Order Of Installation Folder Officer Will Not Be Accepted In No Interview So What Would Draw A Doctor For Inflation Will First Read This A Greedy And Wealth Creator Mac Prized For Its Creator Mac For Daddy Price Of This Manner And SMS Arrangement The Number And Its Position In Are Basically Right Letters Patent William May Pinpoint Website Leave Ko 250 Position Will Be Heroine Direct Valuation Will Give One Should Be Suid 532 Position Ka Hal Titu Position Will Be 246 Position Will Be 3.6 Position Will Be 246 Position Will Be 3.6 Position Will Be 246 Position Will Be 3.6 Position Will Be 350 Tips And MP3 Songs 2018 Position For And Winter Pratishtha Mein Baddi Hai Na Darr Hai Will Create One MP3 Mix Size of a Great to Output Tax Liability Say Zoo You Will Travel Through Are Now Also Withdraw into the Fort Element 1210 More Map Get Wealth Will Get 1351 Hearing That Will Do Map Don't Get Off 200 Episode 228 This Course Will Fight For This is similar to you can go all the best 250 and 15mm don't get 5000 years into the loot in price across the country can solve this problem and solution for this order of n so it is better than previous solution and the time complexity of all Problems with complexities also ordered the 1169 directions to research so this is the solution hai na gram map image google interview questions 100 latest look at the implementation previous 900 vacancies for this you have created a result the ring frame for the head of language and what Is the result 2012 return hai during sir after death vidmate folder position map and position me hui will look through all the elements of be and win fielder position math right with its independence on every number add number and interactive 2011 like share and after that only when Will Again Has Bluetooth Order In Tight Episode In Hand With Another For Lokpal Bill Creating A Girl To All Drop In Word Yaar Nominated For Total Complexity Will Be Order Candidate Cigarette And Loon Services Taken For Loot Withdrawal Ka Agreement And Will Just Popular Tower Result Egg White And Using Position Map Don't Get Off The Element Ride For Example Position Dot Map Date Of Birth Of Date Of Way Fight Clear Light A Product That They Are Doing Is Going To Populate And Result If They Go Into Return Resulted In Software Going To Take Solid Final Gram Meeting Problem Swift Bandh Dewas Police Our Code and Maturity of Giving Maxim Kar To Yaar Getting Correct Answer Shared Hui Cantra This Another Example Also Creating a Solid Waste Officer Creator Input State Data On That Wherever You Yaar All Meeting In This Shoulder Check Yudhishthir Example Search Click on here special audit example hai main to yaar tu yaar fitting correct answer rahi 4321 0.10 to aam to yaar nou in good position 4321 0.10 to aam to yaar nou in good position 4321 0.10 to aam to yaar nou in good position ko submit desh hai 200 g solution ko tax credit balance kodak hair soft this is the way a special person in the Final Village Mapping Problem Mature You Practice This Problem Also Check Out My List Play List Liter and Hunted Current Live Variety of Problem Solved and Its Significance Company Flight by Amazon Apple Google Microsoft Facebook Solitaire Problems of Dynamic Programming for Brain Research in the Treatment of This Map Treated His Death Toll Booths Related Problems Yogik Problem Shuru Related Questions Karanpur Dedh Hundred Putra Udayveer WhatsApp Good Example You Handsome Coding Art Festival Of Which Will Also Give You How To Approach Problem And Formal Logic To All Problems Including Interview Also For The Interview Was Preparing For the Interview Play List Ko Bajao Roop Le District Bahraich Space Frequently Asked Questions Page Company Indore Purna Inka Trend Initial Benefit Which Will Give You Like Jhal Idea Of Work We Previous Internet Service Aa Is United Pollution And If You Find This Video Helpful Please Subscribe And Liked Your Subscription Will Really Valuable To 10:30 The Video Can Reach More Valuable To 10:30 The Video Can Reach More Valuable To 10:30 The Video Can Reach More People The Can Also Watch Station Also Get Help In The Application For The Interviews Code Interview All So Please Subscribe And Thanks For Watching Video
|
Find Anagram Mappings
|
bold-words-in-string
|
You are given two integer arrays `nums1` and `nums2` where `nums2` is **an anagram** of `nums1`. Both arrays may contain duplicates.
Return _an index mapping array_ `mapping` _from_ `nums1` _to_ `nums2` _where_ `mapping[i] = j` _means the_ `ith` _element in_ `nums1` _appears in_ `nums2` _at index_ `j`. If there are multiple answers, return **any of them**.
An array `a` is **an anagram** of an array `b` means `b` is made by randomizing the order of the elements in `a`.
**Example 1:**
**Input:** nums1 = \[12,28,46,32,50\], nums2 = \[50,12,32,46,28\]
**Output:** \[1,4,3,2,0\]
**Explanation:** As mapping\[0\] = 1 because the 0th element of nums1 appears at nums2\[1\], and mapping\[1\] = 4 because the 1st element of nums1 appears at nums2\[4\], and so on.
**Example 2:**
**Input:** nums1 = \[84,46\], nums2 = \[84,46\]
**Output:** \[0,1\]
**Constraints:**
* `1 <= nums1.length <= 100`
* `nums2.length == nums1.length`
* `0 <= nums1[i], nums2[i] <= 105`
* `nums2` is an anagram of `nums1`.
|
First, determine which letters are bold and store that information in mask[i] = if i-th character is bold.
Then, insert the tags at the beginning and end of groups. The start of a group is if and only if (mask[i] and (i == 0 or not mask[i-1])), and the end of a group is similar.
|
Array,Hash Table,String,Trie,String Matching
|
Medium
| null |
904 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem fruit into baskets this is a pretty long problem description but the problem is actually simple I think the best thing you can learn from this problem is how to take like a long description like this and then break it down into pretty simple requirements so we're given an array of fruits the value at each index represents the type of tree or rather the type of fruit that the tree produces so if we have like an array like one two three we have three different types of trees that produce different types of fruits now who cares like what types of fruits they produce but because these are different values they produce different fruits now if we have these we have a one here and a one here that means these two trees produce the same fruits and this one produces a different fruit our job is to collect as much fruit as possible but there are a few restrictions we only have two baskets what that really means though is we can only hold two types of fruit so we can have as many copies of each fruit as we want like we could have multiple one fruits and we could have multiple two fruits but we can't then add a third fruit we can't have three different types of fruits among all of these we want to maximize the total number of fruit that we have so we would probably disclude the three and then collect these because then we can get five fruits of two different types but there is one last restriction actually the trees are lined up in an array so take this example again one two one these are the three types of fruits we have we can start picking fruits at any position we want so we could start here or start here but wherever we start we have to keep collecting fruits basically forming a contiguous subarray we have to collect every fruit until we can't collect another fruit so in this case we can collect all three of these but what if a three came right after that in that case we wouldn't be able to collect the third fruit so starting at this position these are all the fruits we'd be able to collect now we don't have to start at this position so if we had one two one three what if we start at two well in that case we can only collect these two fruits because if we try to collect the third fruit we can't hold three different types of fruits and starting at this position we can collect these two so you tell me which one maximized the total number of fruits that we can collect well when we started over here we were able to get three total fruits so that's the maximum so the idea is that we have to form a contiguous subarray such that there are only two distinct types of fruits in the subway that's the whole problem they give a really long explanation but the problem is actually more simple than you think we're given an array of integers in this case we want to find the longest contiguous subarray that has at most two distinct fruits so what's the Brute Force way to solve this problem well take this array for example we want to consider every starting point so we want to start from here and figure out the longest contiguous subreddit we want to do the same for this position and this position Now The Brute Force way would be to have nested Loops so starting from here just keep going until we can't go any further we would have to stop here so we'd get four then trying it from this position we'd keep going until we got here again so we'd get three and then keep doing that for every value until we get to the end of the array that's N squared though can we do better well this problem is a pretty obvious sliding window problem well it wouldn't be obvious if you're not really familiar with this pattern but this is definitely a textbook sliding window problem which can take o of n time complexity and reduce it to just be Big O of n this is how we can do it we start off being greedy we start here we keep going as far right as we can we keep track of how many distinct fruits we have and we're actually going to use a hash map for that you're going to see why in a second but we're going to take every type of fruit and use that as the key value and then map it to the count of that fruit so initially we have one the count of one is going to be just one then we have a second one over here so we increment the count to be two now and then we see a 2 then we add that to our hash map so far we have two keys in our hash map that means we have two fruits in our basket and we keep track of the total as well I'm just not gonna draw that out but so far we have three total fruits that's our maximum so far then we see another one so we can take the count and then set it now to be three we still only have two different types of fruits but then finally we get to three and we want to add that to our hash map and we will well but notice that's going to make our key count be three now so I'll add it here uh fruit three we have a count of one of it but we can't say that we can collect five total fruit because our sliding window at this point is invalid we need to make it valid again so what we're going to do is from this left pointer over here we're going to start shrinking the window until it is once again valid we found that this is the longest contiguous sub array we could create starting at this point now we want to find the longest contiguous sub Ray starting from here but notice when we pop this one we're going to take our left corner shift it here pop this and when I say pop we're going to remove it from the hash map so the count of it is now going to be two but still our window is invalid even though this is of size four we don't care about this window because we just saw a window that was even bigger than it size five so we don't even care what's the longest contiguous ever we could create from here because we know it's going to be less than five anyway if the window of size 4 is in invalid so we shrink once again and then set the count now to one we see a two over here but it doesn't matter we still have three keys in our hash map so even this two has to go so now we remove two from the hash map so now our window is actually valid we only have two keys we have the one and the three but this window is only of size two the longest that we found before was of size four so that's still going to be our result and at this point our right pointer is going to be over here we can't really shift it any further so at this point our while loop would stop executing notice how we'll have two pointers the right pointer is going to iterate through the entire array and the left pointer is in the worst case also going to iterate through the entire array so even though the code I'm going to show you is going to have nested Loops that doesn't mean the time complexity is N squared the time complexity is actually two times n because we have two pointers iterating through the array but this reduces to just be big o of n we do need extra memory for the hash map but since the total number of keys in the hash map is going to be Atmos to I believe the memory complexity for this is going to be constant so now let's code it up I'm going to first initialize a hash map I'm going to use a default dict mapping the fruit type to the count of the fruit by making this a default dict with an integer default value this will allow us to do what I'm going to show you in just a second but first let's initialize our left pointer to be equal to zero let's have our total count which is going to be the total number of fruits in our basket at this point in time or at whatever current point in time that's also going to be set to zero and finally we're going to have our result variable which is also going to be set to zero initially then we're going to have our for loop I don't need to initialize the right pointer outside of the for Loop because I'm going to do it like this and we're going to go through every position in the fruits array and every time we see a fruit we want to increment the count of that fruit so we're going to get that fruit at index R and increment the count now what if that fruit hasn't even been inserted into the hash map yet well that's why this default deck will initialize the value to be zero if we try to access it and increment it even though it doesn't exist so this will work if it hasn't been inserted yet this will set the count to one and we also want to increment the total number of fruit as well but before we can do this which is updating our result we're going to try to maximize it always so we're going to set it to be the maximum of itself and the total before we can do this we have to make sure our window is valid how do we do that well while the length of our count hash map is greater than two that means we have more than two types of fruit then we are going to start popping from the left let's first get the fruit I'm going to call it f at the leftmost index because we're going to need it a few times so fruits at the left index first I want to decrement the count of this fruit I can do that just like this in our count hashmap we also want to decrement the total number of fruit which we can do pretty easily now there's one thing here since we're measuring the number of keys in our hash map if the count of a particular fruit ends up being zero which we can check like this if not count of that fruit initially it was positive but now maybe it's set to zero if that's the case then we can remove that key from our hash map like this popping the F key and then we're good to go oh one last thing our left pointer we should probably increment it unless we want to get stuck in like an infinite Loop so this will be us shrinking our window until it is valid and then afterwards we can possibly update the result we'll probably never have like a window that's less than zero so we don't really have to worry about those edge cases but after this is all done we just have to go ahead and return our result whoops of course I had a typo fruit is not going to be fruit it's going to be S it's plural so now let's run it and as you can see it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a ton of free check out neatco.io it has a ton of free check out neatco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
Fruit Into Baskets
|
leaf-similar-trees
|
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces.
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
* You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold.
* Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
* Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_.
**Example 1:**
**Input:** fruits = \[1,2,1\]
**Output:** 3
**Explanation:** We can pick from all 3 trees.
**Example 2:**
**Input:** fruits = \[0,1,2,2\]
**Output:** 3
**Explanation:** We can pick from trees \[1,2,2\].
If we had started at the first tree, we would only pick from trees \[0,1\].
**Example 3:**
**Input:** fruits = \[1,2,3,2,2\]
**Output:** 4
**Explanation:** We can pick from trees \[2,3,2,2\].
If we had started at the first tree, we would only pick from trees \[1,2\].
**Constraints:**
* `1 <= fruits.length <= 105`
* `0 <= fruits[i] < fruits.length`
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
| null |
263 |
Hi Rand, so today we are going to do the first question of our Maths playlist which is a very good version and it has been asked in Microsoft, Facebook and Google. This is its sample version of its easy part which was also asked in the challenge today. Let us solve this question, Amazon and Facebook did not ask, it is ok, it is simple, we understand the meaning of the question by looking at the input and output, what is the question, you have to tell whether the number given to you is right or not, your given number is the next one. Whether it is there or not, now when is any number next, let's see if its prime factors will not be just three numbers, okay, then let's see, once the example has six, then what will be the prime factor of six? 2 * 3 is okay * 3 is okay * 3 is okay ours. What was 235? Okay, so see what is its factor, you are three, which is this, okay, apart from this, there is no other number which is other than these three, okay, so this is the next number, okay, so this is all you need. We want to find out whether a given number is yours or not, the next number is ok, now let's look at 14, what will happen to 14, you are cross seven, so see, you are ok, so brother, this is not our next number, ok, so what is the answer to that? What has to be done is the number which is the input you have given N = 64 then keep multiplying till then given N = 64 then keep multiplying till then multiply no everyone is sorry try to divide till then divide by divisible one no problem N = N / 3 Do it no problem N = N / 3 Do it no problem N = N / 3 Do it okay. L shop and percentage do it means we are not that next number okay now in this loops we will come out then n should be 1 right n which is okay then out if n = 1 a gone means we have done all the tu se out if n = 1 a gone means we have done all the tu se out if n = 1 a gone means we have done all the tu se three se If the number is divided by five, then it is ok, otherwise we will post the return. If it is not so, then it is ok. There is a very simple code, here is a small example of it. If I made it 14/2, then my N becomes 7, 14/2, then my N becomes 7, 14/2, then my N becomes 7, right? And mine is done, okay, we have made it 7 percent, okay, now let's take the input van, mine is okay, now what is the van Greater Daman checking, outside the loop, if n reaches equal to 1, then proof the return, okay because Van does not have any prime factor, all its prime factors will be 23 and 5 only, so let's do the coding. Okay, so let's see that it is saying in the question that the next number is such a positive wait whose prime factor you just have to find out. Which is the next number, not like six, I said that it is the next number, because sir, the prime factor is you in three, the van which is mine is the next number, why, because look, you can write van like this, no, the power of you is zero, nor is it in three. Power zero of five, power zero of three and multiple of five can be shown as its prime factor, hence van is also the next number, okay then it was a simple code, we could have done it as told, what is the story, will and is greater. Than van percent, this number we have is not the next one, last return, what will we do if we reach this equal, then van means the next number is the okay, you replace this entire line from here till here. You can return n = 1, only one thing is fine, you are able to pass all the details, I have passed all the details, cases, I hope you understand the question, if not too many, then it was easy, fine, still there is any doubt, comment section video, thank you 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,091 |
hey what is up guys for this question i'm going to be solving shortest path in binary matrix which essentially asks for finding the longest the length of the shortest clear path in a 2d array and a clear path is essentially the path from the top left cell which is marked as a zero to the bottom right cell which is also marked to zero and the only way we can get from uh the initial cell to the very last cell is through going to any other cell that would also be a zero in any direction so we can go to the right of it upwards leftwards downwards and also in all four diagonals to go from one entry in the array to another so the way i'm going to be doing this is a fairly simple way just using a breadth first search approach and essentially we're gonna have just one while loop and initially we're going to start out with a queue that holds this that holds the first cell with the top left cell the first entry in the array and we're gonna do a while loop while we have more elements in this queue we can uh pop the first element in the queue check if it's the last cell if it's not then we add every neighboring cell that's a zero which is what we're allowed to do since those count as a clear path and we increase the length in every step uh whenever we do that and whenever we pop one from the queue and we find that it's the very last element that's how we know that we've found the shortest clear path so let me just give a quick visual of how that would look like so initially our q is going to be zero this corresponds to the length so far that we've accumulated and this actually should be one not zero because we're going to count the first cell that we're on since it's a zero and the x and y coordinates in the array that corresponds to this element and we start at 0 so this will be 0 initially so for the example that's given here since we have 0 1 and 1 0 we're initially going to pop this element in the array we're going to have like a while loop that looks at the queue and we're going to pop the first element which is gonna give us this and whenever we pop it when we realize that this is not the very last element in the array which is this one we're gonna go through each neighbor each allowed neighbor and we're gonna add them to the queue only if it's a zero and it's a valid cell in the array so for example going up from here would go out of index of the array and similarly going to the left or upward and to the left so whenever we add it to the queue we want to make sure that we want to turn this entry into a one so we don't double add it from anywhere else or add it again because we've already seen this so once we add this to the queue we're gonna turn it into one and when we come and pop it from the queue we're gonna notice that we've already reached to the very last element and we're gonna return the length which is gonna be that entry in the first element in the array in the queue and obviously we're going to increment that whenever we add something new to the queue so this will be two by the time we reach to this node so essentially the pseudo code will be pop the first element check if it's the end if it is then we return the length otherwise go through all the valid directions add it to the queue only if it's a zero and when we add it to the queue we mark it as one in the matrix since we don't want to visit this again so just to make a quick visual of this essentially what this would look like say we're given an array of zero one and zero one zero here and let's say a one here initially we're going to have this in the queue we're actually gonna turn this into a one since we don't wanna visit it again then when we append the valid neighbors we're gonna only append this one since this is the only zero that we can visit and we're actually gonna turn this into a one and then in the next iteration we're gonna append this one since it's a valid neighbor that we can reach through this diagonal and then we're going to turn this into a one and then in the very final iteration we're gonna add these two and turn them into one and so far the length is one two three to get to this one and let's say we pick this one up first in the queue it's going to be a 4 and once we process that we're not going to add anything else because we've already switched everything to a 1 so we're going to go back and pick this one up now and it's also going to be a 4 since we were at a 3 here and then we're going to return that the shortest path was 4 indeed so it's a pretty simple algorithm and now i'm going to be showing you how it looks like in the coding parts so initially we're going to start out with a q where we can put the very first elements in it so the syntax for this was going to be the length so far and the x y coordinates so initially this is just gonna be one and zero and like i said it's one initially since the very first element is going to be a zero so we can do a bunch of checks here to check if the first element is not a zero then uh we don't have a valid uh input and we can just return negative one initially or the very last element is not a zero then there's no way for us to get to the very last element and we can also just return a negative one otherwise we go through the breadth-first search we go through the breadth-first search we go through the breadth-first search approach and we initially pop the first element and check if it's the last element if the x and y corresponds to the last elements in the grid and the way we can do that is simply get the length of the grid and since it's an n by n matrix this should be the same value for the x and y and we can just simply return the right length if that's the case otherwise and something just quickly i forgot to do here is since we added this to the queue we want to change the first element to a one so we don't go back to it if there was like another zero for example otherwise we can go through each of the valid directions and i'm going to define this variable shortly and just add those changes to the x and y that we're currently at make sure that these are within the bounds of the array if they're not then we can just skip that entry and similarly for the y the new y and also if it's a one then we don't want to go through this path since that doesn't count as a clear path based on the description of the question so this is why it's important to mark it as a one whenever we go through this path so when we're in that line here we know that this is a valid cell and it's a zero so we're gonna just mark it as a one and add it to the array and the new length is just gonna be one plus what we currently had and we just add the new x and the new y so now what this the directions is going to look like which is going to be a 2d array of each valid offset from where we are so let's see we're here to get to there we need to add 1 to the y so this is going to be just 0 1 and once we do that here like the d y is going to be 1 and that's how we're gonna get to this offset so now i'm just gonna do that for every other direction we have two four six eight and that should cover every single direction that we need and i believe that should be it to solve this problem other than the syntax here that we missed to an org condition here and yeah hopefully that made sense and thank you for watching you
|
Shortest Path in Binary Matrix
|
maximum-average-subtree
|
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that:
* All the visited cells of the path are `0`.
* All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner).
The **length of a clear path** is the number of visited cells of this path.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** -1
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1`
|
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2126
|
1,262 |
well all my problems are invisible to me this is one two six two greatest sum divisible by three all right let's go ahead and get right into this problem so you're given an integer array nums return the maximum possible sum of elements of the array such that it is divisible by three pretty simple problem description right just one sentence this requires some knowledge about you know integers discrete mathematics divisibility All That Jazz but essentially all you need to know is when something is divisible by three what does that mean well for any number X to be divisible by 3 that just means that X Mod 3 equals zero and mod right is the remainder which makes sense when you think about divisibility because what is divisibility means the visibility means that you know three is a factor of that number so 3 is a factor of that number X Mod 3 will equal zero so that's what divisibility means when we look at this some here right if we pick numbers three six one eight and sum them to 18. it's divisible by three right because 18 mod 3 is 0 because 18 remainder 3 is 0 because 18 equals three times six right so since 18 equals three times six therefore 18 mod 3 equals zero because three times six mod three well obviously three goes into this and it goes actually goes in both factors but that's you know not important equals zero so I hopefully you understand how modular arithmetic Works how the visibility works right sometimes people say you know you don't need any math knowledge to solve legal problems you need some math knowledge right you need to understand some things because you need to understand you know these definitions like what is the visibility what is modular arithmetic Etc and actually having a strong module arithmetic background will help you solve this problem why well let's just go through a little proof which kind of leads you to the intuition you need to solve this problem um if you have X right you can think of X any X right and X to be divisible by three well X in the context of this problem is the maximum possible sum right so we're trying to find a subsequence kind of right because we're trying to pick elements right we're just trying to pick a series of elements such that when we sum them up then divisible by three equals zero so let's say x is that sum right so X is going to equal uh for some generic or nums so let's say nums just generically let's use a very generic argument to try to build our intuition let's say nums equals X1 X2 X3 x to the n okay so I'm just saying a very generic system okay and let's say our solution is X and x equals some sum of elements right x i plus x j plus x k plus dot x z whatever what a basic saying is our solution X is the elements that we've chosen such that when they're modded by three right when this system is modded by three it equals zero okay so in this case right our nums are three six five one eight you know three six five one eight and then our X is eighteen because we choose numbers three you know we choose number six we choose number one we choose number eight right that's a specific example I'm trying to generalize that so we can build some sort of intuition about the nature of this problem so this problem is very mathematically inclined right it's very mathematically involved you need to have a strong intuition about mathematics in order to at least modular arithmetic to convince yourself of the solution at least I did that's the path I took maybe there's an alternative route where you can think of this in different terms but mathematics describes this problem very well okay so if X Mod 3 equals zero right that's our solution X is the sum of characters so that means that we have the case that X Mod 3 equals zero well that's just the same thing as saying x i plus x j plus x k plus Dot plus XZ mod 3 equals zero foreign now I guess something you should know about modular arithmetic is that distribution property is kind of interesting right I can take these messages I can take these numbers and I can distribute the modular like this mod 3 these elements plus everything in here also gets modded three plus x to the Z mod 3 all of this system mod 3. right so in the context of this problem right if I choose three six one and eight right that means that three plus six plus one plus eight I'm looking at this particular example to try to kind of convince you of this argument here right of course you can't prove something with an example but it can also give you intuition so I'm not proving anything I'm just saying that it is that without proof and giving you an example so that you can use that to justify it to yourself okay right this mod 3 has to equal zero but you can split that up into three plus six plus one mod three plus eight mod three equaling mod 3 equaling zero so what that basically means is well three plus six plus one that's ten mod three plus eight mod three what's eight mod well just leave it like this for now mod 3. well 10 mod 3 is one and eight mod three is two because eight three goes into eight two times with two left over right and three goes into ten three times with one left over mod three which equals three mod three which equals zero all right which kind of makes sense right because you're just trying to find the remainder of this system so the remainder of one component of the number plus the remainder of another component of the number you can modulate those individually and then mod it with the end and get your final solution so how does this relate to our problem how does this idea of saying well I can split the system into two mod threes help us with this problem well I guess the idea is here which is where you have to make the biggest leap is that you know you can keep track of the maximum possible sums at each mod and then when you're given a new number you can discover where it should go what I'm basically saying is like if you look at any previous sum of elements right so if you have the previous sum of elements x i Plus x j plus x k and you wanted to add an additional element let's call that X um l well if you knew the mod 3 values of this system right if XL mod 3 was 0 and this was zero one two one zero one two saying if x i plus x j plus x k mod 3 equals zero and zero what is the whole system gonna be zero one two zero to 0 1. so if you add up these two components and you the mod 3 of this system with the mod 3 this system and you mod 3 it again so we're basically running we're exhausting all possible possibilities of this problem here if we apply that to this system right you'll notice that if a previous sum mod 3 is 0 and your currents in the current number mod 3 equals zero your wholesome mod three is zero If the previous sum mod 3 is 2 and your newest number happens to be a one now you get a new sum where the mod 3 is 0. right and if your oldest number mod 3 is 1 and you add a new number and its mod 3 is 2 you get a whole sum of zero so the reason why this previous part is important is that every time you add an additional number right every time you add this new number if you keep track of the largest sums modular 0 1 and 2 you can know what the greatest sum you can get is using this number in both of those mod spaces right because like if you have a newest the last number is mod 3 and it's one if you have a really large sum that's mod three is two you can just add in this element and you'll get a new sum which mod 3 is 0. so if you keep track of those largest sums you'll be able to find the maximum mod 30 system so basically if you have a number right x i and this is your newest number so you've already processed let's do this here using all of our previous ideas hopefully this makes sense I'm kind of going all over the place so hopefully in the end things connect so say you found you've already processed you're looking at this number right now you can do this for any digit right I'm making this case for any digit let's say you found X bar one equals the largest sum where X bar 1 mod 3 equals zero X or we'll call it x0 X bar one equals the largest sum where X bar one mod three equals one and X bar two equals the largest sum where X bar 2 mod 3 equals two so I'm basically doing is I'm saying I when I process the system before I get to xn I'll keep track of the largest sum X bar 0 where it's mod equals zero and X bar one where the mod is one and the X bar two and the mod is three right because that means I'll have some set of this system in here right for each of these I'll have some set of this system in here that I'm going to attach this final number to and using this idea here right I'll have this sum system here for the largest system where mod three equals one mod three equals two mod three equals zero and I can attach this final number to make a decision about where things need to go using this idea right so the first case we have is XL equals if the newest number equals zero so using this system bar here let's see if we can get things closer together okay problem is now my face is in the way okay it's fine so I'll do it here so if you look at your newest number right we're talking about xn so I'm adding x n to this system right if xn mod 3 equals zero where in this case right so the longest sum is now what well if any sum before my maximum some largest sum was Zero if I attach my newest number its Mod Space will still be zero so that means that our X zero is either it's going to be either what it was before because maybe including this number doesn't increase it well it always increase if it takes it doesn't matter we'll just leave it like that we don't need to use max for this okay now is well the largest sum with the modular ending in zero is whatever it was before plus this new number right and that goes the same for all of them right if you look at this system if the last system's mod was one and you add something mod three zero the still mod three one okay so that one's not that interesting now let's look at the mod 1 case where the remainder is one right here so what if xn mod 3 equals one that looks really weird sorry well X1 the largest of x one now is well if this thing mod 1 is 0 if I add in something previously that was Mod 0 it'll become one right so that means that X 1 equals x0 plus x n but it may not right because maybe there's a previous sum that's larger that uses x0 right so maybe I don't want to use x0 plus x n maybe the adding this element to x0 using x n makes X1 smaller than it used to be right because we just want the largest sums ending at any modular so if we take the max of that and whatever X1 was before okay and then what about X2 the max of well to get x2 when you have remainder one right two remainder one is when you add it to something that already had a remainder one so you do X1 plus xn X2 X3 equals the max of X2 plus xn and uh okay x0 X zero looks like I was writing some characters and then the same thing for if it mod 3 equals two well you're kind of noticing a pattern here the max of X zero plus XM X2 and I'll just quickly go through all these x 1 plus XM X zero X2 plus x m x one okay so this is all three of them so basically if I know the longest sums right I know the largest sums using the previous elements when I add in an additional element it'll change the largest sums mod anything depending on what that number is itself mod something right so if x of n the newest number mod 3 is 0 well then now my largest sum meaning that the largest sum is the number of elements that the sum of the elements that I'm using to get something modular zero I add in my newest element right it'll now be including xn the one using one including X1 sorry that doesn't make sense if I have my newest number right and it mod 3 equals one well then I can attach my one since xn mod 3 equals one if I attach it to something with Mod 3 equals two right so if this system has mod 3 equals two that would mean that basically what I'm saying in this case here if this doesn't make sense this proof here right this case happens when xn mod 3 equals one so if I add it to something right if I add it to something here where X2 mod 3 equals 2 well if I add these together right I get 1 plus 2 equals three which mod 3 equals zero right so if I take X which I know sorry I messed up there if I take X which I know mod 3 equals one because I'm down this case and I add it to X2 which I know mod 3 equals two together they'll get mod 3 equals zero so I can increase whatever I think my largest mod 3 system is equaling to zero here by using this new system or I can use whatever it already was because maybe it's better before okay so with all that craziness done let's go ahead and do the sample problem Again by hand and see if the intuition we can get works okay so what we'll actually do is we'll keep track of the system so we have three six five one eight now I'm trying to think about how we're going to do this so it's as clean as possible so we'll keep track of x0 X1 and X2 we'll keep track of the actual numbers that we're using even though in reality we'll just keep track of the sums so the first number we look at right is three so one note we have to do is say well like we'd say that X1 whatever it was before plus three would still be X1 but since there's nothing in this spot we can't put a 3 here right we could put a 3 here if there was something already here right because if we add in three then we get four so would be mod three equals one but since there's nothing there initially we can't put that in the spot so that's something to keep track of so three mod three equals zero so we'd add that to this spot here then we look at six again we'd have to add it to this spot here now it's where it gets interesting we look at five right so five mod three equals two so let's look at this problem so 5 Mod 3 equals two so we're going to go down this path right 5 Mod 3 equals two well now since it's mod 3 equals two we can add ourselves to X zero right because if x0 is something mod three plus six is zero so mod two would mean that we can just add ourselves to that system right so if we take something that's mod three equals zero and add something in that's mod three equals two like the five that we're looking at now the system will be mod 2. in order to be mod 1 we have to add it to X2 but since there is no X2 there wasn't any X2 when we added it in right we can't add it here and then for x0 we'd have to add in X1 right because something mod 2 but there's nothing here there was nothing here as well so you can only update this system so let's look at one and hopefully it makes a little more sense I should have included that zero idea okay well one mod three equals one so if anything was mod zero before when I added a one it'll become mod 1 so I can take the longest thing that's mod one anything that was won before would now become two because it's mod one so if it was mod two before now it'll become if it was mod huh if it was mod one before I'd become mod 2 but there was nothing mod 1 before so this doesn't get updated anything that's mod 2 before right so three plus six plus five that's our longest sum that was mod 2 before so if we add in a one that'll become mod zero three mod and then it'll become zero right this is mod 3 equals two so if I add in something mod 3 equals one it'll become mod three equals zero so instead of using three plus six I would erase this problem and I'd say okay I have something before mod 3 equals two and now one mod three equals one so if I attach it to that it'll become mod zero so I can attach myself to this and get three plus six plus five plus one equals um mod 3 equals zero okay now finally now we have eight so we can think about something kind of special because all these have been popular now so we don't have that weird zero thing so eight mod three is what two okay so now it's kind of complicated so let's just walk through our system here right so we can attach ourselves to x0 right so eight mod three equals two we can attach ourselves to x0 to get mod two which we're gonna do right because it's larger than what we have currently right the current X2 is less than x0 plus this so now we can attach ourselves plus eight well I'm really confused now hold up let's update this in order so if it's mod 2 x 0 becomes the max of X1 plus XM so the real thing is a cyclical so I'm confusing myself with my own solution so we're going to update x0 X1 and X2 just for this last one Okay so x0 equals the max of X1 plus our new element and whatever it was before so before x0 was three plus six plus five plus one so it was nine ten it was fifteen but if something is mod two three if something mod 3 equals two and we have some sum mod three equals one if we add those together they get mod 3 equals zero so that means that it would be better to use this sum right and then we get three plus six plus one plus eight right which will give you 18 and then X1 equals the max of X2 plus XM or whatever X1 was before so it'd be better to use this Plus the newest number eight then use the previous thing so we get three plus six plus five plus one plus eight and then x two equals whatever x0 was before plus XM if it's better three plus six plus five plus one yep plus our newest number so then at the end whatever the last two I might have I met a mess to something up here but at the end you'd return whatever your sum is module whatever the largest sum is mod 3 equals zero so you're basically just keeping track of what everything is the largest sums that get you to some mod number right what's the largest sum that gets me mod 3 equals zero what's the largest sum that gets me mod three equals one what's the largest sum it gets me mod three equals two and then I look at the newest number and I say well if I attach this newest number to the largest sum equals zero what does that get me if I attach this number to the newest sum the largest sum equals one what does that get me if I attach this newest number to the largest sum mod 3 equals two what does that get me and that will switch where things are in positions right like because when you attach something mod 3 to something before where it was mod one zero you get one right but sometimes it flips when you have a one it used to be zero becomes one if you had a one before and you attach it when you get a two so it's good to have this table so that's basically this problem I guess the only thing that we don't capture here is that if there was nothing before we can't add in the newest number right like when we started with three right I can't put three in mod one space because there's nothing before it if there was a one here then I could attach three to mod one space because it would just shift everything over one so maybe shift everything over three would be in the same Mod Space okay so with that let's try to just solve this problem hopefully all that makes sense I guess I'll just generalize saying we started by looking at you know what does it mean for number to be divisible how we can apply this modular argument so if we have the largest sum module or something when we add in the newest thing we can treat them separately we can find this separately before we solve for the newest thing that we're adding right and then we know exactly if we solve the problem in two parts right where we solve this thing separately prior we know exactly what will happen when we add a new one a new number mod that space and we just exhausted all possibilities right and then we use that information to make a decision about what it would mean when we add in this newest number given information we've solved previously right we solved all of this information previously so when we add in this newest number what would that mean for the new modular space and then we just solved an example so with that let's uh let's try to do this let's try so I'm going to use I guess I'll use x0 because that's what we did yeah I kind of want to make this three lines though no because it's going to be too confusing for people when they're watching me try to make this obscure I want to make it obscure okay so we'll look at each num and nums we'll call it X in nums right so now we have these cases right so we had to decide what we would do based on these cases right so if X Mod 3 equals zero X Mod 3 equals one X Mod 3 equals two so if X Mod 3 equals zero else if X Mod 3 equals one and then otherwise you know it'd have to be two so this would be the two case so if X Mod 3 equals zero how do we update x0 X1 and X2 well it's just x0 plus X the newest number x 1 plus x 2 plus X but only if these previous things exist for X1 and X2 right because we can't add in the three into X1 until there's some sum that exists with X1 okay so this is x0 plus X right and we don't need to take the max because it'll only grow right we're not shifting anything we're not swapping any variables so if x0 was the max before it'll stay to Max X1 plus X if X1 else X1 so another way of doing that is you could say X1 Plus int X1 greater than zero and then finally X2 plus x times int X1 X2 greater than zero I'll move my head out of the way I'll move myself down here okay now what if X3 X Mod 3 equals one so how does that switch this problem well you'll notice we'll keep yeah well I'm not gonna be able to so X1 equals zero m one and two and you notice that the only thing that swaps are the variables here right but everything on the right stays the same so it becomes one two and zero but now it um becomes a question of deciding if you're gonna use x0 plus the newest thing or you're just going to keep it the same as it was before right if you add something to x0 though it's not going to change um it'll be the same so you don't need to consider if the number is whatever you think it is so the max of that and X2 and the max of this and x0. so I'm just considering what these numbers were before and then this is the X2 case and in the X2 case it's two zero one remember it's all the same here so it's 2 0 1 which means these change to two zero and one and hopefully makes a little more sense here right if it's mod 2 right if this number X is mod 2 well now it'll take something that used to be mod zero and being mod two you just want to check if that's Max and at the end you just return whatever the maximum thing is that gives you okay I just realized I didn't capitalize these you should capitalize this but I didn't hear so it's going to take more time to redo everything here then it would be to just rename these so since I made a mistake just bear with me that I gave some bad variable names to your movie I mean maybe you don't need to capitalize it I don't know all right cool so you know you can make this a lot shorter you could actually make this a three-line solution three-line solution three-line solution um right by just using an array or something but this is good enough for me so what's the run time in the space okay well let's say that n equals the length of nums so for time and for space okay time is pretty easy right because we just have to look at each number and then for each number we make a constant check there's nothing in here that's dependent on N we're just you know doing some Maxes and doing some comparisons and some additions these are all constant operations so that's Big O of n and then for space well we just create these three variables and then we update them accordingly we never doesn't depend on the size of n the size of nums right whatever n is it's irrelevant we only have these three variables so that's o of one okay so that's it for this problem solution hopefully this made a little bit of sense um it's definitely a mathematically involved uh dealio situation circumstance so that might be something to consider when you approach a problem like this um or when you delete code in general that you're going to have some mathematical knowledge if there is another explanation please uh leave a comment and describe that to me all right peace
|
Greatest Sum Divisible by Three
|
online-majority-element-in-subarray
|
Given an integer array `nums`, return _the **maximum possible sum** of elements of the array such that it is divisible by three_.
**Example 1:**
**Input:** nums = \[3,6,5,1,8\]
**Output:** 18
**Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
**Example 2:**
**Input:** nums = \[4\]
**Output:** 0
**Explanation:** Since 4 is not divisible by 3, do not pick any number.
**Example 3:**
**Input:** nums = \[1,2,3,4,4\]
**Output:** 12
**Explanation:** Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
**Constraints:**
* `1 <= nums.length <= 4 * 104`
* `1 <= nums[i] <= 104`
|
What's special about a majority element ? A majority element appears more than half the length of the array number of times. If we tried a random index of the array, what's the probability that this index has a majority element ? It's more than 50% if that array has a majority element. Try a random index for a proper number of times so that the probability of not finding the answer tends to zero.
|
Array,Binary Search,Design,Binary Indexed Tree,Segment Tree
|
Hard
| null |
1,492 |
hey everybody this is larry this is day four of the december leeco daily challenge uh hit the like button hit the subscribe button join me in discord let me know what you think about taste farm uh if you're new to stream i usually solve this live and i talk about my thought process as i'm reading this for the first time uh and so yeah watch in 2x or something like that if you want to speak through to the solution uh toward the end uh and for this problem the k factor of n okay so you just have to list all the factors in this okay and then return the k factor okay so the easy part is that n is less than a thousand um it makes it easy because you can just do proof force uh with respect to getting all the factors in a easy way um if n was much bigger then you would have to do something like prime factorization and then do um a sort of um some kind of heap type thing to kind of get the smallest factors as you take out the prime divisors and stuff like that um but yeah uh but for now this problem will keep it simple because n is a thousand and we'll just make sure that we do the loop um and we don't even have to do anything clever because n is only a thousand so you don't even have to do um if you really want to be clever you could do stuff up to the square root of n um but for me for now i'm just going to do it the most naive brute force way um and if i was in a contest or something like that when i see these constraints that's what i would do because then i don't even have to think about it and i could get it done in about two minutes um and i might still get done in two minutes so yeah so now let's just go let's create a factors we could go from let's use uh i'm just going to say let's just say i uh i in range of from 1 to n inclusive um if and my i is equal to 0 factors that append uh i right and that's pretty much it and then now we return factors of k um is to oh yeah i was looking for the if the negative 1k so don't forget about that so if length of k is a length of factors is less than k or yeah if k is greater than or equal to factors we return negative one otherwise just return factors about and that should be okay uh i it's a lot of uh testing or that a lot of testing there's a lot of typing into the testing but i will do that uh you know feel free to speed this one up through montage or something like that uh okay so now it's running uh ooh so definitely not unless i miss uh quit oh well it's definitely not the right answer because four is definitely not a the right answer even for the first case um okay then the other thing that i double checked was whether k is um one index or zero index and clearly it is one index so that's not that bad we just have to go uh convert it to the zero index okay so that looks good because uh the reason how i could debug this so quickly is because the code is so small that it really can't be wrong by that much um that always is true but yeah so this one was the complexity um the complexity is of n because n could have at most well not really but let's say n heck uh but we do check off n for the factors so this is gonna be of n uh you can actually uh so the two optimizations you can do one again is just counting up to the square root uh that obviously make it smaller and then the other one is noticing that um you know we only need to care about the first k elements so after the first k elements we don't have to care anymore um so that's a little bit faster that second part um but yeah but that's all i have with this problem i think this is a yeezy problem probably and they meant it to be easy so it's just a good warm up for your real problem for when you do some harder things so uh but yeah but still yeah i don't know this is just a for loop so i'm not gonna go that much into it uh let me know what you think and i will see y'all tomorrow bye
|
The kth Factor of n
|
time-needed-to-inform-all-employees
|
You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12, k = 3
**Output:** 3
**Explanation:** Factors list is \[1, 2, 3, 4, 6, 12\], the 3rd factor is 3.
**Example 2:**
**Input:** n = 7, k = 2
**Output:** 7
**Explanation:** Factors list is \[1, 7\], the 2nd factor is 7.
**Example 3:**
**Input:** n = 4, k = 4
**Output:** -1
**Explanation:** Factors list is \[1, 2, 4\], there is only 3 factors. We should return -1.
**Constraints:**
* `1 <= k <= n <= 1000`
**Follow up:**
Could you solve this problem in less than O(n) complexity?
|
The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed.
|
Tree,Depth-First Search,Breadth-First Search
|
Medium
|
104,124
|
1,866 |
hey everyone welcome back and let's write some more neat code today so today let's solve the brand new problem from today's elite code contest number of ways to rearrange sticks with k sticks visible a pretty long name and this is a pretty difficult problem and it happens to be a dynamic programming problem so as with most dp problems it's about how we can break this problem down into sub problems and then solve those sub problems so we're given a list of n candles and each of them is a unique size of lengths from 1 to n we want to rearrange the sticks such that exactly k sticks are visible from the left side so basically with this input we would have three sticks that are visible one three and five the reason why two is not visible is there's a candle to the left of it that's even bigger so basically when we say visible it's if you're looking from the left which candles would you be able to see you would not be able to see two because three is blocking it and you would also not be able to see four because five is blocking four and so we're just given these two inputs n for the number of candles k for the number of candles we want to be visible and we want to return the total number of ways we can arrange it and it could be a really big number so we want to make sure to mod it by this large prime number so let's first try the most brute force of the first idea that you might have what would happen if we put one in the first position what would happen if we put two in the first position and what would happen if we put three in the first position how many different ways can we get candles arranged in each of these three paths remember we start with three candles and k is two so we want exactly two candles to be visible if we put one in the first position what's going to happen to our k and n values well then we get to the sub problem of 2 3 right so basically what we did is we took the number of candles available to us and decreased it by 1. so n is going to be 2 here and since we put 1 in the first position we know for sure one is going to be visible so we took k and set it to one we decremented k by one as well so this is pretty simple right if we choose one as the first candle we get a pretty simple sub problem but the difficulty is going to come when we go along these two paths there and that these two paths are the reason why if we do it this way the overall time complexity is going to be big o n squared times k that's not a bad solution and it's definitely the most intuitive solution that you'd probably come up with but it happens to be that we can get an even better solution that is going to be n multiplied by k it's just going to be a little more tricky to arrive there but first let me just tell you why this is going to be a little bit difficult for us if we put two in the first position then we could arrange it such as then we'd have two candles left over right the candles would be one and three notice how one candle three is going to be larger than two so that could possibly be visible but one would not be visible it's still a candle that would have to go after two but it would never be visible again right because there's gonna be a two blocking it so this is why we're gonna need three variables along this path what we're gonna say here is n is now gonna be one n is one because there's only one candle remaining that could possibly be visible k is gonna be also one because we took the total we needed two candles to be visible if we put two in the first spot that means two is going to be visible but we need one more candle to be visible that's why k is going to be one and we're also going to have a third variable let's just call it m basically m is going to be the number of candles that come after two but that can never be visible again we still have to keep track of them because we could arrange these candles in multiple ways but these candles are never going to be visible n is keeping track of the candles that can still possibly be visible so as you can see this is going to require three variables that's why the time complexity is going to be bad but there's actually an easier way we can break this problem down instead of considering if one was in the first position two was in the first position and three was in the first position let's consider if all three of these candles were actually in the last position does that make our sub problem a little bit more simple for us let's think about it if one was in the last position that means we could possibly arrange things like 2 3 and then put a 1 here or we could do 3 2 and put a 1 here notice how since 1 is the smallest value there definitely exists values that are greater than it therefore one if it's in the last position is not going to be visible so basically what we're saying is if one goes in the last position then we're gonna have two candles left over that could possibly be visible basically we're taking n taking it from three and reducing it down to two our k value is going to remain two why does k stay as two the reason is simple because initially we needed two candles to become visible one is not visible so we still need two candles to be visible basically we're saying is the new sub problem is basically how many ways can we arrange the candles two and three such that two of these candles can be visible so along this path n the new sub problem becomes n equals two k equals two and that's reduced from what it was up here the exact same is going to be true if we put two in the last position notice how if we put 2 in the last position it's not going to be visible because no matter what we have a value 3 that is larger than 2. if 3 comes before 2 then 2 is not going to be visible that's true in this case and it's also true in this case where three is before too basically what we're discovering is as long as the value that we're putting in the last position is not the greatest value in the array it's not going to be visible so what we're saying is the sub problem can then be reduced again to n equals two and k equals two but the only difference is going to be in this last case where we're putting the largest candle in the last position no matter what then in that case for example in this case or here since three is the largest candle it's going to be visible no matter what if it's in the last position right so this is a different sub problem right what we're saying here is we're still looking at n equals 2 right because these two candles could still possibly be visible nothing's blocking them right we put the 3 in the last position so n is still going to equal two in this case we have two available candles to choose from but k is going to be one y is k one because we know for sure there's at least one candle that's visible so since initially we required two candles to be visible we have one that's visible now we can reduce this k equals two now down here to k equals one and for each of these branches of course we know that we could continue going down and down until we got to the base case now what is the base case going to be notice how if we had let's say two candles right one two and we wanted both of these candles to be visible there's only one way to arrange it right from smallest to largest right put the smallest one at the beginning then put the next one and so on right so if we wanted k equals two both of these to be visible there's only one way basically what i'm saying is you know if we had maybe even three candles right and we had k equals three we want all three of these candles to be visible there's only one exact way so what i'm saying here is if the base case n equals k is true then we're going to return one so that's one that's basically the base case now let's think about a different base case what if i had two candles right and i wanted exactly zero of them to be visible if n equals two but i want zero to be visible now this is impossible right so in this case we'd have to return zero what if the opposite was true what if we had an empty array right but we wanted two candles to be visible now we don't have any candles to choose from basically n equals zero right we have no candles but we need two to be visible therefore we have to return zero because this is also impossible so basically if either n or k equals 0 then we have to return 0. that's another base case now of course if we continued on these paths it would be really complex right that's why we can use a cache to go ahead and store repeated work notice we already have some repeated work right both of these branches lead to the same result and so looking at this tree and looking at what we just went over what is the recurrence relation what's that equation going to be basically dp of n k we know that whatever we have like whatever the n value is there's going to be exactly one branch that is where n is going to be decremented by 1 and k is going to be decremented by 1 and that's going to be when we put the largest candle at the last position taking this we can say that this is going to be equal to dp of n minus 1 and k minus 1 but that's not it right plus we have to include a plus for the remaining branches we know all the remaining branches over here are going to be the exact same now how many branches are going to be the exact same we know one branch is going to be here that means the remaining branches basically n minus 1 are going to be the exact same so we can say n minus 1 multiplied by dp now what are these branches actually going to be basically n is decremented by 1 as you can see k stays the same so that's what we can say for this dp n minus 1 k stays the same so this is actually the equation once you can arrive at this equation this problem becomes a lot simpler and as you can see based on the dp dimensions the overall time complexity of this is going to be big o n multiplied by k that's also going to be the memory complexity once you can arrive here and yes it is tricky to do so because you have to consider you know if one was going in the last position if two was going in the last position that's not super intuitive most people would assume that one would go in the first position two would go in the first position but it works out a lot easier as you can see when you do it the backwards way with that being said let's jump into the code now so as i mentioned we are going to have a dp cache so let's just make it a hash map in this case and we're going to do this recursively with our cache so i'm going to define a function inside a function we have n and k as the variables that are going to be passed in and we know that one base case was if n is exactly equal to k that means there's only going to be one way that we could possibly arrange the sticks now the other base case is if n was equal to zero or k was equal to zero remember and in that case we know that it's impossible for us to rearrange the candles the last case is if we've already computed n k so basically if nk is in dp then we can return whatever happens to be in our cache right and the last part is basically once you figure out the equation you have solved the problem so that's what we're gonna do we're gonna go ahead and type out that equation so it's going to be dp of nk is going to be so we know that one case is basically where we put the largest candle in the last position basically in that case we're saying that we are remove we're decrementing the total number of candles available obviously and we're also decrementing k by one basically because since we put the largest candle in the last position we know for sure that it's going to be visible so we're going to take that and add it to n time minus 1 multiplied by dfs of n minus one k stays the same this portion is basically if we put any of the other remaining candles and we know the other remaining candles is n minus one that's how many candles there are other than the largest candle available to us and for each of those candles the dfs is actually going to be the exact same because if we put those candles in the last position our k has to stay the same basically we're saying that the number of visible candles has not changed but the number of available candles has been decremented by one so this is the recurrence relation once we've computed it we can just go ahead and return it so i'm going to copy this and then return that last but not least we're going to return our debt for search function we actually have to call it so we're going to call it with the initial n and k values given to us don't forget to mod this by 10 to the power of 9 plus 7 because it could be a really large number so this is an optimal solution n times k big o of n times k now for some reason it is time limit expired for me so let me show you the actual dynamic programming solution as well so this is the real dynamic programming solution the bottom up solution i'm not going to explain it too in depth because it is pretty similar to what we did up here basically we are initializing one base case where n and k equals one and that's going to be set to one i think that is pretty self-explanatory because we do need at self-explanatory because we do need at self-explanatory because we do need at least one base case to be initialized in our cache and then we're basically just iterating from here to here and the reason i'm starting here at n equals two is basically because we already have the n equals one case initialized for us here and if i had any if i started this at n equals 1 then we'd go through every k value and basically what we'd be computing is n equals 1 and let's say k equals let's say 4 or something right and this would always return zero because we know that if we only have one candle available there's no way we could possibly have four candles to be visible so that's why i'm starting at n equals two and then for basically each pair of nk we're basically doing the exact same equation we did up above now one thing i'm doing is i'm calling dp get getting this tuple now in python the way this function works is if this tuple does not exist in our dp cache i'm returning a default value of zero which is the appropriate thing to do in this case and i think once you can understand this recursive approach you could probably come up with the dynamic programming approach mostly pretty easily and if you really need to you can draw like the dynamic programming chart like two-dimensional grid for that dynamic two-dimensional grid for that dynamic two-dimensional grid for that dynamic programming solution if you need to but i think this solution is pretty self-explanatory for some is pretty self-explanatory for some is pretty self-explanatory for some reason it just doesn't get accepted on leak code i don't know why but i overall hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Number of Ways to Rearrange Sticks With K Sticks Visible
|
restore-the-array-from-adjacent-pairs
|
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it.
* For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left.
Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 3, k = 2
**Output:** 3
**Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible.
The visible sticks are underlined.
**Example 2:**
**Input:** n = 5, k = 5
**Output:** 1
**Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible.
The visible sticks are underlined.
**Example 3:**
**Input:** n = 20, k = 11
**Output:** 647427950
**Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible.
**Constraints:**
* `1 <= n <= 1000`
* `1 <= k <= n`
|
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
|
Array,Hash Table
|
Medium
| null |
743 |
hi everyone so they talk about network delay time so you are given the endnotes and then basically you have the time array at any time the race we want to give you uh the source destination and how much time it will take from a source to a target and then what you have to do is you want to send the signal from no k and then you want to calculate how much time you would take from k note to every single other node and then if this is impossible to reach all of the nodes you are returning negative one right so basically this is supposed to be easy so uh in this case uh this is the time array to one is top of one two to three is five over one three to four is false of one right this is supposed to be easy and then we will have four nodes right four nodes one two three four right and then we started for we started on uh note two because k equal to two right all right now we need to just uh spray the name right from node two and then this will basically be the first uh for the first uh iteration and then uh since the process one right so it's actually one and then uh these are the same level right and then you go from here to here for the next iteration so this is oneplus 2 right so this is the answer so how do you actually need to do it you have to build a box right so you can use hashmap to build a buff and then the key is what the kids know the i mean the starting note and the value could be what another hash map storing the target and also the time right and then basically you just have to just keep reversing right based on what you find right and then if you visit that note right you just um just small as music so you don't visit it again imagine there like imagine there's a direction from here to here right and then this direction doesn't work it's because what the first iteration is already used you don't actually need to use this okay even though the cost is less right all right so this is going to be pretty much it so there's another thing you have to worry about you have to use a priority queue because when you want to visit your first iteration since these are the same level right if this is cause of two right you definitely need to traverse the smallest copper pine first and before you reach the i mean before you try the second part so i mean second uh plus time right so i'm going to just build a prop and then i'll definitely um explain when i put so hash map so type map i'm starting integer as the node right and i also have another patch mac i'm doing so integer for the destination source uh destination node and also the value for the valuable time and this is math right now and then i'm going to traverse in a raid i mean to the array right to the array times so i'm going to put i'm going to use put it in action this is because if the timer is giving me typically uh no i mean this is not all right so uh just for example and there's two three right so if i already know i have two i don't have to uh initialize my two again i just want to i can just keep adding you know right so since this is a hashmap inside attachment right we need to initialize the hashmap first so this is what the source node and i need to initialize the text then i need to get the social and i need to put the rest of the stuff first t eq right p1 and d2 so again this is builder off so you just have to know like you want to initialize your node and then you don't want to re-initialize again right because if you re-initialize again right because if you re-initialize again right because if you say it's good right if you just put then you're basically leaking the data right and this is initially your uh soft node and this is like putting your destination you know in the top end in the time okay now i need to have a visit so boolean right so this is what so this is like uh currently no right so i don't want to revisit again right so uh also i need a return value it's going to be into node right so i'm going to return what if and if i'm going to do and inside and they don't i would just keep picking my mind and also i need a priority too right barbecue i'm going to use the inner rate i will explain why later so priority too all right so what does this mean i need to put i need to apply any current right so time and current not inside the linear rate so i will just compare based on the time not based on the curve no i'm the third other top so i will compare a and b using lambda expression from smaller two logix right and then i need to add right q and then this is pretty much it right so i'm traversing about the pq array well i think it's not empty right and then i will have to say current uh right or people that would move doesn't matter right then i'll say what's all the time people do uh third node zero this is not her name let me say data all right data zero and then turn you know one right this is more exact uh it's more detailed so uh so what you have to do is what you have to check if visit at 30 no right if you do visit then you just what skip continue right if you didn't need it right you make it you want to make it true right all right so if this is uh if this is the case then we are visiting a new uh i mean it's i mean the new norm inside the map right and then we need to consistently update our uh total time right and then i would think to me my every single time i'll be going on my own right so for example i'm right here and then when i'm traversing right i'll update my current um total client and people taking when i know right so i started following i started wrong uh i need to do two i mean k with the two right so i start from k to two and then i'll decrement mathematically my note right and then i said they said this equal to true right and then the prime is supposed to be zero uh yeah it's supposed to be zero right and then if unable to evaluate i already know i traversing higher uh if i know right so uh i also need to traverse my neighbor right i haven't traversed my neighbor right so you have to think about this so if you can find your neighbor based on your what uh based on your personal right because we will keep well we'll keep traversing based on the neighbor but we don't know if neighbor exists no right so i need to say if makeup contains e i don't know right if this is allowed then just follow me so it listens aloud which means there is a connection there so uh i mean uh there's a neighbor beyond this right so two to one right two to one because of one right but one doesn't connect to any others else right so you have to make sure uh the one is still inside my map which is what connect with a nominal but if not then we ignore right so if this is true then we need to find out what's my neighbor so my neighbor forget the current know right so what does this mean um this is the map right my glock right so i will get the entire sorry so i will get the current node based on my chi set so based on the key set on the second mac so uh so you have to think about it and then when i uh when i get this one i definitely can give it time right so i need to keep updating my couple time so um i will say mac oh sorry so you need to keep adding to your p2 based on uh with basically that connection neighbor that's right so i need a time so the time is what total time plus the cost of the connection point right house of commission time so i started from two i need to convention one right so it's from the one network get third i don't know but this is not a time right you need to say get next which is what the key set right one of the key inside the uh the inside map right so if i keep wait what was this so i get a time right and i need to possibly know it right so this is be pretty much the solution so let me run this space so okay so i do have a typo uh give me one more second plus total time plus no all right let's find out my mistake this is total time now the total travel i don't know what i'm doing so sorry about this all right so let's talk about time and space and this is going to be a time right all of t represent n of the times and this is time as well right but don't forget this is time right priority key when you sort it right this is going to be t log t represent length of the time so you have to basically um when you just keep adding your uh 1d array inside my pq right you need to compare keep finding out your connection so this is supposed to be t i don't think it's unknown right so unrepresent the number of no because you don't you are not guaranteed you have what the number of the uh the other one length of the uh connection right so you basic basically based on the primary and this is what this is pretty much it for the time t log t this is all of t nominated one right you only trigger as well once uh once every single one right and then let's talk about the space is this right and then this is a space right and this is also the space and but i would say g plus so what does t mean t represent like the land of the time you need to put harmony stuff inside a map and this is all of key this is all of them and this is going to be pretty much a solution so you have to like uh just follow along my logic and i apologize my typo this is supposed to be total time and this is the solution and i will see you next time 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 |
1,602 |
Hai gas welcome tu today's video and today we are going to do lead code problem 1602 named find nearest right node in binary tree so we are given a root okay and what we have to return is nearest node on d se level date is tu D right of view and return null if u it is d right most note in d level so basically what we have to do is in a particular level where we find our u we have to take the next note of u in the level and return this then ok Let's see how we are going to do this, so first of all, when I hear ' hear ' hear ' take the right note of level one', the first thing that comes take the right note of level one', the first thing that comes take the right note of level one', the first thing that comes to my mind is the level order driver, so when we say this one, level one, this It will be you and this will be three when we start this level 45 and its size will be I can do this when I go into this remove mode my own four will come out then I can check which note is available in front of the You process and this will be ours then I will set the answer in this condition when remove node IF remove node dot 12 equal you whose right we have to find out then I will process the complete answer of this equal you Front and then we will see that if my note is equal to you 6, then what we do is very simple, what we do is we put this condition, this is our jo aaye, my i is this note is equal to you size mines. If it is one, it means my right node is not existing, then we can keep our answer as null in the default, so that it will directly send this answer and if our U is 4, then it will convert it to five. In the UK answer, it is okay, this was our approach and this was the Kid of Sudo code approach. We got the strike that we have to play with some notes in the same level and he has to take the right of the note, which is our already setup, relief. Why am I going to run labor order from travel? So I will run my level order. Okay, so this is also done. Let's code once and see. So, first of all, why do I create a link list in Pari Note. This is equal to the new link list in that. And then I will go to my level order ice le give size i plus which is if a remove similary our you know which is 12 equal tu u.12 because 12 equal tu u.12 because 12 equal tu u.12 because they have given that each one of the ways value. Is distinct then if the well of remove node is equal to my UK wall and what else and this is not my last iteration this level means I note this is equal to size -1 level means I note this is equal to size -1 level means I note this is equal to size -1 then do it in my answer equal to here pick first And then after that do our answer Why will I push our route and run the dev order in which we do this is our next level in and processing this one so that is ours and the right child is exit Meaning When will this equal tu ke ka front be on the front, that's why this is ours, this is remove mode and first of all we have to keep it here and there, if there are children, then add them, brother, we will add and then check. Is the value of our remove note not equal to yours, so we do not do anything and the look ends on this, then after that again we size it with the updated one and the look starts running, first of all what do you do with your laptop road? I go to three, what it does is it adds its left and right, which are five and six, then after that, 3 itself checks whether my value is equal to four, then it is not so 3p does not do anything and this But the loop ends then we take the size again which is three and it comes again but the loop starts from zero then what happens first four comes out this is the critical moment then as soon as four comes out What happens is that first of all we check whether the left and right child of our four exits, if not then we do not add anything, but here now we check whether our four is equal to the UK value. With the fact that they have already passed, yes, this condition is true, but we also see whether my station which is last has started, otherwise mine has just come, this equal to zero has started, where my size minus one means last. Station because front co and why what is front 5 so in the answer I add 5 then after that it goes remove note and starts going next for i = 1 and starts going next for i = 1 and starts going next for i = 1 and it goes five a out five itself what It adds its children to ' It adds its children to ' It adds its children to ' K' if it is existing and then K' if it is existing and then K' if it is existing and then this five also goes away. Then the sequence of 'I = 2' this five also goes away. Then the sequence of 'I = 2' this five also goes away. Then the sequence of 'I = 2' starts going on. The last one and the six goes out. Then what does the six itself do after that? Checks whether it is equal to four and whether it has left and right children, all three of the three are new, so the six itself goes out of the loop on us and this is the condition of the wire loop, which is the size of the note. Equal tu zero plus but the size of the time is already zero so we break it with the wire loop and we return this function in the answer. You must have understood that this was a very straight forward question. Let's do this again so that you will get more understanding of the board, so this is our random tree 4567 and grab this and our U is 7, so now what will happen this time, we will see that once is added first, why I am one. One size relief, one goes to zero, starts looking at the inside and goes into remove mode, one, you add both the children, you and three, then one checks whether my value is equal to 7, that Does not remain, hence nothing happens, A starts running in a loop on the next generation due to which A goes out here, sorry ends, then the size is retweeted as it is, here we take the size and again look at this new one. Let's read this for the new level because our second level is a relief for the first level, ours is reduced, so what happens now and A goes out, if you add both the children, then it does not happen, so what does the three itself do? Adds both the children which are six and seven and three. Have you seen that my value is not there, hence three is gone and this loop gets broken because our i becomes then what happens after that? What happens after this, nothing happens, the loop ends and the size becomes again, it is recalculated which is equal to four, then for i = 0, the look on the inside i = 0, the look on the inside i = 0, the look on the inside starts again. In remove mode, a goes to four. Answer When you exit your children, it adds whether my value is equal to its value, so nothing happens, this condition plays and we move to the next iteration, then it adds it out and then it checks whether my Value is equal tu hai uk with vallu which is not 7 so I will not do anything and it goes still what happens now see this is Krishna movement it starts moving i = 3 = 3 = 3 and it goes 7 out remove In the mode, Seven checks whether I have children, so if I add it, then there are no children, so it does not add it too, but what happens here is the UK value because of this condition, so what do we do, we have come to know this. That in this row, in this level, seventh is our last note, hence the next one does not exist, so do not do anything and do not run this IF condition because I is equal to you size -1 because 3 is equal to you size -1 because 3 is equal to you size -1 because 3 is equal to you is our size. 4 - 1 = 3 So our note is our size. 4 - 1 = 3 So our note is our size. 4 - 1 = 3 So our note is not equal to you, so the look on this does not work. This look does not work and on this it loops I plus and this becomes four and then after that this remove node does nothing. It goes and it loops on this break then what happens after that size Riya Sen ho jati hai one se and then it goes out again and it goes to a and see break and then this outer value goes Is zero and then we return the same answer with the same tap, so I hope guys you have understood this whole problem, it was a very good simple level order driver sale example, this problem and its time complexity will be off N because we directly We are checking each mode, if you want to make it a little more efficient, then here you can also write break that if we have already got the answer, then you are running the look on K, directly break, which will also make it work, there this is going on. Apart from this was the question, please try it yourself and submit this problem by coding yourself and after submitting it, please tell me in this video that you have submitted this video, that's it for today. See you in the next video til cup tring and cup bye
|
Find Nearest Right Node in Binary Tree
|
find-nearest-right-node-in-binary-tree
|
Given the `root` of a binary tree and a node `u` in the tree, return _the **nearest** node on the **same level** that is to the **right** of_ `u`_, or return_ `null` _if_ `u` _is the rightmost node in its level_.
**Example 1:**
**Input:** root = \[1,2,3,null,4,5,6\], u = 4
**Output:** 5
**Explanation:** The nearest node on the same level to the right of node 4 is node 5.
**Example 2:**
**Input:** root = \[3,null,4,2\], u = 2
**Output:** null
**Explanation:** There are no nodes to the right of 2.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `1 <= Node.val <= 105`
* All values in the tree are **distinct**.
* `u` is a node in the binary tree rooted at `root`.
| null | null |
Medium
| null |
138 |
hello and welcome to another video in this video we're going to be working on compilist with random pointer so in this problem you're given a linked list of length n and it's a normal linked list except now every single node has a random pointer as well and that pointer can point to any other node in the linked list or it can point to null and your task is to make a deep copy of a linked list meaning all the nodes have to be just like these but you have to use all new nodes and they have to point to the new nodes they can't point to Old nodes so for this first example I mean it's hard to like exactly show it but essentially for a list like this you're making a deep copy so you're making all these five elements that point to each other and for these kind of the same thing so let's actually draw this in a different way to make it maybe a little bit easier so we're gonna have 7 13. 11. and 10. and one and then I guess we'll have null at the end because some things do point to null so this points no and seven as you can see points to null so let's draw that with another color so the random Point are seven points to know three and a pointer of 13 points to seven the random pointer of 11 points to one the random pointer of 10 points to 11 and the random pointer of one points to seven so this so how do we essentially do this problem pretty much right and it's not super easy obviously but like how many different ways can we do this for just this one example the rest of it is the same thing essentially so if you want to make a deep copy there's two things you can do that are pretty straightforward one is you can just make a copy of every single node and then you can store in a hash map so essentially we can just ignore all these randoms right so essentially we can just go through this list and for every node we'll just store it in a hash map and then we'll make the next pointer point to whatever that is in the hash map so let's show what that's going to look like so the hashmap will just have like nodes let's say and essentially what's going to happen is we're going to go through this whole list ignoring their random pointer for now and we're going to go through it and we're going to say okay well node seven is that in the hash route no it's not okay so let's store node 7 in the hash map and what do we want for the value so for the value we will make a new a completely new node and we'll represent it with seven Prime but essentially it is just a new node with the same value right and then for yeah so you can keep doing that so for node 13 you would also make a brand new one 13 prime 11 Prime 10 prime and one and now it's pretty straightforward for the rest of it right so for these new nodes first you make their next and no pointers or null and random pointers equal to none right so for now they're going to equal to none but then we're going to do one more pass you can do this in one pass but it's easier to explain in another pass so essentially first pass you just Loop through this list and every single node you create a new node and you store it in a hash map right Keys the old node new and then new node is the new node then we make one more pass and we just say okay for every node we'll take its next pointer figure out where that is in the hash map and we'll make the next pointer of the value go to the same place so for example the Seven's next pointer is 13. so we can just say like okay well if the Seven's next pointer is 13 that means this Seven's next pointer should be whatever the value is for 13 right so we can do this so essentially the next we'll call that n is 13. and it's easy because we have this hash map right so if we know that 7's next is 13 it's always going to be in the link it's always going to be in the hash map we can just say like give me the key for the next pointer and then the next of the value is going to be the other value right and what about the random so seven points to null so that part is just going to be defaulted to null so we'll call that R is null okay then we go to the next node 13 and we say okay what's the next of 13 well it's 11. so we'll just say okay well if the next of 13 is 11 the next of the value is going to be whatever the value of this is right so the next of 13 will also be 11. pretty straightforward because we can just use these keys to figure out where like we can use these keys to get the mappings to know exactly where to go to and then where does the random pointer of 13 go well it's at seven so once again I can get this key 7 get the value 7 and say okay well the random of this should be the value here right so that's going to be 7 Prime and then for 11 same thing so 11 goes to one so it's going to be this is the next is going to go to 1 and the random goes to oh sorry 11 goes to 10 and the random goes to 1 right so it's going to be 10 random one for 10 it's going to go to 1 and it's random is 11. so next one random 11. and so on and for one it goes to seven and it's next is null so next is null is default and random is uh seven so that's one way to do it right with this hash map but we are going to show an In-Place solution an In-Place solution an In-Place solution and pretty much what we're going to do for the In-Place solution is it's going for the In-Place solution is it's going for the In-Place solution is it's going to be a little bit different but also not too hard so instead of having this hash map what we're actually going to do let me make sure you get this and delete this hashmap section we are actually just going to go through this once again one pass and except now after every node we will create a new node with the same value and it's going to have a random pointer going to nowhere so let's show what that's going to look like so we're going to have seven let's actually use this color so we're going to Traverse and for every node we get we're just going to create a node in place right after it with the same value and then its random pointer will be pointing nowhere and then it's next we'll just be whatever the next node in the list so essentially we would be at seven and we're going to say okay well now that we're at seven let's create a new note after seven with the same value and let's make that Seven's next pointer now point to 13. and then we go to 13 we do the same thing we make a new node with the same value and we make this next pointer point to 11. so essentially you have something like this 11. 10 and it's pretty straightforward doing this right so putting a new node is pretty straightforward you can just say um you can just say like 7 dot next equals new node and then that value that node has value of seven and then its next value is 13 right so that's pretty straightforward but we have 10. and we have one and one okay so now essentially we have a list of 10 elements now these random values are going to stay the same right so seven points to null so let's actually put a little null here so seven points to null but this new value doesn't Point anywhere right for now essentially like we just did a one pass its new value doesn't Point anywhere so we are going to do a few passes through so it's okay it's still going to do the same time complexity so 13 points to seven this first seven right same thing and then 11 points to one and then 10 points to 11. and finally one points to seven so we're gonna loop around again so you can see like these newly clear created nodes these maybe we can even give them a little color to symbolize but they are the new nodes so these newly created nodes don't have next pointers yet right or sorry they don't have random pointers they have next pointers but they don't have random pointers so we do have to give them next pointers and how do we do that well that's also really straightforward so we can just Traverse the even nodes so we can just say like okay you know let's just start over here and let's just actually so let's say we're traversing and let's say we're going to do this color we're just going to start over here and we're going to Traverse until we are now and we're going to Traverse every other node because we want to Traverse original nodes and we'll just say like okay well here's what we can do so if seven has whatever random value we can just say the node after seven has the value of the random value of 7 dot next right or if its value is null then we'll set it equal to null so for seven its random value is null so the node after seven will have a random value of null and we will represent it with this Arrow here so it's going to be null then we will Traverse over here and we're going to say okay does this have a random value yes it does that means that the random value of the node after it will be the random value of whatever this is but it'll be the next note right so we can write that down So Random value of node after occur equals random or I guess yeah it's random right yeah random pointer it's a random pointer will be random pointer of her and then it's going to be dot next right so whatever the curve points to it's going to be the next one and that's because these are all duplicates right so if 13 points to 7 that means this 13 needs to point to the next seven that's why you just go to whatever random value points you can check the next one so this 13 will point over here now and then we go to the next node right so we Traverse every two nodes we can just say like cur.next.next now we can just say like cur.next.next now we can just say like cur.next.next now we are over here and we're going to say okay does this 11 have a random pointer yes it does so then this 11 is going to have a random pointer that's going to be whatever this is pointing to but the next one so this 11 will point over here and then we will go to the next one 10 does it have a random pointer 11 okay so then this next one will point to the next value right after 11 which is over here and then for one same thing it's going to point to the 7. so I know there's a lot of arrows kind of confusing but that's essentially what it is so now we have all our random pointer set up and you see that these new nodes these Brown random pointers are pointing to all only new nodes and now essentially we have a list of old node new node and so on so now all we have to do is just split it up and so when we originally created this list I forgot to mention we're going to have a dummy node so we'll just have some dummy node point over here pretty straightforward and now essentially we need to break this list up into the original list and the new list right we want to like maintain the structure of the original list ideally because we don't want to we want to like give the inputs the same way they came so what we can do is we can just make a new dummy node we'll call that like new list or something and essentially all we have to do is just go through the old list so we just go through the old list so you could do this one of two ways you could do this uh by making two new lists or you could just take this original list and use that for the old list and then this is going to be the new one then that's what I'm going to do so essentially you start once again at the very start over here and you just say okay as long as that's not null the next pointer of whatever I'm at needs to go to the new list so this is going to have this new seven I'm not going to show the random pointers but they will still be there I'm just not going to show them in this because it's just too much stuff so essentially the next pointer will go to the new list and then just make the next pointer of whatever I'm currently at instead of it's next make it's next right so essentially that will get rid of this in here so it will do this and then we will be at this node and once again we want to do the same thing we want to split it up right so we're going to say the next pointer of this is going to go over here so we're going to put 13 here and then the next pointer of this make it instead of this dot next equals 13 you can just say something like Cur dot next per dot Max dot next and this one line will essentially just update this pointer to point over here and so that's what we are going to do and so we will delete this section and now we will have the pointer like this so I guess maybe I should draw these in blue because it's a little unclear essentially this is blue and the same thing here we are at this node so now we need to say okay let's take the next of this and put it in the new list so we're going to have 11 over here and then once again 11.x equals and then once again 11.x equals and then once again 11.x equals 11.next.next which will make it point to 11.next.next which will make it point to 11.next.next which will make it point to 10 so we are going to get rid of all this point to 10. and then same thing right so this points to 10. and then this is like this and for the 10 same exact thing so we're going to put in the 10 over here the second 10. and then we need to do the same thing here so we need to make this next point over here so we will do that but yeah if you want to do this using two lists that's totally fine too like you can make two new lists and you can split this up that way okay and now finally for the one we are at the one so one last time we need to put the one over here and finally this one will now point to null so now points to null and so these Brown lines they will persist in these new nodes like these new nodes random pointers will still point to each other I just haven't drawn that so when you move these like pink nodes around their random pointers will persist it's just their next nodes will change and also similarly the random pointers of these original nodes will persist so now we have the old list and we have the new list and now we simply just return the new head so that's essentially the steps let's go over it one more time right so you take the list and you put in a new node after every single node that's just going to have the same value as the node originally had so you'll have like seven thirteen eleven and so on then to get the random values for the new nodes you just take whatever the random value was for the old node the one right after it and then you just say let's take whatever that is and let's take the next of that one because that'll essentially be the new node so you're essentially doing like an In-Place hash map where doing like an In-Place hash map where doing like an In-Place hash map where you could say like okay the node I'm currently going to the new node is going to be the one right after that so it's kind of like the same thing as the hash map only you're doing it in place basically you're making these Connections in a linked list and then finally when you do have this list of new nodal node or sorry old node knee node old node and so on then you just break it into two lists and you return the new head and now notice our old list still has the original structure that it came in with right so 7 13 11 10 1 the original list here Anna points to know so we basically manipulate our input but then we kind of change it back to be what it was okay so now we have enough uh to code it and I will say doing it in place is definitely tougher so I think it's like getting to the harder there's not too much code and I will also say when you do this I would strongly recommend drawing this out as you go because once you get enough like once the complication gets big enough and like this I feel like it's really hard to visualize exactly what's going on and TC make mistakes so I would like write out code and then maybe do like a dry run of like okay what is what does my linked list actually look like as I go just to make sure it's correct because it's very easy to run into errors okay so we can actually get rid of all actually we'll keep this for now and also yeah you want to keep in mind the initialization for the node because they're different all the time like here that you do have to give it an x value it's not optional and then it also takes an x to the random okay so essentially we're going to make a dummy node first so it's node and we're going to give it some value and It'll point to the Head and now we will essentially take that original list and we will just insert a new node after each original node with the same value and just a random pointer equal to null for now so we can say wow ahead dot next equals node it's going to take head.val head.val head.val and then it's going to point to head.next head.next head.next right so if you have something like 7 13 whatever as your nodes essentially you're putting in a seven here and you're saying let's let that seven point to 13 and now we'll let this original Seven point to 13 by saying head equals head.next.next so this original seven points to the new seven and then this new seven will point to the 13 and then we want to iterate two notes forward because we made a duplicate so that's going to give us our list of new node new nodal or sorry old no new node old node new node and so on then we need to Traverse through it and put in the um random pointers so and the easiest way that's why you want to do it in two pass because you don't want to like if you don't do it in two pass you might try to put a random pointer to a node that doesn't exist yet right like if you have some nodes like one three seven whatever it is like the random pointer of this might be all the way over here and then you don't even have that new node created yet that's why I'd recommend doing it in a few passwords where you create the notes first and then it becomes a lot easier to put in random pointers and once you realize that I think it makes it a lot easier to figure out how to do the random thing you can just do it in multiple passes so now we are going to do another pass essentially where dummy.nex will be the essentially where dummy.nex will be the essentially where dummy.nex will be the new head of the list so we can just say while Kurt if kurda random meaning if the node so we're going to Traverse old nodes and um if the old node has a random value that's not equal to null then we're going to need to update then the um random value of the new node so we can do this current x dot random plus curve.random dot next plus curve.random dot next plus curve.random dot next and that's essentially because the random pointer of the new node is going to be the same as the random pointer of the old node except it'll be the node right after that because that's the Clone node okay and then we are going to do the same thing we're going to move it up two nodes at a time because we all want to go through the old nodes so now we need to split up this list into the new list and the old list and we're going to keep the old list in place so we can just say new list equals node zero and then we can make a curve so occur a new Cur equals dummy dot next is where the whole list starts the new and the old combined and the new list will be this new Curve will be where the new list will go so we could say Walker and then we need to essentially break this list up into both parts so we can say new Cur dot next equals curve.next say new Cur dot next equals curve.next say new Cur dot next equals curve.next meaning if we're at some node the node we want to add to the new list is the one right after occur it's the new node because we're going to be traversing old nodes then we could say occur.next nodes then we could say occur.next nodes then we could say occur.next equals per dot next so essentially we're saying you know if we have something like this 7 13 when we do let's say we're on seven we do let's say we're on seven we do let's say we're on seven it's query.next.next essential we're it's query.next.next essential we're it's query.next.next essential we're saying the seven now points of 13 so we got rid of the duplicate and then we need to say current equals Cur dot next to actually move up to the new node and finally we need to say new curve equals new curve.max to move up on curve equals new curve.max to move up on curve equals new curve.max to move up on the new list as well and then we need to return the new list dot next it's about next because new list will be the dummy head of the new list oh and I think that's it so let's see how this goes next and yeah you don't have to check for like next.next because assuming all your like next.next because assuming all your like next.next because assuming all your list is always going to be um your list is going to be uh an even length there will always be like a next World we know so let's take a look so we can see it's reasonably efficient and like I said you do have to do multiple passes here maybe you can shorten the past but the time and space is still going to be the same so here for the time it's going to be we're basically doing like a few passes through this old list right and then sometimes we're passing through a new list so if the old list had end nodes sometimes it will have sometimes the paths will take end time sometimes it'll take two end time but whatever you know you'll have some multiple of n which rounds down to n and then for the space we are making new nodes but those are that's part of the results those don't count and then we are making a few dummy nodes but we're only making two it's not like proportional to the size list or anything it's a constant number so the space is going to be 01 for this one and yeah so hopefully uh you got that one and like I said once you realize that you just want to fill out these randoms after you create the whole copy it becomes a lot more straightforward I think that's the toughest part of this problem is like trying to fill out these random nodes before you actually created the new nodes and then you'd be like well I didn't create it how do I go through that so yeah that's gonna be all for this one hopefully you liked it and if you did please like the video and subscribe to the channel and I'll see in the next one thanks for watching
|
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
|
883 |
hello welcome today let try to solve another lead code problem 883 production area of 3D shapes so we are giving a 3D shape actually this shape is just a grid so this means uh each of the rows and each of the columns it would be like a square for this array yeah and we can check yeah as you can see the grid dot length should equal to grid I do lens it is a square so this is the grid and N is not a very big number it is just 50 maximum and we want to calculate the sum of the three projections so the projections is just from the three side you can look down and you can look from the left side and you can look from the front side yeah so let me just use ex this example to explain it actually this is not a difficult question yeah even it is uh the ometry problem but it's not so difficult what we should do first we need to yeah just use this example to make it to be a 2d array and this would be easy for us to analyze the problem yeah but for writing the code you need to think a little bit about it yeah you don't need to use uh to write many lines of code especially while you are using python because there are so many methods in Python to make the writing of the code so elegant now let me just prepare uh variable n because the rows and columns they are equal so I'm going to just use this n should be length of the grid now I going to defy three variables so I'm looking from the left side and then I'm looking from the downside and then I going to look from the front side so let me analyze so if I look from the left side or the right side it will be the same yeah so for this number 1 2 3 and four if I look from the left side I going to choose the maximum number so this two and four would be yeah would be the final result I believe if I look from the and left side yeah now let's let me just yeah get the final result it would be just the sum of the uh sum of the result yeah so inside the sum it will be the maximum of the array so this array should be inside the grid so this is looking from the left side it is not so easy to write the code as you can see it yeah just one line of code and now let's just look down so it means we yeah we are higher than the building we just look down it means 1 2 3 and four the final result would be four because it is just 1 + 1 + would be four because it is just 1 + 1 + would be four because it is just 1 + 1 + 1 + 1 and we can check also some of the 1 + 1 and we can check also some of the 1 + 1 and we can check also some of the numbers can be zero it means if there's no building we're going to not count it yeah so this should also be easy we just need to use a sum inside it would be greater R and C so for R in r n and for say in r yeah but for this grid RC should be more than zero because it is not the number itself it is just a booted value if it is more than zero we're going to count it as one if it is a zero yeah because there is no negative numbers it must be zero and positive so we're going to check if it is more than zero we're going to C it as one if it is a zero we're going to not count it so we're going to yeah just not count it if it is BU value it is true so we're going to C it as one now we are going to calculate the front basically for the front it's difficult to calculate if you don't use a yeah n NP from the python machine learning library if you use NP yeah you 2D array to another 2D array to this one you're going to compile this one and three two and four and you get the result but currently we don't need to do that because uh in L code while you are using NP it will be much slower so we can use another way uh actually there's uh another way let me uh try to explain it so still we're going to use the sum of the max array but this array would be inside zap so for array inside with zip so we just need to zip the grid yeah but here we're going to use a star so this star it is a similar like the JavaScript code this structure so for this grid it is basically a 2d array if we use a star it going to be just two it going to just turn the to the array into two arrays one and two three and four so basically we're going to zip it so one and three would be combined to this array and two and four would be combined to this array we just check the maximum yeah so one and three combined the maximum is three 2 and four combined the maximum is four so this is seven and this is four 7 + 4 so this is seven and this is four 7 + 4 so this is seven and this is four 7 + 4 it is 11 and this is six as we uh calculated earlier this is 2 + 4 so this calculated earlier this is 2 + 4 so this calculated earlier this is 2 + 4 so this is the final result it is a 17 it should be right yeah now we just need to return this left plus down and plus the front so this is from the three sides yeah if you are using other languages maybe you don't have such method you might write more lines of code yeah basically this going to be easier for python by using the zip and by using the two for Loops in one line yeah by using the sumary max now let me just run it to tck if it works as you can see it works now let me submit it to tck if it can pass all the testing cases as you can see it passed all the testing cases and it's pretty fast thank you for watching see you next time
|
Projection Area of 3D Shapes
|
car-fleet
|
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes.
Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`.
We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes.
A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side.
Return _the total area of all three projections_.
**Example 1:**
**Input:** grid = \[\[1,2\],\[3,4\]\]
**Output:** 17
**Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane.
**Example 2:**
**Input:** grid = \[\[2\]\]
**Output:** 5
**Example 3:**
**Input:** grid = \[\[1,0\],\[0,2\]\]
**Output:** 8
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 50`
* `0 <= grid[i][j] <= 50`
| null |
Array,Stack,Sorting,Monotonic Stack
|
Medium
|
1902,2317
|
1,515 |
hey everybody this is Larry this is q4 for the reason kinda sit to like magnets of the eye one join my discord and hang out and chat about these problems anyway for best position for a service center so for this problem I think I'm trying to figure out how to best describe it I think well first of all you're wondering whether you need to know this for an interview I would say no I there almost every other problem on the code is probably better for you to learn before this one I think like it's a cute trivia maybe there's an easier solution I'll have to kind of revisit this later in the video but the way that I solved it's not really everything that I would expect anyone to know or that it would appear in an interview III said it jokingly but I still believe it is that if someone gave you this problem on an interview maybe just you know kindly thank the interviewer say your goodbyes you know get your jacket get your stuff and just head out because they never really wanted to interview anyway unless you're doing some kind of geode job or something maybe I don't even know but yeah but basically the problem and this one is you're trying to find the center with you minimize or lilian distance and there's really no easy way to think about how I did it because the way that I did it to be honest is that I've solved this before and the way that I solved this before was that I looked it up the answer so I spent a good amount of time on during the contest trying to find my own solution I wish i Carol eyes it so maybe that's something that I have for learning for this one is count categorize your pass code or whatever because I didn't remember this I mean I had some angling pit but this is so far remote from what I have been practicing that I don't remember like I couldn't we prove this from first principles or anything like that but yeah but basically when I would recommend is Google geometric median and a couple of algorithms and that's pretty much how I served it I know that this is a cop-out I don't because this is you know cop-out I don't because this is you know cop-out I don't because this is you know this is a descent of being a linear programming type of optimization problem and in the general case it's gonna be tricky I think it's possible that two constraint where you only have 50 points and also they're within a hundred allows you to get away with you know something that maybe it's okay but I'm even though I got an accepted answer I was and I still am not confident about a lot of numerical every type things but yeah but I did implement this I could go over a little bit but it's really just a lot of guesswork I don't know how I would explain it to you in a way that isn't research EOB yeah it would have to be a different video but yeah I think yeah I take a so basically what I did and I don't even know this is the optimal way to write this algorithm it's just been a wild that's just how I did it last time which is that I think the geometric mean which is not the geometric median to find a candidate for the center point I also look at each point to see if it could be a possible candidate for a center point and then from that I look up down left way to kind of see where I can go to see that I could find a place that is closer to give me a better answer and once I found it I try again to kind of it I when I was talking about it reminds me a little bit of simulator and annealing but not really and these constants I can't really prove it I just it was kind of gut for you and guesswork the doubter is a hundred because the positions are between so and hundreds hours I go okay that prize should be good enough a thousand is just a big enough number that isn't too big because if it's too big then you may want into performance time issues and I don't want to get a time limit exceed it but a thousand seemed enough that conceptually once you do enough steps it'll converge I think in having in the classic version of this there actually you can't get stuck in local minima s-- I believe I could be in local minima s-- I believe I could be in local minima s-- I believe I could be wrong on that one which is you know this is like research east of so which is why I keep on saying that I don't you know this is a silly problem for an interview but yeah I did a thousand because I figured that it should probably convert by dad in a way that like if it's binary search I mean it's not quite binary search so it's not that but you only need a hundred loops of binary search to I mean less than that really you wanna do the math one on how much bits you can store about you should do like a hundred just to be lazy and that's good enough because you're your doubter would be smaller than whatever it is that you're trying to find anyway so I did a thousand for that reason anyway I know that this explanation is kind of crappy probably but it's just me trying to say that I don't think this is a reasonable problem so I would say if you are trying to learn this learn it because you wanted to learn it for fun for an interview I cannot imagine sing or an interview anytime soon and if you do then just accept that life is unfair and hope for better luck next time anyway you could say to watch me do it live right about now one but yeah that looks good mmm good best position for service center so this one I actually have some trouble with I remember some so this is just what experiment buys you a little bit and I don't know that I would you know get it any other way don't you know do the top person shall did it about three minutes so a really experienced person would get it even quicker but for me and I'm gonna skip forward a little bit bad I just want to say yeah because I just thought about this point I was doing paper for a little bit but died but the sort of idea is that uh I was a little bit aware of the solution because I have done similar things before for a commutation of geometry evening I knew two things one is that is called the geometric median so it's a very standard thing well not very standard but I also knew that there was no easy algorithm or well I would say that there's no it's not an easy answer the reason why this worked a little bit and was because that when you look at the bounce it's only within a hundred times 100 bounding box or that position doesn't have to it's not that much of a worry but it's still like a to be frank a very crappy question for an interview and maybe even for this kind of contest because well it's not really with like we already I don't but yeah so I'm gonna skip ahead real quick don't be a link below so that you could follow along but because I literally don't do much like I was cuz I so what I'm doing here is that I'm either playing around paper trying to draw some stuff try see if there's any like weird dynamic programming that I missed or but I knew that wasn't the case or I've figured out that it wasn't the case because I was like no they you know just you cannot or for me I couldn't figure out any way to pull out like linear component or whatever its core meaning that I couldn't figure out like a way to symbolize because they all depend on your child in a way so that I was trying to and then I spent some time looking over my cuz I so I went in similar cone for this for before so I was trying to find some recall for that before I'm not gonna explain it life i'll doing the explanation portion but I did have code win for this that's how I kind of I was trying I spent a bit of time actually looking for my own code bases because I didn't younger Larry didn't care I stuff or didn't have keywords that he could search so but now he could maybe I need to a better job that's another story yeah I'm gonna skip ahead so stay tuned how about this don't know enough math for this one we have no idea people can you told us what people have garnet welcome back but yeah but basically I wrote up the template for because I knew that I was going to need it because I knew it was some sort of search album so this part I you know I mean and it should be straight for which is that given a Center X&Y that's how you given a Center X&Y that's how you given a Center X&Y that's how you given a center X and why that's how you calculate the total distance where the total cost function that you're trying to get well now I'm just I gave up oh I took a look quick look and be like yeah right now I'm just doing the really basic thing of playing around with the geometric median and here I just literally took the arithmetic average to find the center and then calculate that and I'm just playing around with it a little bit and I was like okay that's not that close I'm I knew that was not close I guess but uh but still yeah and then after that I was like okay let's test out the point I mean I think I found my original code but I was trying to just really understand him how it works again and it's hard to try to learn what you used to remember from like Sabo this code may be like a decade ago so it took a long time to find it and it took me like mmm that was it like and it's not plug and play right well I wouldn't C++ because play right well I wouldn't C++ because play right well I wouldn't C++ because it was ten years ago but it's not plug and play right so like I was like mmm do I really believe past Larry what has passed now he done you know I don't know he I wasn't sure to be frank I think that's the kind of thing and now just playing around with the result in there we go but yeah I kind of it so the way that I try to think about this is some sort of simulator and owling annealing not quite though to be frank I mean I think that's just the way that my mental motto is so definitely to be pedantic yeah pathetically it's not simulated annealing but it's just how I thought about it and I was like oh wait I need to get the updated thing yeah and so I took a thousand because it's just a random number to be honest but it just I figured that so it to me what I was thinking at the time was that it was kind of like binary search evening and that after a certain number of loops we should be able to converge but to be frank I don't have proof for this one yeah now it's like okay what am I doing here just double-checking my code because so just double-checking my code because so just double-checking my code because so what I do when I am doing new things is that I'm especially now I'm trying to be a little bit more careful and one thing that I'm happy about for this contest is that I didn't get any wrong answers because recently that's been plaguing me but yeah I don't have any proof on how just one converge my thing I'm 1,000 is just one converge my thing I'm 1,000 is just one converge my thing I'm 1,000 is kind of similar to binary search where after a certain number of elevation it doesn't really matter way so yeah pretty much I mean I was were defying that it was correct but after I died it was good I did okay
|
Best Position for a Service Centre
|
find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k
|
A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i] = [xi, yi]` is the position of the `ith` customer on the map, return _the minimum sum of the euclidean distances_ to all customers.
In other words, you need to choose the position of the service center `[xcentre, ycentre]` such that the following formula is minimized:
Answers within `10-5` of the actual value will be accepted.
**Example 1:**
**Input:** positions = \[\[0,1\],\[1,0\],\[1,2\],\[2,1\]\]
**Output:** 4.00000
**Explanation:** As shown, you can see that choosing \[xcentre, ycentre\] = \[1, 1\] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.
**Example 2:**
**Input:** positions = \[\[1,1\],\[3,3\]\]
**Output:** 2.82843
**Explanation:** The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843
**Constraints:**
* `1 <= positions.length <= 50`
* `positions[i].length == 2`
* `0 <= xi, yi <= 100`
F(0) = 0, F(1) = 1, F(n) = F(n - 1) + F(n - 2) for n >= 2.
|
Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process.
|
Greedy
|
Medium
| null |
1,209 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem is remove all adjacent duplicates in string so we will be given a string and an integer k a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them so k adjacent equal letters means like if k is 3 so a is occurring three times that is k times then we have to remove those three a's causing the left and the right side of the deleted substring to concatenate together what does that mean c for example we have a string a something like this we have right and k is 3 so we will find out if there are adjacent e same letters and count should be equal to three or equal to k which is three so see these are same letters and that three letters right same which is k so what we will do we will remove these three so when we remove this the left of the this substring this is the substring right because they are at the same so left of the substring and right of the substring will concatenate together so b and c this will be the final string okay so we repeatedly make k duplicate removals on s until we no longer care return the final string after all such duplicate removals have been made it is guaranteed that answer is unique okay so see uh here there is k is 2 but there are no duplicates it's the same duplicates so obviously there is nothing to delete and this will be the output let's see this test case okay so here i am removing just erasing this so for this test case we have k is equal to 3 okay so first step what we need to find adjacent same how many letters k letters that is three letters and we have to what do what we have to remove them remove so see here e are there are three occurrences of letter e same letter and that to adjacent right so we have we will remove this so when we remove this what will happen d and this d will concatenate right and rest of the string will be same bb then three c's and b a okay now they have written that we have to repeatedly do this k duplicate removals until we no longer carry so just find out see there is one the c is also occurring three times together adjacent so we will remove this also so when we remove it we will get dd bb this is get this is removed so b and then d a now see again we get this bb together so we will remove that and when we remove it we'll get b d and then this b and then a so again we get three d's together we'll remove them and we will get a as the final string so output will be a okay see output for this is a so i hope you understood the problem now let's discuss how we can approach so see guys one simple brute force approach is which directly comes into our mind is that we will find out k like if there are k edges and letters and if they are we will just remove them simply okay so see that how we can do we have this e right here e so see for example i will be iterating first of all i'll have i pointer i will come here i will check whether there are three k occurrences case adjacent same letters if there are edges and same letters what i will do i will find out i will just concatenate this string till this i and i plus k that is still here so i will pick this substring whatever was before this i and i plus k from i plus k substring till this so i will concatenate this in this together d be like this and rest of the string and i will do this for entire strength i will shift i here that is here at this position right so this is like how i can do it brute force so for this what will be the time complex see one thing is that we will be iterating on this entire string each letter will be hydrating and for every we will be checking whether there are adjacent k elements or not right whether there are adjacent k elements or not okay so what it will be we'll be traversing the entire string n and for each we will have a for loop right we have a for loop in which we will be checking the k letters so n into k will be the time complex so i hope you understood this one approach right but this is not efficient okay so what we will be doing is we will see another approach so let's see that here let me write this case again so d e d b c so see here k value could be 10 raised to power 4 right so 10 raised to the power 5 into 10 raised to the power 4 will be 10 raised to the power 9 here this could be 10 raised to the power 9 hence it will get tle okay so pb we have bb c three times and then d a okay and k is three so now guys see what we need to do is we need to let's say we are here so we need to check whether there are previously k minus 1 same letters or not like if this is let's say i so before i or after i there should be uh k minus 1 same this letters like e okay this we need to check so see guys whenever there is something like we have to check previous characters right previous characters or any previous element we need to check then what we can think of using a stack why because in stack we store the previous elements for example if i am traversing the string so i'll store this d then i'll go to e then i'll again go to e okay like this i will be storing the previous characters again i'll go to e then again go to d something like this so you can use a stamp now pause the video and try to think how you can use tab in this scenario so see guys i am storing this three times what if i just store like this is this e i do not store individually if i am getting same e again and again like adjacent e's i will be storing the count of that is like e comma three so if e is occurring three times that is k times then i will just simply remove the c don't worry you will get it let's diagram once so see what we will do we'll take a stack okay we will be taking a stack and we'll start iterating and in stack right we'll be storing a pair in pair what will be the two elements first will be the character whatever the character is we are inserting in the stack and it's count okay so for first of all we traverse we go to d there is nothing in the stack like stack is empty so first of all we will just insert this d with count one okay now i go to e i just simply insert this e with count one then i go to this e now i will check every time i will check right every time i will check whether this letter is equal to the top this top pairs first element or not this is e equal so i will just increment this count and it i will make it two okay again i'll go further i will check this e is similar to the top and top pair this is pair at the top right so and this e is equal to the first element of the pair so i will just simply increase its count so this will become three now see guys this three count is equal to k hence we can just simply remove these three edges and keys from our string so what i will do i will simply pop this from step fine now we go further we get d now just see this d it's equal to the top element in the stack so i will just simply increase its count so see guys obviously when these e's are removed right this d and this d will come together so that's why d two times then we go further we go to b is not this b is not equal to this d so b will add in the stack and its count will be initially 1 then we go to next b its count will be again 2 because this b is equal to this then we go to c now this c is not equal to this b so we will include us we'll add a c and count will be one so we go to this another c same so count increase again go further c and c count increase it becomes three then we go to this d oh before going to this d see this count has become equal to k so we will just simply remove this from the stack so these also are removed these three are removed now we go to this d is not equal to uh here this b right i think i have missed something so after the c right there was a b so after these three c's there was a b here so we go to this b right and this b is equal to this b so count will become three here and this 3 is equal to k so we will remove these b's so this right this b these three b's are removed after that we'd go and find t and this d is equal to this top element so its count will increase three so we again we get count three which is equal to k so we will remove this also that is see this d and this b are removed then we go to this a stack is empty so just simply add a and count one and then again we go to this a same letter so we just increase its count okay now we have traverse the entire string and we will just simply pop from this stack and we will see a is two times so with this will be the output okay and one more thing guys here right now here there is when only one element in the stack but let's say for example here in the stack we have a b two times right so then when we pop from the stack right string will become b this b will come out first then this a will come but we have to reverse this right we have to reverse this will be the final string why because this is inserted for before right so obviously it will be first in the string so this needs to be reversed so i hope you understood the approach and the gyro now let's see the code once try to write code by yourself make cases so see first of all obviously if size of the string is less than k just simply returns a string take the stack will have a pair corrector and the integer that is this character and its count so we will iterate on the string okay and if the stack is empty or the stack talks first stack stop see stack stop will be appear and the first element of that pair will be the character so if that is not equal to s of i that is this character is not equal to the current character so we add the pair in the stack with count one otherwise what we do we will pop that pair from the stack we will make a new pair and we will increase its count by one for example if d was like b two times and d again comes so we will pop this from here two plus one we will do three and then we will include add the pair in the stack and if the stack stops second that is the count right this count becomes equal to k so just pop that from the stack so after this we will make the answer string just keep on popping from the stack and how many times the count is there of the stack just add that element in the answer that many times for example b was two times so answer string will be b then a was two times so a and after that we will reverse the string so it will become a b so i hope you understood the problem and the approach time complexity is o of n we are doing single traversal and uh space is also often because we have taken a stack so if you found the video helpful please like it subscribe to my channel and i'll see in the next video thank you
|
Remove All Adjacent Duplicates in String II
|
design-bounded-blocking-queue
|
You are given a string `s` and an integer `k`, a `k` **duplicate removal** consists of choosing `k` adjacent and equal letters from `s` and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make `k` **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It is guaranteed that the answer is **unique**.
**Example 1:**
**Input:** s = "abcd ", k = 2
**Output:** "abcd "
**Explanation:** There's nothing to delete.
**Example 2:**
**Input:** s = "deeedbbcccbdaa ", k = 3
**Output:** "aa "
**Explanation:**
First delete "eee " and "ccc ", get "ddbbbdaa "
Then delete "bbb ", get "dddaa "
Finally delete "ddd ", get "aa "
**Example 3:**
**Input:** s = "pbbcggttciiippooaais ", k = 2
**Output:** "ps "
**Constraints:**
* `1 <= s.length <= 105`
* `2 <= k <= 104`
* `s` only contains lowercase English letters.
| null |
Concurrency
|
Medium
| null |
1,905 |
hey everyone welcome back and let's write some more neat code today so today let's solve count sub islands a problem from today's leak code contest we're given two different grids m by n so basically each of these grids is guaranteed to be the exact same size that's good for us they're all containing either zeros or ones zeros represent water ones represent land and we want to count the number of sub islands in the second grid so this is grid two we want to count how many sub islands it has now what exactly is a sub island well first of all an island is basically a set of contiguous ones basically horizontally or vertically right you can't go diagonal but you can go up and down left and right so this is one island and this is a second island down here so what makes this red one a sub island basically if you look at an island in the grid one you can see that this sub island has a corresponding island in grid one where basically every single cell in this case there's six different cells are included in this island and not only that there happens to be an extra one but extra ones are perfectly fine we just want to make sure that every single cell in the island here is also contained in a single island in grid one you can see it's made up of a single island in grid one right so that makes this island a sub-island now let's go through the sub-island now let's go through the sub-island now let's go through the other islands here we have a single island it's not connected anywhere else vertically or horizontally does it have a corresponding island in grid uh one it does not so this does not count as a sub island let's go to the next island over here this is a single island by itself does it have a corresponding island in grid one yes there's a corresponding big island like this one which includes every cell from this one but this only has a single cell right so that's basically made up of a island in grid one that's good now we have another sub island over here right that's made up of that exact same island we just went over but that's perfectly fine it could be that two sub islands in grid two have a single you know larger island in grid one that still means these two are separate sub-islands we still sub-islands we still sub-islands we still count them and lastly we have this island over here now it's a yellow meaning it's not a sub-island and if you meaning it's not a sub-island and if you meaning it's not a sub-island and if you look over here uh you know it does have a single uh corresponding cell but the other two are water we needed both of these two over here to be yellow to be islands uh for it to actually be a sub island but that's not the case so this is not a sub island so in total we counted one two three sub islands so on our output we are going to return three now a really naive way to solve this problem would basically be okay get every single island in grid one map the island to a list of its coordinates so you know zero is one coordinate zero one is one coordinate you'll get that entire list of coordinates do the same for every single island in grid two and then just check for every island in grid two does there happen to be a island in grid one that contains every single cell now that's obviously not gonna be super efficient and it's gonna be kind of a pain to code right you're gonna have to compare basically two hash maps together try to find how many sub islands are here that can be made up in grid one a more intuitive way and easier to code ways basically do a simultaneous dfs so the goal is go through every position in grid two find every single island right first position we find an island then we're going to traverse this right basically to traverse the entire island get every single cell in the island of course we're going to end up going through every position like this now of course if we went out of bounds or if we reached a water cell we would not continue right but basically we're going to traverse every position here and at the same time we are going to be looking in island or in grid one and checking for every one of these positions that we visited that we found a one at meaning it's an island was there a corresponding one in grid one if there is then we're going to return true if we find even a single one like for example maybe this was water and you know we're checking does this show up as a one over here if this was water then we would have to return false this is an island this is a contiguous island but you know there happened to be a cell that did not correspond in grid one so therefore this is not a sub island but that obviously wasn't the case right if we do a simultaneous dfs we're going to end up traversing every position like this right because these six correspond to these six over here we're gonna see there's a one in every single position over here so then of course this is a sub island so we can return true meaning we found one sub-island we're going to add that one sub-island we're going to add that one sub-island we're going to add that to our total so our result so far is going to be one we found one sub-island and of course we don't want sub-island and of course we don't want sub-island and of course we don't want to have to visit the same island twice so we're gonna you know as we cross these out we're gonna add them to our visit set so we're not gonna want to visit the same island twice of course now we're gonna traverse through every other position right we're gonna say okay this is water okay now we found another island right so we're gonna traverse this island it's only one position right so we cross it out we visited it but before we're finished we want to check did it have a corresponding island in grid uh ingrid one it did not right so yes we visited this yes we traversed the entire island but it did not it's not a sub island basically so our result is going to stay one and we're basically going to continue this algorithm right this is going to be water we're going to do a dfs on this island see that yes every position in this island had a corresponding one in the first grid so yes we're going to add that to our result we're going to visit this and we'll do the same here right we'll do a dfs here but we'll see that yes there was at least one position that was water so that one of these cells could not be found and so this is not going to be it so that's kind of the main idea if you uh are trying to you know figure out maybe a similar problem to this it's kind of like in a certain binary search question where for example you're comparing two trees excuse the drawing which is kind of overlapping with some of the text but you know if you're comparing two trees and you're checking do they have the same values you would basically do the same thing right you'd start at two pointers both at the root of the tree you'd compare the values are they equal yes then you'd recursively compare the left subtrees of each of these you'd recursively compare the right subtrees as well so that's kind of the intuition of this problem we're doing a simultaneous dfs on both of these grids we can do that in o of n by m time where these are the dimensions of the grid and that's also going to be the space complexity because we're going to have a visit set with the same dimensions to make sure we don't visit the same positions multiple times that being said let's finally jump into the code now so this problem is going to be about 20 lines of code so the first thing i like to do with graphs is get the dimension so get let's get the number of columns and rows in these grids remember both grids are the exact same size that's going to be really good for us we're also going to have a visit set to make sure we don't visit the same position twice in grid 2. and we are going to use a dfs function so we're going to pass in the coordinates that we're currently doing dfs on and i'm going to fill out this function in just a bit so what we're going to do is basically go through every row in our grid and every single column basically go through every coordinate in our grid and we're going to run dfs but of course we don't want to run dfs on the same grid we're on the same position twice and we only want to run dfs on grid two if we found an island portion so basically if this position is equal to one or in other words we can just leave it as it is so if this evaluates to true and this position hasn't been visited so if r c uh not invisit and if then we're actually gonna call dfs so we're doing this in the conditional statement we're gonna call dfs on this coordinate and if it evaluates to true we're going to take our result which is going to be count increment it by one so let me actually define that result up above so count is initially going to be zero count basically is the number of sub islands in grid two if this evaluates to true meaning you know this island that we just found an unvisited island that we just ran dfs on if it happened to have a corresponding island in grid one then it happens to be a sub island then we can increment uh count by one and at the end we're just going to return whatever account happens to be so now we're going to do the actual uh meat and potatoes of this function which is going to be the dfs so our base case is always going to be if we go out of bounds so first let's check if row is less than 0 or column is less than zero or row is too big meaning it's exactly equal to rows or column is too big meaning it's exactly equal to columns or we're going to continue if this position is water basically if grid two of row column is water or is equal to zero then we're also gonna return or if this position has already been visited we're also gonna return right so then we're gonna return now what value are we going to return false or are we going to return true well just because we found water in grid 2 doesn't mean that this island is not a sub island right of course we're going to have to find some kind of base case we're going to have to reach the edge of this island at some point so we are going to return true in this case this itself does not mean that the current island we're visiting in grid 2 is not a sub island that's going to be the next condition i'm going to show you so basically you know we if this did not if we did not return up above that means grid 2 is land meaning grid 2 is a 1. but if grid 1 if the value in grid 1 is equal to 0 that means grid 2 is land but grid 1 is water remember that's the case where we know this is definitely not a sub island so that's when we're going to return false but we don't want to return false immediately so i'm going to have a result variable in this function result is initially going to be true but if this condition evaluates then we're going to set result equal to false we don't want to return immediately because we still want to visit the entirety of this island that we're at in grid two so we're going to do that we are going to run dfs in all four directions before we actually end up returning this result variable so we are going to return result but before we do that let's run our dfs in all four directions oh and don't forget uh we do have to update our visit so if we uh did not return up above that means this row column has not been visited so we can go ahead and add it to our visit set and of course i'm going to copy and paste this dfs four times because we're going to do this in all four directions so row minus one row plus one column minus one and column plus one and we do want to know what the result of these was so maybe it turns out that this portion of the grid happens to be a one so this if statement does not execute but maybe in one of these four directions we do find a cell in grid two that is a one but in grid one it's a zero meaning that grid two is not a sub island so we are this result variable we have uh we do wanna potentially update it so we're going to set result equal to the res the return value of this dfs and it with results so basically if any of these four dfs functions returns false then we are ultimately going to return false because remember all it takes is one missing uh cell in grid one for us to have to return false because we need to find every single one for this island if we find even a single one is missing for this island in grid one then we have to return false because then it's no longer a sub island so you can see it's about 20 lines give or take if you remove some of these spaces or you could probably figure out some ways to shorten it up but you can see it does get accepted in this contest i think this is about as efficient as you can get for this solution maybe after the contest somebody's gonna have some super insane solution that i didn't think of but i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Count Sub Islands
|
design-authentication-manager
|
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in `grid2` is considered a **sub-island** if there is an island in `grid1` that contains **all** the cells that make up **this** island in `grid2`.
Return the _**number** of islands in_ `grid2` _that are considered **sub-islands**_.
**Example 1:**
**Input:** grid1 = \[\[1,1,1,0,0\],\[0,1,1,1,1\],\[0,0,0,0,0\],\[1,0,0,0,0\],\[1,1,0,1,1\]\], grid2 = \[\[1,1,1,0,0\],\[0,0,1,1,1\],\[0,1,0,0,0\],\[1,0,1,1,0\],\[0,1,0,1,0\]\]
**Output:** 3
**Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
**Example 2:**
**Input:** grid1 = \[\[1,0,1,0,1\],\[1,1,1,1,1\],\[0,0,0,0,0\],\[1,1,1,1,1\],\[1,0,1,0,1\]\], grid2 = \[\[0,0,0,0,0\],\[1,1,1,1,1\],\[0,1,0,1,0\],\[0,1,0,1,0\],\[1,0,0,0,1\]\]
**Output:** 2
**Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
**Constraints:**
* `m == grid1.length == grid2.length`
* `n == grid1[i].length == grid2[i].length`
* `1 <= m, n <= 500`
* `grid1[i][j]` and `grid2[i][j]` are either `0` or `1`.
|
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
|
Hash Table,Design
|
Medium
| null |
73 |
hey everyone today we are going to solve the readable question set Matrix zeros so this is a one of our brand 75 literal questions so you are given M by an integer Matrix if an element is zero set its entire row and the column to zeros so you must do it in place so let's see the example so you are given this Matrix output is like this because we have zero at the center of a matrix so that means so entire this row and the entire this scrum should be zero right so that's why output is like this and then we have a follow-up question so could you devise a follow-up question so could you devise a follow-up question so could you devise a constant space solution so we have to solve discussion with the order r01 so let me explain how to solve this question okay so let me explain with this example so two sort of discretion so we have to solve this question like Embrace and constant time so that's why we use a first row in the first column as a like a node to keep track of like which row has zero and the which column has zero and if before that um so we are going to update the first row and the first round so that's why uh first of all we before that before updating we checked the so first of all has zero or First Column has zero so in this case uh all values are one right so we don't have a zero in the first row in the first column so um so I'll explain uh later so why we need a district and next we iterate through um except like a fast low and a fast run so that means this four position and then find the zero and if we find zero up to date current row and the column position so that means so let's say we find the zero here in that case update this position to zero and this position is zero so that we can definitely know so this row and this column will be updated with zero right so we just uh mark and then um list of um data is one so we don't update anything so if we have zero here so we also updated this position to zero and then um after that so we know that this row should be all zero and this column should be all zero so I'll put it a row with zero so now this here is zero and this is zero and we have to change this value to zero and also we have to update this program with zero so zero and we have to update here to zero and then um after that um so before we start um like a update uh each position so we take uh if first row has zero or not if we if First Column has zero or not but in this case initial values are all zero right so that's why we don't have to update everything but if initial value here this initial value is zero so in that case we have to update this row uh in the end right so in that case um we should update like a disgrace to zero also right so that's why uh we have to check if we have a zero in the first row and first one before we updating because after updating zero so which value is uh we don't know which value is the initial value or not so that's why so in the end so we um we create and we successfully created like a output Matrix like a one zero one so that's why we should return this uh output this Matrix yeah so that is a basic idea to solve discussion so with that being said let's get into the code okay so let's write a code first of all character is a ranks of row ranks or Matrix and the columns equal ranks of Matrix in the zero and first of all we want to check if we have zero in the first row and the First Column so we should have like a flag so far let's say first row has zero equals uh equal false so in the we have also we First Column has zero and a possible pulse so after that first of all check if the fast row contains zero so for column in range and the calls and if Matrix and the row should be fixed zero and uh move column and uh equals zero in the case um so this fast row groups zero should be to root and then break so let me copy this so we it is almost same thing for columns so take e fast column contains zero so we change rows and r and uh in this case R is like a dynamic and the column is fixed equals zero and the fast column has zero and three and break so after that um use the fast roll and the column um like a other note so after that so for low in range start from one two lengths of rows and we need ramaphool for column in lens and start from 1 to length of crumbs and if Matrix Arc and C equals zero in the case updates the first row and the first scrum so Matrix row and zero equals zero and then Matrix and the zero and the column equal zero and then after that um set the marked rows to zero so for R in range and start from one two rows rings of rows and if Matrix and the row and the zero equal zero in the case um Crump in lens and I start from one to lengths of grams and then up to date Matrix in this case r and the C equals zero and the read is almost same thing for ROMs so set marked columns to zero so in that case from one to lengths of grams and the C and uh in this case so row is fixed and the problem is dynamic equals zero in the case um so this one should be rows and all in The Matrix R and C equals zero looks good and so we need like a space so like this so after that um so sit the fast row to zero if needed so um before we start updating so we check if we have zero in the first row and the First Column and if we have update uh like a first row and our first grams two zero so if fast row has zero is true in the case for column in range and calls in The Matrix so row is fixed and the Chrome is dynamic equals zero and then I copy this so set fast from to zero if you need it so first call has zero in the case so this is a length of roll and they are so this in this case uh raw is dynamic column is fixed equals zero and then after that just return Matrix yeah and this is a really complicated and looks like uh all four of the is like a boil operate so I hope um I'm going to pass all cases once yeah so let me submit it yeah looks good and the time complexity of this solution should be order of M multiply n so where m is a number of rows and the N is a number of columns in The Matrix so this is because we iterate over all element in the Matrix twice so once in the nested Loop where we Mark the rows and the columns and once again in the loop where we set the marked rows and the columns to zero so that's why and the space complexity is o1 because we are using a constant amount of additional space to store the beryllium variables like a fast row hard zero and the First Column has zero and that we are not using any extra data structure that scale with the size of input metrics so the space complexity are remains like a constant 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
|
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
|
1,887 |
hello and welcome to another video in this video we're going to be working on reduction operations to make the array elements equal and so in this problem you're given an injur array nums and your goal is to make all elements and nums equal to complete one operation follow the steps find the largest value in nums and find the next largest value in nums strictly smaller and you reduce nums to the second uh smallest or the second largest and it doesn't really actually matter like they say like if there's a tie then pick the one with the smaller index or whatever but you have to basically reduce all of them so it doesn't really matter which one you pick first so in this example uh you have nums equals to 513 and so it takes all operations because essentially if we have 513 and I'm going to write this in a sorted way to make it a little bit easier to see basically you need to reduce the five to a three because you find the biggest element then you reduce to the second base element so you reduce the five to a three and then you need to reduce everything else down to a one because the biggest element is three next biggest element is one so this is one operation then we have two operations and three operations and in the second example everything's equal already and now let's look at the third example so we have 1 one 22 three so first what we need to do is find the biggest and reduce it to the second biggest so we need to reduce three down to two that's one operation and then we need to take every single two and reduce it down into a one so that's three more operations so we have four total so just to figure out like what algorithm to use even though this one is kind of straightforward we can look at the constraints and we have 5 time to the fourth so something like DP um on an N squ solution would probably fail I think 10 to the N would fail so you basically need an N log n or a o of n solution to make this pass and so right away the most common Solutions are you know for linear or something like that or sliding window or two-pointer or something like that so two-pointer or something like that so two-pointer or something like that so maybe we could do something like that um or like a binary search but let's kind of like figure out what we'd want to be using so probably not DP probably not something too complex not any kind of Brute Force we need like an N log n or n so basically what we need to do is we need to take the biggest number and convert into the second biggest number and there's a few ways to do this but the easiest way first of all like we want to know what the biggest number is quickly right because we have to have a fast solution so there's a few ways to do it but just to also keep in mind like if you have a bunch of the biggest number you want them all ideally to be found right away so there's two main ways of doing this problem um one is sorting and one is getting a dictionary of numbers and then sorting those but I think sorting I think the dictionary of numbers is going to run a little bit faster on Le code but it's going to take up space and the O complexity will be actually worse because it's taking up space essentially what we need to do is we need to basically sort our numbers so let's just say we have bunch of numbers and I'll just draw the sort right away so say we have like 1 2 4 8 12 24 or something so it's going to be very easy basically what we're going to do is we're going to take our biggest number and any number we find that is smaller we're basically going to take everything that we've converted so far and convert all of that into the smaller number and we can do this very quickly so what we're going to do here is we're going to have like the result we set equal to zero and then we have we'll have another variable called like nums we don't actually even need a variable we can just use an index so actually if I take this array and instead of writing it like this we could reverse it so instead of actually instead of reversing I'm just going to write the indices backwards but essentially our array is going to be sorted top down actually let's just rewrite it so let's yeah so in instead of sorting this way let's sort it the other way so we're going to have 24 12 and the index will tell us how many numbers we have very quickly so instead of having another variable you could have another variable as well so let's say we have this now let's give all of these an index so we'll say 0 1 2 3 4 5 6 7 8 okay so basically what we're going to do is anytime we encounter a new number that means we have to take everything before that and change it into that number and I'm going to kind of show you how that looks like and updating our result so in the beginning we encountered a new number so we're going to say okay whatever the index is of this number we can figure out how many numbers come before this right so the index of the number is going to be the numbers that came before it so we can write that down so index equals numbers that came before it right so for like index zero there are no numbers before it for index one there's one number before it and so on and what basically we're going to say is we're going to say we need to take everything and turn it into this number and because it's sorted we're automatically going to start at add our biggest number and then turn it into the second biggest number and so on and you kind of see how this works so we'll start at this first number we'll say okay well our result is going to add uh so we need to take however numbers that came before this number turn it into this number and we can also initialize our current number so we'll have another variable for like current number call that like Cur or something we'll set it equal to null at first so null and essentially what we're going to say here is we're going to say okay we've reached the new number so we're going to update our curve to be this new number and we're going to take every single number before that and turn it into this number and that's going to cost us n uh or it's going to cost us the number of numbers you came before so in this case it's actually zero so now let's go to the next number and you'll kind of see how this works so now we've reached the new number so we're going to say okay however many numbers came before this they are all the same because we're going to be turning everything into the number we're currently on so everything before the number were currently on is all the same and they're all bigger than this number right because we've reached a new number so we're going to say okay well we have a 12 so we're going to update our Cur to be 12 and we're going to say the number of operations we need to turn everything before this 12 into a 12 is however many numbers came before this so in this case there's only one number that came before this so we'll update our result to one and this is basically saying we're going to turn our 24 into a 12 right so we turn the 24 into a 12 and we can actually write it in here as well just to make it easier to see so essentially that cost us one operation then we go to the next number and we say is it the same or is it different it's the same so we can just keep going we don't need to do any kind of modification here it's the same and here it's different so we're going to say we're guaranteed to have everything before this be some number right because we are changing as we go so how many operations how many numbers are there are four so we're going to update this result to be 1 + 4 and basically what we're saying is 1 + 4 and basically what we're saying is 1 + 4 and basically what we're saying is we're changing everything now into an eight so our new C is eight and we're changing all of these numbers right like I said it doesn't really matter what index you pick first because you have to do all of them anyway so it's basically irrelevant so we're going to say 8 88 and eight as well here so now we have all eights now we go to our new index and kind of the same thing right so how many numbers do we have before this well we have five so we'll add five here and now we change all of these eights into fours so four 4 update our current number to be four go to the next index same thing we've have a new number so we have six numbers we have to change so six change everything into a two so change all this into twos so two now we come over here same thing we have a new number update our number how many numbers do we need to change seven so now we change everything into a one so I'm just going to cross this out and pretend these are all ones now and then when we get to eight is the same so now everything is a one and it cost us this many operations so we have 5 + 5 10 + 13 many operations so we have 5 + 5 10 + 13 many operations so we have 5 + 5 10 + 13 uh 23 so that should be the return so essentially you just sort your numbers and you go through and you know that everything to the left of what you're at is already the same number and every time you reach a new number the number of changes you have to make is just the number of previous numbers before that so it's going be an unlog and solution pretty clean not super hard to figure out but yeah we definitely did eliminate some things like DP and so on so the first thing you want to look for typically is like you know do I need a sore or can I have ideally you want to have a solution where you can go through your array and you can Traverse and you don't need to like cut out numbers right so if you can Traverse in order those are going to be the best Solutions so that's typically and it's the most common one so typically you want to look for like a sliding window if possible and then if not go to DP and then after that look for other stuff so this is kind of it's not a sliding window it's just basically going element by element even easier than sliding window right so now we can code it up and so what we're going to do is we're going to sort our numbers but we're going to sort from biggest to smallest right because we want to convert bigger numbers into smaller ones and every time we reach a smaller one we have to convert everything above that so we're going to say nums do sort in reverse order so you can just in Python do reverse equals true and this will sort inverse order now we want to have a current number we'll make that and we'll have a result equal to zero and we'll just say like uh 4 i v and enumerate nums if cerr is new right so if cerr does not equal V then we update C so C equals V and we need to update our result so every number before this number needs to get changed into this number and how many numbers are there before this number that's just going to be the index so plus equals I and we can just return the result here and hopefully that's it so pretty easy one um I think that should be fine and there we go so we have a pretty efficient solution pretty straightforward I think honestly this I don't know if it's whole month but last few weeks the problems have been like really easy I think the month before this we had like it's crazy they give you like a week of like almost all hard DP problems and now they give you this kind of stuff kind of funny but regardless so um the time complexity here is going to be log n right cuz we have a sort everything else this is O of N and the space is going to be o of one now like I said you can there is a thing that will actually run faster on Le code and basically the idea there is instead of sorting you would store uh key value pairs where the key is the number and the value is the count of the number and then instead of going instead of sorting this you can sort the keys cuz then if you have a bunch of num that are the same uh it will be faster also I think something like a bucket sort would actually be faster for some situations but for most of them it'll be slower but this dictionary one is also worse in space because it has you know takes up space so it'll be the same time complexity it'll just have like a better runtime on leite code which is like whatever um yeah so I think that's going to be all for this one though so hopefully you like this one if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
|
Reduction Operations to Make the Array Elements Equal
|
minimum-degree-of-a-connected-trio-in-a-graph
|
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`.
3. Reduce `nums[i]` to `nextLargest`.
Return _the number of operations to make all elements in_ `nums` _equal_.
**Example 1:**
**Input:** nums = \[5,1,3\]
**Output:** 3
**Explanation:** It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\].
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** 0
**Explanation:** All elements in nums are already equal.
**Example 3:**
**Input:** nums = \[1,1,2,2,3\]
**Output:** 4
**Explanation:** It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\].
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 5 * 104`
|
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
|
Graph
|
Hard
| null |
7 |
hello welcome to Nets @os today in this hello welcome to Nets @os today in this hello welcome to Nets @os today in this video we will discuss about how to reverse indie job earlier I have discussed how to reverse string now we are covering lead code part so today we will cover reverse indie job so let's understand what is the question first it says first of all it's an easy one and here given a 32-bit signed integer here given a 32-bit signed integer here given a 32-bit signed integer reverse digit of a number if we are given input as 1 2 3 the output will be 3 2 1 if it is in - it should return - 3 2 1 if it is in - it should return - 3 2 1 if it is in - it should return - as well and if it has zero at the end 120 then an output it should be 0 to 1 as 0 has no meaning in the beginning so 21 should be there in output the that we have in note assumes we are dealing with an environment which could only store integer within 32-bit signed integer within 32-bit signed integer within 32-bit signed integer range that is from minus 2 to the power 31 to 2 to the power 31 minus 1 so mainly we have to focus on first how to reverse the integer and secondly if the number is smaller than 0 sign should be negative so for this first let us know how to reverse the integer here we have algo in front of a screen what I do I'll take the same number num as 123 and I know the reverse of this integer will be 321 which I will write somewhat in the side of my screen now let see the reverse of numb so for reversing I should have the last most digit as my first so here I need to take out this three out of my num number so what I will do I'll make use of this remainder which will be 123 divided by 10 so when I divide 123 by 10 divide 10 12 120 and 3 in my remainder so with the help of first step I got remainder as 3 now the second step is to shift because firstly I extracted the digit from the num I got this 3 now what I have to do I have to shift to the left because I want this 3 to be my first digit then the rest so what I will do first I'll initialize some as 0 so 0 into 10 plus my remainder which is 3 so right now sum is 0 anything multiplied by 0 will be 0 plus 3 will be 3 so some will be 3 right now and then resuming the last statement num divided by 10 the quotient which I will use for the next step so now I will take this tool and will divide by 10 so 10 ones are 10 and I got 2 as my remainder right now I have in my output as 3 now I want this to be with 3 so what I will do some has 3 into 10 plus vcn tremendous - so three into ten thirty plus two will - so three into ten thirty plus two will - so three into ten thirty plus two will be 32 so I got 32 as my current output now what I will do I take this one out of my question and we'll divide by here we can see 10 will not be able to divide one as it is a very less number so one will be the remainder now this one will be in the remainder and some is 32 into 10 which is 3 20 plus 1 so I got 3 21 as my output as simple as that so here we have completed our first point which is to reverse the integer now I need to see whether that integer is less than 0 if it is less than 0 I will append minus sign to it let's say if I have in my input minus 1 23 so what I will do I'll apply num is less than 0 then sign will be minus 1 and our num will be minus 1 into na so this question was simply two steps based quotient now apart from these two steps it says to have your integer value within 32 sign bit integer otherwise it will return zero when we reversed integer overflows so the third condition we will apply this so here our number should be written this range so let's implement this into Python program so we will go to pycharm and here I have already made a file name with people's underscore integer now what I will do I will start making function d/f reverse signed value where input d/f reverse signed value where input d/f reverse signed value where input parameter will be none and here I will take the result value as sum which I will initialize as zero and a variable sign initialized by one now we will have two situations either are value that is num value will be less than zero or greater than zero so first let's see if num is less than zero sign will be minus one and Arnim will be none into minus one whatever may be the value now let's see if num is greater than 0 it will have the remainder which will be num mod n then we will shift it to the left by sum is equal to sum into ten-plus sum is equal to sum into ten-plus sum is equal to sum into ten-plus remainder and then we will resume our value for the next iteration for next iteration that is here we need to apply by loop because it will be happening for each and every digit of a number so num divided by 10 here with the this sign I will get integer value on D so here we completed our two steps now we will apply if sum is within the range minus 2 to the power 31 to 2 to the power 31 so here what I will do if my value is not minus two one four seven four eight three six four eight two one four seven four eight three six four seven if it is not within this range it will return zero else it will return sign in do are some value now let's call the function for 123 width print statement now let us run the program here for 123 we got 321 now if I apply a minus sign over here let's see I got minus 321 because it will go and have minus 1 appended with it and then it will calculate remainder and with that it will check whether our value is within the range of these values or not so this is how we can calculate reverse integer so please like share and subscribe my channel thank you
|
Reverse Integer
|
reverse-integer
|
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1`
| null |
Math
|
Medium
|
8,190,2238
|
8 |
hello today we'll be working on lead code number eight string the integer a to I stands for ASCII to integer and our function is given a string and we need to extract the first number characters from the string so let's go over the different things that we need to do in order to get the correct answer all right first we need to ignore leading white space if the string begins with a positive or negative sign we'll use that sign to make our number positive or negative next we capture all number characters until we hit the end of the string or we hit a non number character there aren't any number characters after the sign or no numbers in the string in general we return zero next our result has to be within a 32-bit signed integer range so this 32-bit signed integer range so this 32-bit signed integer range so this means our number has to be in the range of negative 2 to the 31st or 2 to the 31st minus 1. so if the number overflows or becomes larger than the range allows we make the value the maximum allowable number if a number underflows or becomes smaller than the range we make it the smallest allowable number and then lastly we return the value so I made a list of different inputs for us to consider the first four inputs will return zero the next six inputs will all return 42 with the strings starting with a negative sign being negative the last four inputs will all be pulled back into the 32-bit range be pulled back into the 32-bit range be pulled back into the 32-bit range they'll be clamped with the negatives being assigned the smallest allowable number and the positives being the largest allowable number all right I quickly want to step through all the steps with the second to last example that I just showed you so we're going to take this string and return this number so first we remove the leading white space and we check if the string now starts with a leading sign in this case it does so we'll need to remember that our number is negative next we capture all the numbers until we hit the end of the string or hit a non-number character in this case we non-number character in this case we non-number character in this case we stopped it the letter A then we convert the captured characters to a number and then add the sign to it and then the last step before returning we check to see if a number is outside of the range this number is smaller so we assign it the smallest sine 32-bit we assign it the smallest sine 32-bit we assign it the smallest sine 32-bit integer value and then we return that value all right so let's go ahead and step into the code and see how we can do this all right we're going to start by trimming the white space at the start of our string with the trim start method then we'll create our Max and Min for our 32-bit range then I'm going to our 32-bit range then I'm going to our 32-bit range then I'm going to create two variables for the character codes of zero and nine we'll use this later to see if a character is a number or not then I get a reference to the first character the string and we have three more variables so result will be our output which is assigned to zero this is for the case if we have no numbers in the string we'll just return zero the sign represents if our number is positive or negative and we start off with positive an index will be the position we start looping at now we check if the string starts with a plus or minus sign but if it's a minus sign we make sine a negative one and either way we move the starting index to one that way we don't include the sign in our Loop and then we're going to now create a for loop I will start at index I'm going to create two variables Char for the character we're on and code for the character code of char so if the code is outside the range is 0 and 9 we know the character isn't a number so we can break out will update the result if result is a zero we'll replace zero with our character let's say we had multiple zeros in a row this makes sure we only have a single zero and it prevents us from having leading zeros so if our result isn't zero we'll append the character to the result okay so once we're out of the loop we can now do plus result which will convert our string into a number and then we multiply this number bar by our sign if our sign was negative the number would become negative else it'll stay positive all right and one of the last things we need to do is check if result is within the 32-bit range if it's above result the 32-bit range if it's above result the 32-bit range if it's above result becomes the max 32-bit int else if it's becomes the max 32-bit int else if it's becomes the max 32-bit int else if it's below the range it'll become the Min 32-bit end and then we return the result 32-bit end and then we return the result 32-bit end and then we return the result all right so let's submit this cool what's accepted so I also have another way I want to show you real quick so there is a built-in JavaScript so there is a built-in JavaScript so there is a built-in JavaScript function called parse int which does basically this hold function the only difference is if the string has no numbers at the start we'll get back Nan so we just need to check for that and yeah there's another possible solution all right and that's Elite code number eight you can check out my GitHub repository in the description for the solution and tests if you have any suggestions please leave a comment below and I'll catch you in the next video
|
String to Integer (atoi)
|
string-to-integer-atoi
|
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function).
The algorithm for `myAtoi(string s)` is as follows:
1. Read in and ignore any leading whitespace.
2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Convert these digits into an integer (i.e. `"123 " -> 123`, `"0032 " -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2).
5. If the integer is out of the 32-bit signed integer range `[-231, 231 - 1]`, then clamp the integer so that it remains in the range. Specifically, integers less than `-231` should be clamped to `-231`, and integers greater than `231 - 1` should be clamped to `231 - 1`.
6. Return the integer as the final result.
**Note:**
* Only the space character `' '` is considered a whitespace character.
* **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits.
**Example 1:**
**Input:** s = "42 "
**Output:** 42
**Explanation:** The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42 " (no characters read because there is no leading whitespace)
^
Step 2: "42 " (no characters read because there is neither a '-' nor '+')
^
Step 3: "42 " ( "42 " is read in)
^
The parsed integer is 42.
Since 42 is in the range \[-231, 231 - 1\], the final result is 42.
**Example 2:**
**Input:** s = " -42 "
**Output:** -42
**Explanation:**
Step 1: " \-42 " (leading whitespace is read and ignored)
^
Step 2: " \-42 " ('-' is read, so the result should be negative)
^
Step 3: " -42 " ( "42 " is read in)
^
The parsed integer is -42.
Since -42 is in the range \[-231, 231 - 1\], the final result is -42.
**Example 3:**
**Input:** s = "4193 with words "
**Output:** 4193
**Explanation:**
Step 1: "4193 with words " (no characters read because there is no leading whitespace)
^
Step 2: "4193 with words " (no characters read because there is neither a '-' nor '+')
^
Step 3: "4193 with words " ( "4193 " is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range \[-231, 231 - 1\], the final result is 4193.
**Constraints:**
* `0 <= s.length <= 200`
* `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
| null |
String
|
Medium
|
7,65,2168
|
1,025 |
welcome ladies and gentlemen boys and girls today we're going to solve another coolest question which is divisive game okay so this question is cool man so it deserved like for me because this person is very interesting this person doesn't likes from myself okay so let's see what the question is think so the question thing like alice and both take run takes done playing a game with alice starting first okay so it means like they think like we have two persons alice and pope okay and alice always starts first so or alice always starts first so this is the right now condition that will be the same okay initially there is a number and on the choke board on each turn the player makes a move consistent okay so it means like what was saying over here like each player can take only one term at a time let's say if aliens start initially then the next turn is of both then after um both then the next name of alice is like that okay so that's the question anything now okay now they give some rules for the game the rules is like choosing an x 0 to x is n okay so this is one condition i will tell you about it later on okay then the another condition is like whatever the number you choose it's more or less it will has to become zero okay only that number you have to choose all right and replacing the number for the another place and minuses like for the this is one condition and for the another condition you have to reduce the number by n minus x okay so let's say i will tell you just one more time okay like i just will give you one minute after i will tell you what the portion is actually okay also if a player cannot make a move then he loses let's say the player is unable to make a move then he will definitely lose again let's say if he didn't does not have any move left okay so that's the question return true if and only if alice wins again okay this is racist this is basically if the online if listening then we have to win two y five fourths for both also these are true anyways so for the ball we have to written fourth okay so let's see how we saw this question okay so according to this condition was questioning let's say we have n equals to 2 so remember this condition which i just show you n is 2 so it means 0 it will start it has to be zero above from zero okay and between two so greater than zero and less than two okay it has to be over here okay and it more or less has to become zero okay let's say we are starting with alice we have n equals to 2 initially over here we are starting with alice so what will happen how many moves i have i just have only one move okay so what will happen obvious just simply check and modulus against 0 so i will check is 2 modulus 1 is 0 yes it is zero so what will happen i have to reduce n minus x so n is two minus x is one because actually we just we choose one because only one move two minus one is given one so for the bomb whether condition is left zero x one okay now how many like what movie he can use he cannot take any move because he does not left anymore the number has to be greater from greater than zero and less than one what left we can't take decimal values so there's no move so alice wins and we have to written two so we are hitting true for the true alice when okay i hope so the question is clearly like what the question is saying i hope sorry the german is clear it's still not don't worry i'm over here okay so let's just try for the another condition let's just go for another condition let's say we are working for n equals 2 3 over here okay let's check this one right so what will happen like i'm checking anyone so first chance look bob uh alice i mean sorry alice will go first chance so it will go from zero x three okay so what will happen over here so uh it has two move one comma two but it has to only take that move which more or less give us 0 so it is not able to take 2 it will only be able to take one okay so when alice takes one so what will happen how uh for the both what will happen n minus x so 0 x it will become two because three minus one because we take one so three minus one give us two okay so i have to do this thing is clear now we are working for both okay so for both how many moves it has only one move okay because like two is the maximum okay so what will happen it will take is one move okay so for alice how many moves left zero x one okay so how many move that four l is no move left so both win in this game so alice lose the game so what i can say alice lose the game i just lose the game okay so i have to written force for that i didn't false for that like if the balls win or if the alice flew is the same thing then we have to written force for them but we didn't force them i hope so the question is now making some sense if still not don't worry we will try one more time okay so let's say we are checking for n equals to four right so we are going for four so alice will start in the initial initially the alice will start okay so what will happen so initially ls will go from zero x four so it can take a one two o three okay so it can take either one two or three okay so threes cannot be taken because like uh two more plus four is zero one minus four is zero okay so it can only take this one out okay so let's say like i will go for one in this one okay so what will happen it will become zero x 3 okay so let me make it more familiar all right guys so i hope i have now explained it okay so now what i'm doing is it's going 0 x 3 okay so for 0x3 uh now this is our alistair now this is our boat so you know bob has how many times one two so it can only take one so what will happen alice will get zero x two okay so alice has only one so bob how many left zero x one so go lose because bob can not move any more chance so alice win so alice will come true for uh four it will come true okay so what the condition we are checking like we just get one condition over here we just find one uh you know a hint over here like what we find like if we are getting an even if our n is even and we take odd move or number move okay so what happened we what happened alice always been alice always win ladies and gentlemen focus on this thing but i just write over here just focus on this thing make sure what i'm writing this i'm telling it again one more time just focus on what i'm saying if n is even okay and we take odd number move we take odd number we get one over here t reject one over here okay we take odd number move alice always will why because you see like whenever i take one alice's value now i will go for the even one i will go for the blue one you will see the result you definitely see the result okay let me erase it so now you will understand complete question if you still don't understand this one then i will suggest you to watch this video again okay all right so now uh we alice will go so it i will uh say to god for the even one so 0x4 okay so it will go for the even one all right so what will happen what have one two three so it will go for the two one it will look for this one but it can go for this one but we will take before this one which cannot be possible okay so what will happen i will just say n minus two so both will go for n minus two so n minus two is four minus two will give us two so bo will go for two okay so bo will go for zero x two all right guys okay so how many moves can do only one okay so both can do only one loop so uh let's move how many left no move left zero x one so alice lose at least lose over here right so now definitely it's making sense what i'm doing at least lose and i will return force over here so i hope now this condition is very clear like what i'm saying any if n is even and we take odd number move alice always mean so what i'm saying like whenever you find even number you have to take one uh he has to take one so that he can miss okay so i have no questions now let's just start solving this question so this question there is nothing to solve this question believe me we just use a simple bit manipulation over here to solve this question so let me just again make it bigger okay and here we go all right so let me install it okay so what i will do i will just simply say if my n modulus 2 give me zero then return true for this okay else return false for the example otherwise uh he will lose and both will win okay that's the condition so let me just run this for to see there's no that's not good guys so it's accepting okay so uh i can make it more bit clear more with like sexy okay so how are you gonna do this let me just create everything from over here okay so i just simply write one line of condition i will just say return i have so you some of them you have figure out like what i will do and fold us 2 is 0 then written in this condition true or get false so i'll do this things clear so that's the core is that the code is guys let me just run it and we did it ladies and gentlemen we just did yeah our code okay so this is in summaries and let's see whether it's accepting or not okay and it's going hundred percent faster so here in general in this question we are dealing with the time complexity of we go off and because like we're just going and we're just calculating n number of times okay and the space complexity is below one because we are not using any extra space so ladies gentlemen i hope this code is kister creative like how we are solving this question and i just want to say ladies and gentlemen thank you guys for watching this video i will see you in the next one till then take care bye and i love you guys believe me i love you take care bye
|
Divisor Game
|
minimum-cost-for-tickets
|
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
322
|
234 |
all right let's talk about the parent drum nicholas so you're giving the head of the single linguist so return true if it's a parent drum so this is an example and then there are a couple ways to solve these questions and the easy way is using the recursion so you just find out the last note in the linked list then you have uh you have a pointer here and then you will just keep comparing each other and since this is a recursion pointer you will this will get recursively back so you are recursive back to this pointer and then you will just have to move on the next clicker to compare so this will be the solution and this is supposed to be the easy one and the next one is going to be preferences so this is the second solution so you can actually create a stack and then i have a fast and slow pointer so fast moving twice not at a time so slow pointer moving one uh one this note at a time so you will actually uh find out where did you start on your uh on your right side of the uh paragraph linguist right then you can actually i mean when you traversing when you're slow you have to push into the stack and then when you know this is the right side of your pointer and then you can actually uh pop your popular additional value from it from the stack and then to compare the current list node and if they are the same then you will pop and then you move on and this has a uh this has a trick this is because so the trick is because if a listener is actually what okay if a linked list is actually odd like uh this one is all length right this is even length right so how do you know uh this is all this is even right so when we traverse uh the linked list based on the slow and fast we can actually determine is this linked list of our length or even length just based on this right so fast point to move twice at a time slow point the move one at a time and then when you want to move your fast again you need to check the condition if a fast is not known and also if the facts are next is not known right you need to check these two conditions if they are satisfied then you can move on right if they are not satisfied this is going to be all thing right so the slow point has to move uh one again this is because the left uh the right side of the linked list doesn't start at this point so it started at least linked list yeah listen i'll be honest so you will still start from the beginning and start it from the beginning and compare it with this value based on the stack and this is uh pretty much the solution so uh let's talk about the recursion first so i'm going to say recursion so i need to create at least no i'm going to call l right so l i represent the head so i will point and this note i'm going for r this is this will be my uh right pointer for my blue uh result of the language right so transverse and i need to say a hat i need passing the head no matter what right so if r is actually good to know right if you hit the end you will ensure all right so i need a variable to actually store the current value for the right pointer so i'm going to call result and then this will be traverse my uh i don't know so this will just traversing the entire list now to the end and then recursively back right so uh this will be pretty much nothing but you would just know where is the pointer at and then i'll just have to keep updating my results with the current right value and then the value since they are recursively background so other value is equal to l value if they are equal uh the reason why i'm using n this is because i need to keep track of the previous record and this would be pretty much like uh no is this the linked list is the parent draw now right so if they understand i need to move on my mobile my left pointer dot next y because a right pointer will recursive back right so they are going to be the same so it will be l dot next and then at the end i will just have to return the result right and this will be the solution all right let's submit all right here we go so basically layout super super straightforward the time is going to be all of them and the space is constant right you are not allowing any space and let's talk about another solution so the motorcycle is stacked so i need a stack right so what i need to put is putting the door you can put this now doesn't matter but they are the same i'm going to kind of post that so i need a fast and small pointer so plastic to the head slow equal to 10 so well fast is now and also fast on x is now so slow equal to next pass you could do faster next time next you need to move twice at a time right so if fast is not low this will actually determine the length is all right so i need to move my slope i want all right now i need to just keep comparing right so comparing my uh slow pointer with the stack right so i know where i start from my right side will put linked list so files slowly sign on flow equal to slow down x but before i move i need to check if slow down is actually not it's actually equal to the stack of pop right if they are not april i will have to return post and i just realized i didn't add a value into my stack i made a mistake last time so it's actually stacked by ad right so it's going to be slow down right and at the end if the value is actually success and you actually have to return true because you will return false if they are not the same so this is the solution and let me submit all right so let's talk about time in space for this one the space is all the fun the time is actually all the time as well like you have to traverse every single link list right at least not in a linked list right so this is all open the space is all the thing is because you have to basically store half of the list now into the stack so one over two is approximately all of them so this is pretty much it and i will see you next time bye
|
Palindrome Linked List
|
palindrome-linked-list
|
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_.
**Example 1:**
**Input:** head = \[1,2,2,1\]
**Output:** true
**Example 2:**
**Input:** head = \[1,2\]
**Output:** false
**Constraints:**
* The number of nodes in the list is in the range `[1, 105]`.
* `0 <= Node.val <= 9`
**Follow up:** Could you do it in `O(n)` time and `O(1)` space?
| null |
Linked List,Two Pointers,Stack,Recursion
|
Easy
|
9,125,206,2236
|
1,422 |
hello friends so today we can discuss this question from weekly contest 186 problem number one for two to maximum school after splitting a string you are given a string s of zeros and ones return the maximum score after splitting the string into two non-empty sub the string into two non-empty sub the string into two non-empty sub strings left and right the score of the splitting of string is the number of zeros in the left sub string plus the number of ones in the right sub thing okay so let me take this example so this is a string and you have to find out how many zeros are on the left side and how many is in the right side how many puns are there okay and it is also given that these are non empty it means there should be at least one element there one and B sub spec so you cannot cut the string at this part this is zero and just all the parts in here okay so we can cut it here we can cut it in here you can cut it here okay so if we move our find from here from I equal to one we can do two loops from I minus one to the end and some I till the end because they are cutting from here so we have to position I minus 1 and from I so we have to do a loose from I equal to 1 to I equal less than n because when we came at this point we have two sections okay so when we when I came at this point we have two sub strings one start at I minus one and other started ions so that's a simple logic and because the constraints are very small we can just brutally count how many bonds are there on the left side the zeros on the left side and one on the right okay so let's try to cool n is equal to s dot size and we have this towards the maximum whether it's any size equal zero and as I've told you we have to do from I equal to 1 to less than equal to n I plus so we want to count the number of zeros next I pick with zero put to count one we stack it with zero able to follow J equal to I minus 1 it is greater than equal to 0 t minus and if X of I is equal to 0 because now we are iterating on the left side if it's 0 then 0 that's okay now we are did it for the right side into a is equal to I then and a plus if s of I is equal to 1 plus but ok so now we have to find out the maximum which is if 1 plus 0 is greater than Maxie then actually is equal to 1 plus and after that you click on that it's not so it's giving the wrong answer that understand what we have done wrong okay this is cause the drilling aubergine on I find a section I hope you understand it's very simple question thank you watching this video and put the rest of the problem solutions data so keep tuned and thank you for seeing this video actually an expert
|
Maximum Score After Splitting a String
|
divide-array-in-sets-of-k-consecutive-numbers
|
Given a string `s` of zeros and ones, _return the maximum score after splitting the string into two **non-empty** substrings_ (i.e. **left** substring and **right** substring).
The score after splitting a string is the number of **zeros** in the **left** substring plus the number of **ones** in the **right** substring.
**Example 1:**
**Input:** s = "011101 "
**Output:** 5
**Explanation:**
All possible ways of splitting s into two non-empty substrings are:
left = "0 " and right = "11101 ", score = 1 + 4 = 5
left = "01 " and right = "1101 ", score = 1 + 3 = 4
left = "011 " and right = "101 ", score = 1 + 2 = 3
left = "0111 " and right = "01 ", score = 1 + 1 = 2
left = "01110 " and right = "1 ", score = 2 + 1 = 3
**Example 2:**
**Input:** s = "00111 "
**Output:** 5
**Explanation:** When left = "00 " and right = "111 ", we get the maximum score = 2 + 3 = 5
**Example 3:**
**Input:** s = "1111 "
**Output:** 3
**Constraints:**
* `2 <= s.length <= 500`
* The string `s` consists of characters `'0'` and `'1'` only.
|
If the smallest number in the possible-to-split array is V, then numbers V+1, V+2, ... V+k-1 must contain there as well. You can iteratively find k sets and remove them from array until it becomes empty. Failure to do so would mean that array is unsplittable.
|
Array,Hash Table,Greedy,Sorting
|
Medium
|
659,2261
|
1,091 |
what is going on everybody it's your boy average leader here with another video and today we're tackling number 1091 shortest path in binary matrix this question is commonly asked by amazon google facebook oracle snapchat and this question was also requested to me by one of my most active subscribers santosh i see you subscribed i see you comment i see you like my videos so thank you so much for your like interactions on the channel it helps my channel out a ton by giving it more exposure to people that don't know me and i very much appreciate you my friend and with that being said if you guys want to see another problem done just comment down below and i'll make sure to do that problem for you and i'll even shout you out okay so with that all out of the way here we go and quickly right before we start this problem i want you guys to go and watch my minimum night moves video uh you're gonna see a lot of similarities in the problem structure as well as how we are going to create the solution for this problem so go give that a quick watch it at two times speed whatever you got to do just so you see how similar these two problems are but all right given an end by an binary matrix grid return the length of the shortest clear path in the matrix okay so immediately this line is telling me that a few potential solutions that we can use to solve this problem are either some type of dynamic programming maybe or a breath first search now i'm not a hundred percent sure just yet but uh shortest path i mean shortest path has been seen many times you and uh usually we can use one of those two strategies to solve the shortest path type problem but i'm not sure yet let's keep reading and we'll see what we're going to use if there is no clear path return negative one okay a clear path in a binary matrix is a path from the top left cell so zero to the bottom right cell n minus one okay such that all the visited cells of the path are zero and all the adjacent cells of the path are eight directionally connected okay so this here was the clear indicator for me what this is saying is we have a starting position at the top left cell zero and we have an ending position which is the bottom right cell uh n minus one now when we are given a problem where we have a starting position an ending position and we are told to find the shortest path of the problem i am automatically thinking we need to use a breath first search for this problem those are some big hints given to us so we can use bfs to solve this problem um so finally the length of a clear path is the number of visited cells of this path okay so let's look at this example number two on the ipad and see how maybe we can use a breadth-first how maybe we can use a breadth-first how maybe we can use a breadth-first search all right so i wrote down example two straight off of the code and right now what we're trying to do is see if we can do a bfs on this grid to see if we can get the shortest path from the top left of the grid all the way to the bottom right of the grip so in true bfs fashion what we would usually have is a queue in our implementation which would hold all the nodes or all the spaces of the grid that we'd like to explore and look at all the neighbors of and we'd also have like a counter or like a something that's holding on to our length at all times of our bfs so the first thing that we're going to do in our bfs is we're going to add our starting position to our queue so what is our starting position we're going to have this top left part of our grid in our key but how can we actually store this information into our cube we need an object type which can represent each of these spaces of our grid an easy thing for me that helps me visualize where we are in our grid is to treat each of these uh cells in our grid as coordinates so i'm going to quickly label all of the coordinates of this grid our first number in each of these tuples is going to represent the row of each of our cells and our second number is going to represent the column of each of our cells so what we're going to initially store in our queue is the coordinate 0 and also for our count variable remember this count is going to hold the total length of our path that we're going to return at the end and um since in the problem it says that the length of a clear path is the number of visited cells of this path and since we have already started at the coordinate zero we automatically have a length of one for our path so i'm going to store one as our counts frame and from here we're going to pop off uh this node from our cube and when we pop off an element from the queue we're going to explore all of the neighbors of that elements or all of the adjacent cells from that cell so in other words we're going to look at the right the top left the bottom and the bottom right now immediately we see that all of these directions right here from the top right all the way to the bottom right they are outside of the matrix's range so we're not even gonna look at that and looking at the bottom direction uh we see that's going to a one so we're not going to look at that and looking at the bottom right that's also going to a one so we're not even going to address that but the direction going in the right is going to a zero so if we are given an adjacent cell with a zero we're going to add that coordinate to our q so i'm going to add coordinate 0 1 into our q um and let's uh let's clean this up just a little bit okay so after we're done going through all of the directions of this of our cell we are basically done with that iteration of the breadth first search and hence we've added all the nodes that we want to explore uh to our path and after we're done exploring all of these cells that are neighbors of our current node we basically added another element to our path in our queue and every time we're adding an element to our path we're incrementing the length by one so once we're done adding all the potential neighbors to our q we're gonna increment our count by one so now the count is going to be two our length currently has uh two notes and that note is this one right here and this one right here okay so now that we have that out of the way we're gonna go to the next iteration of our bfs so next we're going to pop off the coordinate zero one from our queue and uh since zero one is right here we're gonna search for all of the neighbors all of the adjacent neighbors from zero one so instead of getting all messy one more time i'm just going to go ahead and add the neighbors that we can add to our queue so we see that we can add the right direction we can add 0 2 to our q so i'm going to add coordinate 0 2 and the we can also add negative 1 two to our q so negative one two and notice that we also have uh zero that we could potentially add to our q but now we don't wanna do this we don't wanna add nodes that we've seen already into our queue because it just doesn't make sense to go to this note again because once we go to zero then we're gonna add zero one again and then zero one so this is like an infinite loop in our queue and to combat that what we can do is utilize another data structure and i'm thinking we can use like a visited set so a visited set that's just going to be like another hash set so let's create a hash set also and i'm going to shift this down i also see that our q is about to be full so i'm just going to make this like a bigger cue here so we're gonna have a visit set and it's gonna be a hash set and in our hash set every time we add an element to our queue we're gonna store it in our hash set as well so far we've seen coordinate zero one and we just added zero two and negative one two to our uh q so i'm gonna add zero two negative one two and this way uh this way we just asked ourselves one last question before we add a cell to our queue have we seen that coordinate in our visited set already since we've seen zero in our visited set there's no need to add it again to our queue so that's where we're also going to keep in mind uh while we're going through our paths so now after we're done going through all of the neighbors in this current iteration what we're going to do is we're going to increment our count by one since we're basically increasing our length by one in our path so now we're going to pop off zero two from our q and at zero two we see that we can only go down to uh negative one two and zero one but we've seen these uh coordinates in our set so we have zero one here negative one two here so we're not going to add this add any of those to our q uh anymore and um finally in our q in this iteration of our q we also have negative 1 2. so let's pop off negative 1 2 and at negative 1 2 we don't want to add the top left since we've seen those already but we can add negative 2 too so let's add that into our cube and we'll also add it to our visited set and uh after we're done exploring through all the nodes in that iteration we're going to increment our count by one so now the final step that we'll do is every time we pop in elements from our queue let's just do like a quick check to see if that x and y coordinate matches the n minus 1 uh coordinate in our grid so in this case our grid has a length of 2 and you'll see when we code it out we actually account for this for now we can just like pretend to take like the absolute value of this and we notice that the x and the y coordinates are the same so after we have reached our target coordinates all we can do is return our count that we've been keeping track of so far so we see that we get 4 here and that is actually the solution to that problem if we can't find a proper path uh in our grid like let's say we're given uh this grid right here we see that if we try to do a bfs on zero on coordinate zero we'll get this node that cell and if we do a bfs on zero one we get that cell uh but after we're done here we can't add any node after that because uh you know those cells don't have a value of zero and uh basically we just end up with like an empty queue so after a queue is empty if we still haven't found a path where our last node in our queue has the same x y coordinates as the length of our matrix like two in this case um then we're going to have to return negative one so if we can't find a path we're going to return uh negative one and the last thing that i think we need to keep in mind is we start off by adding these zero coordinates to our cube but let's just say at the zero coordinate we have a uh a cell with a value of one and also at the uh final bottom right cell we have a value of one if either of these two situations happen we should also just return negative one there's no need to uh start any type of bfs if we can't if we don't have a proper starting or ending value so with all these things considered uh we see that a bfs is possible let's go ahead and dive into this code all right who is ready for some code i know i am so first things first you guys know what i like to do i like to start with uh asking a question what are we trying to return well we are trying to return the shortest path and that's going to be an int and i usually just like having it called like count or something but uh in this case i'll just call it length uh length equals and remember since we are like automatically start by adding the very first elements uh the very first cell 0 into our q i'm going to start with a length of 1. and at the end we can just return this length now if you guys feel more comfortable uh you know making the starting length at zero and then returning a length of length plus one go for it that's all you but i think for me it's just easier seen as starting at a length of one and from here let's also initialize the data structures that we're going to use so we're going to use a q and what is our q going to hold we decided earlier that we want our q to hold some coordinates so i'm going to make a coordinate class in just a second so it's going to be coordinates q equals new linked list and this will be our q for the whole problem and next before we forget let's make our coordinate class so i'm going to make this a class coordinates and in this coordinate class oops spelled that wrong in this coordinate class we're going to have two instance variables we're going to have the x and y which is going to represent like our row and column that we're going to uh have and i think you know maybe it might be better to see it as row call and we're going to have like a constructor that is basically going to take in uh our row and call and it's going to initialize our instance variable row and call to the row and call that we're going to pass in so what i'm going to do is say this dot row equals row and this dot call equals call so we have a proper coordinate class here and uh since this queue is going to hold coordinates this should work properly and we're also going to keep a visited set ready to go so i'm gonna make a hash set and this hash set there's one of two things we can do uh we can either store coordinates in this hash set but if we store coordinates we need to define an equals method within our coordinate class or we can do something that's a little bit easier and we can just have it hold strings and every time we pop a coordinate off from our queue and add it to our hash set we're just going to add like some quotes to that coordinates and make it a string so this string hash that we'll call scene equals new hash set and i believe we're done uh creating all of our data structures that we're going to use for this problem so uh now all we have to do is add the very first cell to our cube so how i'll do that is q that add new coordinate zero and i'll also add uh the string zero to our hash set c dot add zero and i'm gonna have a comma that'll separate the row and column that we're at that particular moment so all right so now that we have all these things ready to go we can just start uh writing out the code for a normal bfs we're just going to go through a normal bfs implementation so while the queue isn't empty uh we're going to grab the size of our queue at that particular moment and all we're going to do is iterate through all the cells that are in this size so for into j equal and j equals zero j is less than size j plus uh the first thing we're going to do is pop off uh the first thing that's in our queue so we have a coordinates uh p equals q dot poll and from here i want to grab the uh particular row and column that we're at that particular cell so what i'll do is i'm just going to make a new variable into px equals p dot rho and into py equals p dot call and after we have these two things all we have to do is iterate through all of the potential directions that we can go to now how are we going to simulate going to uh the right the top left and so on and so forth how are we going to simulate actually going through directions well we can hold the directions using some extra storage at the top of our uh method here and i would just call it intex dirt and this will hold like all our directions in the x direction and inch wider is going to hold all the directions in the y direction oh and i also forgot that since these are arrays i need to add these little square brackets here and i think the biggest thing to remember is every time we create storage that's going to hold directions at each index at both of these entries uh that index is going to represent the xy pair for the direction that we want to go to so for example let's say i want to go in the bottom left direction so i'm going to have minus 1 minus one so this pair at the zeroth index is going to go in the bottom left direction and then let's say i want to go uh down in the bottom direction so i'm going to have 0 and a minus 1 here and then let's say i want to go to the bottom right i'm going gonna go one and minus one so each of these indexes is going to represent the pair of our x y direction that we're going to go into so let's just populate the rest of the directions so we have so these are all the directions that we're going to go through and now all we have to do is iterate through uh our direction so i'll say 4 into i equals 0 i is less than extra that length and since they're both extra and wider the same length it doesn't really matter which one we iterate through and we are going to add each of these direction pairs to our current coordinates so uh i'll do n's new x equals p x plus x stir at the index of i and i'm gonna do the same thing for uh the y direction so wider p y mu y so now this is going to represent the neighbor a potential neighbor that we can go to now remember we can't go through all the neighbors we the neighbor has to be uh within the bounds of our matrix uh the neighbor also has to be a zero and the neighbor can't be in our visited set that we've seen already so to make sure that we're following all those things we're going to have a really big conditional that's going to take care of all those things so if new x is less than the grid that length so here we're checking to see if we're in the bound if we're not going over in this direction of our uh matrix length and mu x is greater than or equal to zero that way we're not going under our matrix length and we do the same thing for the y's and mu y is uh less than three dot length and uh new y is greater than or equal to zero all right so these are all our balance checks okay we're making sure that our coordinates and stuff are within our matrix and our grid at the index of our new x and new y equals zero so this is us checking to make sure that we're not going to iterate through any of any ones and finally and our hash set hasn't seen uh that coordinate pair well first before we do that before we check that let's make a new string s equals mu x plus comma plus nu y so and our scene hasn't uh seen or hasn't contains rs so only after all of these conditions are checked only then are we going to add that new coordinate to our q and also to our uh hash set so q dot add new coordinates dragon spell coordinate new x new y and also we're going to add this to our uh visited set but we're not going to have the coordinate we're going to add the string that we created out here so s so after we do all this basically will do our you know bfs for us uh here we're iterating through each of the uh cells that are within our queue and here we're just at going through all the directions that we want to explore and we're adding all the possible ones uh to our actual cue so uh remember the whole point of this is to return the shortest path in our binary matrix so when are we going to increment our path when we're done iterating through all of our nodes and appending all the potential nodes to our q that's when we want to increment our length so after all this we're gonna do length plus and this is like very similar this uh style is very similar to like a level order iteration in a bfs this is like a very standard kind of thing where uh at the very end of our inner for loops we'll have like a incrementer at the very end which will represent like the level that we're currently at but this is kind of the same thing here um and now when are we going to want to return our length well we said earlier that if we once we pop off a point from our uh q if that p x and p y uh is the same coordinate or like is the same position of our uh bottom right of our matrix then we're going to want to return the length so all we have to do is check here if px equals grid that length minus one and py equals grid that length minus one then we're going to return uh the length and that is all we're gonna have to do uh for this problem so let's just check to see if i made any mistakes i'm gonna run this code all right no mistakes here now the last thing that we're gonna want to check we're checking uh for every case that we could potentially fail right so far this is only gonna work if our bottom if our top left is zero and our bottom right is zero but remember what if we have a one at the top left and what if we have a one at the bottom right then we're never going to get a good path right so before we do any of this let's do a quick check to see if our uh top left and our bottom right are zeros and if they're not we're just gonna return negative one so if grid zero equals one or grid uh grid dot length minus one grid that length minus one equals one then uh if that's the case we're just going to return negative one nice and easy so i'm gonna rerun make sure that i'm not spell anything wrong okay and let's submit this they ask you how you are you just have to say that you're fine when you're not really okay so let's see i made an error somewhere oh you hate to see this guys you hate to see it oh okay all right guys listen i am extremely sorry for this i don't even know why i did this but remember if there's not a proper path that we can get from the top left all the way to the bottom right at the very end we are going to return negative one i don't know why i decided to return length here because only if uh if our px and our py equal that bottom right uh corner if the coordinate of the coordinates of that bottom right only then we're gonna return length if this never triggers we're gonna return negative one so let's run this on that example that we missed all right that works my bad guys let's submit this all right a whopping 109 milliseconds we're faster than five percent of the java online submissions woo that's looking real nice right oh no we don't like that oh dang it okay i thought i can get away with this but no at least we're faster than five you know we could have been faster than only like three percent but hey uh okay so this is a good start okay now i always preach like the reason i think we should do a ton of problems is so we get exposure to as many types of problems as we can and i decided to base this video and the answer to this into this question based off of my minimum nights minimum night moves uh video and that in that question that one really helped uh prime me for this video so if you notice most of this code is actually very similar to that video over there but now i'm trying to think how can i make this faster how can i be better i don't want to be faster than only five percent i want to be faster than more than five at least give me like at least ten so how can we make this a little faster um now the first thing that i'll think of is there any particular data structure that we don't necessarily need if we can represent a data structure using another uh primitive type or like a primitive storage type then we can improve our time complexity like much more much faster and make it that much more efficient and um the reason i use the hash set was because i was thinking in that minimum night's uh moves video we needed a hashtag to contain all the coordinates that we've seen already but in that problem we had a board that was infinite it we didn't know the size of that board but in this case we know the size of the board we have like a grid of a certain length um and if we have a grid with a certain length uh is there any way that we can represent that board and specifically represent all the nodes that we've seen so far all the cells that we've seen so far oh we can actually create another fake like a dummy board that will represent all the nodes that we've seen so far so all i have to do is make another board and in this case i need to do an inter board or a boolean board but i think for uh it's easy for us to see that if we have like a boolean double array every time we add a note to our q we'll just make that coordinate in our board a true value instead of false and that way we'll just check to see if our uh board if our boolean board which i'll also i'll just call like visited if our visited boolean board uh equals true that means we've seen that note already we've seen that cell already so we don't want to visit that node one more time so by replacing the hash set to a uh an int array a double entry we are saving so much more time so all i'm going to do is if uh visiting equals new boolean and uh the dimension of this visited grid of this visited uh double array is going to be the same as our grid dimension so newborngrid.length newborngrid.length newborngrid.length uh grid.link uh grid.link uh grid.link so since this is going to replace our hash set i'm just going to comment out this hash set and i'm going to change every line every time we're adding something to our hashtag i'm going to change that line to uh the visited double array equivalent so here we're adding zero that's equivalent to saying at visited row zero column zero uh we're gonna set that equal to true and here we're adding uh s so uh this is just the equivalence of us making that new x new y in our visited uh visited double array we're just going to make that true at that quark it's a visited uh ux mu y equals true and also we don't need the scenes that contains us all we have to do is if the visited uh at new x new y isn't true uh then we're gonna want to you know actually go into this conditional and add the coordinate and also have our visited cell at that spot equal to true so if i run this let's see if i okay i didn't make any mistakes i'm going to submit this and boom immediately our run time goes from 109 milliseconds to 72 milliseconds and now we're faster than 7.83 of java and now we're faster than 7.83 of java and now we're faster than 7.83 of java submission so still not where we want to be but it's an improvement if an interviewer asks you hey is this the most efficient thing you can do is there anything you can change this is a quick change that you can make now finally what did we do to increase our efficiency here we changed an object type a container holding object types into something that holds primitive types we changed a hashtag holding the string object to a visited set a visited uh boolean array which only holds boolean and that increases our efficiency where else are we making an object well it looks like this coordinate is an object and this would be the last thing that we'd have to change here now once again for me it was easy to see uh this problem as like a coordinate type problem but is there a way where we can use uh like quote-unquote coordinates without quote-unquote coordinates without quote-unquote coordinates without actually making an object class well maybe we could represent a coordinate using an inter array and in our inter array we'd have the x and the y coordinates within our inter array so the zeroth index would always be the uh x coordinate and the first index would always be the y coordinate so if we were to change all our coordinates here to inter rays all right i just have to change all of them to it's like primitive type equivalent so now here we adding uh we're adding new coordinate zero that would just be equals new int uh zero comma zero we would do the same right here we're not popping off a coordinate we're actually popping off an int array and then our px we're not accessing the row instance variable of each of our uh coordinates that we're pulling we're actually going to access the zeroth index for our x's and our first index for our y's i believe that is all the changes that we have to make for this to work so let's run this code fine you're not really fine but you just can't oh i guess i missed something oh we're not actually doing new coordinate new x new y anymore we're going to do new int and in that uh array we're going to hold a new x new y coordinate and let's run this and look at that works so let's submit this what the ah and finally the last thing sorry guys i know this is a little bit of a longer video but the last thing we need to do is we keep making a new string every single time but now we don't need this new string anymore so i'm going to comment that out and this should be the last step that we need to do in order to increase our efficiency and look at that we went from a whopping 74 milliseconds all the way to 13 milliseconds and you know drastically improving uh the time complexity here um you know the reason i did this problem was to show us that like even though we did an approach uh to a similar problem in the past it doesn't necessarily mean that approach is going to be the same exact thing we need to do for all types of problems and the reason we did this coordinate class and uh we had like a hash set in that previous uh minimum night moves problem is because we were told that the minimum that the board was infinite it was an infinite board but now there was actually one key detail in that problem that i actually missed and it told us that the constraints of our x y coordinate that we're actually passing in those cannot exceed 300. so what does that mean that means at the worst case scenario we're gonna pass in and look for the x coordinate at 300 and the y coordinate 300 so that means our board has a max like length and width of like uh 0 plus 300 0 minus 300 in the x direction and then also the same in the y direction so if we actually uh redid that problem the same way we did here and we changed our uh our hash set there to like a boolean visited uh double array uh and we changed what we store in our queue has like a bunch of like ins arrays we see that even that time complexity changes drastically for us um and it actually becomes much more efficient and you know this is something that i'm going to keep in mind for all future great problems that i'll even do i'm most i'm changing my approach so that we get the most efficient dilution every single time so with that being said let's just finish off this problem by discussing the time and space complexity the time complexity well let's see what are we doing here well i guess the bulk of our complexity happens within this while loop so we're iterating through all of the nodes within our queue here and we're only looking at each of the node at uh at most one time since we have this like visited double array that's in charge of like telling us what nodes we've seen in the past so at the worst case scenario since we go through we can go through all of the elements in our grid our time complexity would be o of n and our space complexity well we have our q which at the worst case could hold n nodes uh in our graph and that means our in our grid and that means our space complexity is also uh o event so that is how you do this problem guys uh hopefully that made some sense i know this was a longer problem but i hope my points uh got across that like even though we know how to do uh a type of problem in the past we can utilize the same type of strategy in this problem but we're always trying to improve ourselves we're always trying to become more efficient and for me it was seeing this initial 109 milliseconds that kind of uh told me that hey maybe my solution wasn't the most efficient but now this one looks like a much more efficient solution than that first one so anyways if you guys like this video go ahead and give this video a big like and subscribe to the channel also please feel free to comment down below let me know what problems you'd like to see done and i will make sure to do them for you guys and um yeah hope you guys have a great rest of the day great start of the week and i'll see you guys next time everyone
|
Shortest Path in Binary Matrix
|
maximum-average-subtree
|
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that:
* All the visited cells of the path are `0`.
* All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner).
The **length of a clear path** is the number of visited cells of this path.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** -1
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1`
|
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2126
|
981 |
um hello so today we are going to do this problem which is part of lead codes um daily challenge time based key value store so the problem says is we have a time-based key value data structure time-based key value data structure time-based key value data structure where we can store multiple values for the same key a different time stamp and what we want is to retrieve the key value at a certain timestamp right so it's a Time map class and we have two functions set and get set gets three values the key the value and the timestamp and we want to store for the key um a pair of value in the timestamp you can imagine like value is something that occurred at this time Stone and the get function gets two values gets the key in the timestamp and what we want to do is return a value such that the timestamp we want to return a value that is smaller or equal than the provided timestamp um and if there are multiple of them like if there the key was insert the key has multiple values Associated then we want to return the largest the one with the largest timestamp right so the most recent one and if there are no values um so the key is not even present we want to return empty string right um yeah so that's the problem here now let's see how we can solve it um okay so how can we solve this well the easiest way if we assume like we get these set values in order which sort of seems like it in these examples then it's super simple so let's first solve it that way um like assuming that we'll get set called in order so we'll end up with a list um sorted right what we can do is just have a map right have a map with the pair of values um being the timestamp and the value right so let's just call it time and in Python let's default to a list because we want to just add values to our list so we can use default dictionary of list right and whenever we get a set we just add the value and we when we get we can just binary search because what the problem wants is the largest value that is smaller or equal than timestamp so that's easy to do with binary search we can either write our own um so it's the closest smaller or equal value that's what we are looking for so we can either use our own binary search or just in Python use bisect to find it right um and so here we will use binary search to find timestamp and this is of course like to find the value and this is of course assuming set will be called with increasing timestamp values right we'll solve it later um assuming it doesn't um and so here what do we want to do um we just want to add it so we take the time key for that key we want to add the new value so this would be timestamp as the first element so that when we binary search we'll use the first value um and Bali right so if it we already inserted in it was just append if it's a we haven't inserted yet then with this we will get an empty list and we'll add this to it um okay so now uh when we get a get first if the key is not doesn't exist even then we want to return an empty string so if the key is not in solve that time then when I return empty right but otherwise we want to binary search you could of course like write your own functions but I we've done that so many times you can look at other problems um so I'll just do it here using Python's bisect to give a different way so we can bisect and this would do bisect right so it will look at the closest uh so it will find the index after all the values smaller so what that would mean is we need to do -1 to get the mean is we need to do -1 to get the mean is we need to do -1 to get the exact position of the value that is smaller than it right so what basically what I mean here is that um let's say we have a values here and we will it will find this value which is the insertion point and this insertion point is bigger or equal then the is bigger actually I guaranteed to be bigger than um then all the values that are smaller than this time and so to get the closest smaller we just do minus one and do it and get this one here right and so that's what we do here and what do we pass to bisectual we need to pass the list itself we need to pass the value we are looking for so that's timestamp and we want to find the in the pair one of get the first value so we can use key just similar to sort and we want to binary search for the first value so that's why we do x0 here and this will give us the index we are looking for and so we can just do self that time so sorry here the list we are looking at is sub.time.key this is the list we are is sub.time.key this is the list we are is sub.time.key this is the list we are looking for because of that time contains all the key all the keys we only want the one for this key and so here we can do key and we have the index and what do we want the value so that at the position one in the pair right now one small thing is what if uh what if there is no value smaller than it so maybe Y is here instead right so there is no small value so we need to check if this is smaller than zero then we just return empty string right because it doesn't there is no value right uh smaller than it um cool so we return that and that should be it and Allah submit okay so that passes test cases now um the one thing I mentioned is that what if these values are not called in order right um so we can either insert and then sort right or even like easier in Python um we have a bisect insert function that we can use which will insert the value at the right position um in the list in an ordered way right um if your interviewer says you can do that you can insert and then sort but then that will take also a long time um but yeah for now we'll just use this insert so what do we do here so if so we can actually just do bisect dot insert and we give it the list and what do we want to add the timestamp the value like this um and so let's try this I'll submit okay so that passes this cases another alternative um is to also use a sorted list in Python which will maintain the order of the elements you insert it in and also supports a bisect function um so that's also another option um yeah so that's pretty much it for today's problem uh please like And subscribe and see you on the next one bye
|
Time Based Key-Value Store
|
delete-columns-to-make-sorted
|
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the `TimeMap` class:
* `TimeMap()` Initializes the object of the data structure.
* `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`.
* `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `" "`.
**Example 1:**
**Input**
\[ "TimeMap ", "set ", "get ", "get ", "set ", "get ", "get "\]
\[\[\], \[ "foo ", "bar ", 1\], \[ "foo ", 1\], \[ "foo ", 3\], \[ "foo ", "bar2 ", 4\], \[ "foo ", 4\], \[ "foo ", 5\]\]
**Output**
\[null, null, "bar ", "bar ", null, "bar2 ", "bar2 "\]
**Explanation**
TimeMap timeMap = new TimeMap();
timeMap.set( "foo ", "bar ", 1); // store the key "foo " and value "bar " along with timestamp = 1.
timeMap.get( "foo ", 1); // return "bar "
timeMap.get( "foo ", 3); // return "bar ", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar ".
timeMap.set( "foo ", "bar2 ", 4); // store the key "foo " and value "bar2 " along with timestamp = 4.
timeMap.get( "foo ", 4); // return "bar2 "
timeMap.get( "foo ", 5); // return "bar2 "
**Constraints:**
* `1 <= key.length, value.length <= 100`
* `key` and `value` consist of lowercase English letters and digits.
* `1 <= timestamp <= 107`
* All the timestamps `timestamp` of `set` are strictly increasing.
* At most `2 * 105` calls will be made to `set` and `get`.
| null |
Array,String
|
Easy
| null |
429 |
hello everyone welcome to learn how flow in this video we'll discuss another little problem that is the nre treat or label order traversal so when it's in re you mean it's like the number of child is uh n so what is a binary means we have two children right that's half we have but when you say a that means it can have a n number of children so we don't uh know how many children so how do we define that the definition is basically uh it's like uh in binary tree we used to say left chair and right here it had two variables the node left and not right but in uh n r tree you will see something like this a list of children's okay a list of children is given to us a list of type node of children so in that channel you will have every uh children address now uh what do we need to like given an energy tree return the level of the traversal of the nodes so level out of traversal means just uh travels through the particular levels okay so whenever we see level out of traversal that simply means uh bfs approach like breadth first search we are we will go to the breadth of each of the levels right so there's no need to go for the depth but we are visiting the breath so like when the question says written the level under traversal of roots the question is pretty easy the question actually meant uh return like the breakfast search of this but the trick over here is the number of children is not two so uh in breadth first search when you do something like uh our current node like current queue dot add our node like the child node in that what you will do you will simply uh run a loop of the to this children uh like the group of through this children uh list and in that when this list runs uh the uh like in that list you will simply keep on adding it to a current uh queue okay so that's a small difference else the question is exactly uh like our uh like the breadth first search of a binary tree okay like for binary we know like if left is not null it add to the queue or if right it's not none like the queue but in this uh you will simply go uh go through a loop for loop or everything in that loop we'll simply keep on adding uh one by one all the children to our current queue so that's a small difference else this is a breadth first search so let's uh quickly go ahead and write the code but before writing the code uh make sure to subscribe to this channel for regular code videos like this and also uh comment down if you uh have any further doubts in understanding this so let me write the code and again i will explain once again like what uh and how this code works uh like how this breadth first search algorithm works right so let's go ahead with that the idea is basically we uh get one uh answer list okay the exact way how we uh solve a breadth first search but the only difference is this part okay only difference is this now what we did we just got like if root is null because uh as i check to do it that the root is actually can be zero so if the root is now we written answer uh if like if q dot uh we just created a new queue over here and then we just offered uh our root performance offer at last okay and we actually uh do something that you don't add but qrad also do it in the last so remember that uh further again simple bfs logic we continue with the uh while loop while queue is not empty all right keep continuing and then we took another uh release that is the level so this error list will be the uh internal list of this right so we took it as a level and further what we did we took the size of the queue right we took the size of the queue and then we uh run from zero till the size okay like till now how many variables are like how many nodes are there in the queue we took all of them and one by one we pulled the uh nodes so when we do pole whole simply means we are just uh pulling from the first since it was a queue remember it's the queue it's like last in fast out so when you're offering is adding in the last and when you're pulling it's adding like removing for the first so one way one the values will be will get uh removed and further we'll go up to the level order uh traversal okay like uh we add it into a level the values okay so the current level and then this uh small thing is the change from our basic bfs logic because this sort of things we create a follow for uh this uh for each child in our temp.children child in our temp.children child in our temp.children list okay for each of the time we simply uh go one by one and add them to our child class i mean add them to our value we have over here fine and then of what we do uh we simply add them and then after this formula we like once we are done with all the current level values like all the size current level values over here so we simply uh go ahead and add them to our answer okay so that's the thing we do over here we simply add them to our answer uh like that we have a level there's an entire list product and finally so this is like the exact b of this logic but the only change with this uh traversal of this child okay nothing but so that's the idea i hope it's understandable it's not so hard and it's understandable yes you see the time complexity changes like not the complexity changes but rather the runtime changes because it's the online judge of this uh lit code might have any problem anyways uh so if we talk about the complexity is only if we look uh like this okay we traverse through all the uh all the values like all the nodes actually that's the which traverse through all the nodes and uh it's more like while q is not empty is like for each of the levels and for uh this slope is for counting the uh total like this loop is actually going through all the values okay eventually it will go through all the values so it's like order of a number of nodes okay so that's the more or less the count over here so i hope it's pretty understandable and uh it's understandable on how we can uh solve it if you have any doubts you know make sure you comment them down i'll be happy to help you out with the comments are as well also like this video and subscribe to this channel for regular report videos like this thank you all for watching this video hope to see you soon in my next video as well thank you you
|
N-ary Tree Level Order Traversal
|
n-ary-tree-level-order-traversal
|
Given an n-ary tree, return the _level order_ traversal of its nodes' values.
_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** \[\[1\],\[3,2,4\],\[5,6\]\]
**Example 2:**
**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** \[\[1\],\[2,3,4,5\],\[6,7,8,9,10\],\[11,12,13\],\[14\]\]
**Constraints:**
* The height of the n-ary tree is less than or equal to `1000`
* The total number of nodes is between `[0, 104]`
| null | null |
Medium
| null |
763 |
so hello friends today we're gonna discuss a very interesting problem from lead code problem name partition labels so i will be putting out a lot of content on code complete coding as you know but i will be also putting up like a lot of content now on different topics wide variety of topics such that you can practice among all the wide variety of topics so i will be putting out some videos on greedy so let's start this problem can be solved using greedy but like i will be telling you in this art but uh in the later videos i will not be telling you we'll go over the problem and they'll discuss how to solve that or approach that problem so this problem name uh actually we can go about the problem statement it states that a string s of lowercase english letters as you can see is given in the problem statement a string of long like integers are given to you or sorry alphabets and now you have to partition this string into as many parts as possible such that each letter appear in at most one part only and you have to return the length of the integer like the integer parts length which actually means that as you can see if like you have to partition this whole string into different small subsections such that every character only appears in only one string each alphabet only appears in one string it doesn't appear in another string so as you can see this a is only appeared in this string you cannot see a in these strings so if this a is one here and one a is in the last position then obviously then like there is only one string because you cannot split the string such that two is appears in two different strings okay so that's the whole problem you can find out how many different strings you can like divide this whole string into and also what are the different length of those strings as the output okay so uh the length actually uh like the first lens is the first line the second length and so on now how you can approach this problem now as you can see the best way to solve this problem is find out the farthest point so let's assume that you iterate over this whole string okay if you take out this whole string uh i'll take this string only to explain you more okay outline okay fill it yeah cool so let's stretch it out first to uh yeah so as you can see uh this a appears first here if you somehow find out the farthest position of a where you can find out as you can see the farthest position of a is here so you can mark out as the maximum which means that you have if you are taking this a in one string then you have to take out the other end somewhat this or more further down the line which means that you cannot make your cut before this a okay so you have to first find out the last occurrence of every character okay what you can how you can find out just enter it over from left to right and for every character store out what is the current position you have seen it so as you can see you have seen a for the first time here so storage that a i've seen at the 0th position when you get from left to right whenever you see an a again just re-update the value re-update the value re-update the value because now you have seen a at the latest and the latest value is this okay so this is fine now what you can do next here is when you trade from left to right for every character find out the maximum length you can like you want such that this character exists in one string cut so as you can see this is a so you have to make the other string cut not less than this so this is the maximum position you have to still make your cut for b as you can see b is less than this maximum cut so it is fine a the maximum update is here so it is fine b is here c is also in this c because there is no further a is here c here is here and a when you come to the iterating point when your i come to the same point which is equal to maximum then you realize that okay this is my one cut position so you can make your first cut at the zeroth place and the other cut at this place so this is now you can easily find out the length by the last position plus the current position this is the length now your next last position the next cut or the next string will start from this okay now you are at d find out where the farthest d you can see okay this is the furthest thing now for the e where you can fart is d e is here so now your fathers go to this position okay so this is not the farthest if f is not here e is okay this is the farthest g this is the farthest d e as you can see now this is the farthest so now this is the last occurrence the cut is here so this is the length of the cut and now the next cut will start from here and so on now you can understand the logic part of this now so this will always happens to be forming out an optimal cut out of this string because you are cutting out the string as the most farthest okay because uh because you have to take this string as a whole anything in this string if it is the farthest is less than the string then it's obviously fine because you are inside this else if it is more you have to shift your maximum to the right side more and that's the whole logic for this problem i'll take out the code part now uh this is the a is it about the whole string and find out the latest or the last position it is seen by updating the i values that is that this is the last occurrence and this is maximum okay so maximum is the maximum occurrence so the maximum position you have to mark this out okay then iterate from left to right and for every ith character on which you are update the maximum okay and at any position when my i become equal to maximum i know that i have come to the end okay for every position for every character is b the maximum with b is this which is less than a okay so my maximum is storing out the maximum position i have to do a cut if this the value of every character maximum is less than this then it is fine this is this will still remain the maximum else if the other maximum is more than this then i have to update my maximum and at any time i become equal maximum that means that i have come to an end so now i have to push this length which is i the current length minus the last position plus one okay and then push this in the answer and now my last will become the eighth position plus one because or you can see the maximum position plus one because this is the current position the next current cut position will start from this the next plus that the next character and then the answer is just fi like iterating out or actually printing out the final answer vector which is storing out the lens which is this okay and that's the whole logic for this problem i open the channel logic as of the code part for this question if you're still involved you can mention on the unbox as the next one keep coding bye
|
Partition Labels
|
special-binary-string
|
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`.
Return _a list of integers representing the size of these parts_.
**Example 1:**
**Input:** s = "ababcbacadefegdehijhklij "
**Output:** \[9,7,8\]
**Explanation:**
The partition is "ababcbaca ", "defegde ", "hijhklij ".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts.
**Example 2:**
**Input:** s = "eccbbbbdec "
**Output:** \[10\]
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1).
A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached.
Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached.
If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is:
reverse_sorted(F(M1), F(M2), ..., F(Mk)).
However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
|
String,Recursion
|
Hard
|
678
|
496 |
[applause] [applause] [applause] [ [ [ applause] [ applause] [ applause] Hello interesting problem name is this next cricketer written curious mines one square in return d answer ok answer is re and this is answer of I is nothing but d next cricketer element ok and explain you What it is question is saying about this example from this they can easily understand so where life is you are ok number one is where you are ok in terms when are you are not small of which is the subsidy of not you so per namas One way need you find suppose there comes d first zero d index they have four know and search on it they have anything which is greater give 4 towards d right in namas you need you give d index ok per example no it is not so They bill pat so -1 in this They bill pat so -1 in this They bill pat so -1 in this how to give they have one ok they have one so co and search one is every in this number you is this one find d next retail element towards right ok next limit is three ok four is also greater so they Bill Pat Debt Values 3 In greater so they Bill Pat Debt Values 3 In greater so they Bill Pat Debt Values 3 In This How Nothing Is There -1 Example Latest Discussion D Approach Okay So If You Are In Trade Yourself Debt Is Good If You Are Not Just See This And Tree You Jump By Yourself So They Are Life You Are Arrested Number in all set of n so per every this one per every element they need you find d next limit in d you ok so for four in d you have towards d right nothing is there ok so they bill pat mines one ok per one way Have three four you are F-1 and what is it Have three four you are F-1 and what is it Have three four you are F-1 and what is it approach what is it observation first think first observation is date last element is there no date bill nothing you it's right so it bill put mines one there okay date is on sir date is done so They bill start over from this ok so 4 what bill be doing so if approach is something like they bill be using hashtag every and bill be using stock ok every value in lamps you bill find d solution ok let's start from one so one is there Na bill pat what tu d value per this i media text element is three per three what is d next element vich is per four what is d next element -1 per tu what is an expression -1 ok -1 per tu what is an expression -1 ok -1 per tu what is an expression -1 ok so can see per one they have three But three way are but four is also -1 and but this last one which is four is also -1 and but this last one which is four is also -1 and but this last one which is you have this one right these are D elements debt they have life no debt bill post in you debt bill story in our has map okay so this is done okay And Give What Bill B Doing Per Every Value Bill B One Hashmat and Debt Bill B Constant Operation Order One Operation Four Bill B Finding In Per Bill B A Minus One And One Bill B Having Three And Thou Bill B Having -1 So Debt Bill Just Keeping d update on d element ok latest this one direct approach your way have this one ok they are going to be creating hashmating n stack nerves ok so first think what bill does in this map bill add d first you value ok first by value which is tu because per d last one they are sir date d value bill b not date anything bill put de right bill not b greater den those ok so they have tu in per tu wheel b having mines one per shop date they already put and in de stock They bill b starting from d very right so tha pushing dat tu aate d initially only initial and let bill b starting our position over index from this one which is non stop length - 2 ok so from this one which is non stop length - 2 ok so from this one which is non stop length - 2 ok so bill start over iteration from every way bill co towards d Left From Her Checking They Need You Put This Value This Values Can They Have Without Checking They Need You Put This Value This Values Can They Have Without Checking They Need You Put This Value This Values Can They Have Without You Values Here It Can Be You Values Here It Can Be You Values Here It Can Be Mines One And Something Else Somebody Some Mother Element Which Give It Greater 4 OK But Singh Every Date Bill First C Date On D Towards D Left Also it's not going to be using because four bill be brother on sir which is greater than this you so witch is poet and wicked so gas sir date mins one bill be do date after date bill put this four on top of de state OK no four is date come d top of d state no again they bill on d three per three unit you put something here it can be -1 more elements so here it can be -1 more elements so here it can be -1 more elements so first bill check in d state they bill check in d state if some element is Greater den three yes this value is greater den three ok so bill push simply date three bill b having d value of four in this how ok and check this three bill not b four bill not b popping out because it is greater den three den they bill to but on d previous one ok on d previous one this three can be d immediate next on example on one this three it which d four give it greater one but they are not taking d four further output bill take in d one because they need tu Find D Next OK Immediate Tax So Way Bill Question Three And Top Of This OK Give What Bill B Give Bill B Having This One Right Bill B Singh D Top Of D Stock Which Is 3 Ok Will Look Pushing Date - 14 Date Is Don No Bill B just singh in - 14 Date Is Don No Bill B just singh in - 14 Date Is Don No Bill B just singh in d number one are and take in d value one by one so four wheel minus one per one bill b having three and you bill b having -1 b having three and you bill b having -1 b having three and you bill b having -1 ok so date is simply they are going to be using this ok and date operation Tax order of one basically ok so let try you solve this problem and write this number let start ok so simply way bill write has map and date bill make wait comment teacher ok because of will be wait and de valuable wait ok and welcome and way Can him new # also start portland-1 ok with last value basically noms tu dot length they are put de first value iteration on this one mine's i - so first think what bill check first think bill check wether the stock first bill tree tu pop de Waluj OK [MUSIC] [ MUSIC] I coma tu compare ki rate tere is nothing they can put dat ok so dat is wicked dat wicked this one some value bill be right which is de top of de step with greater den dat so putnams tu simply Push over d last element ok and bill b putting tha number -1 ok so man bill b putting tha like you go d basic idea of this problem thank you for watching
|
Next Greater Element I
|
next-greater-element-i
|
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array.
You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`.
For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`.
Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._
**Example 1:**
**Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\]
**Output:** \[-1,3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3.
- 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
**Example 2:**
**Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\]
**Output:** \[3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3.
- 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1.
**Constraints:**
* `1 <= nums1.length <= nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 104`
* All integers in `nums1` and `nums2` are **unique**.
* All the integers of `nums1` also appear in `nums2`.
**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution?
| null |
Array,Hash Table,Stack,Monotonic Stack
|
Easy
|
503,556,739,2227
|
225 |
hey everybody this is larry this is day fifth oh cinco de mayo huh uh anyway and i forgot yesterday was may 4th you know may the fourth be with you i don't know i mean i'm just a nerd i guess so i did forget it so maybe not that much of one but anyway uh how does it go felice cinco de mayo i guess uh yeah happy i don't know if that's a real thing that bill celebrated just like one of those things that people do to get like i don't know uh just like a thing but uh but yeah anyway today's form is let's get to this one it's implement stack using queues uh i was going to say it was like uh what you would call it uh like a holiday they create to sell alcohol or something but i don't know maybe it is i feel like that's just like one of those things but uh anyway that's all right implement stack using queues let's focus on this welcome uh if you're new here uh we'll be doing this all month uh or these problems i mean we have a 760 something streak going as you may discover um so you know i'm not going to work that today uh and also sometimes i have like a little re-logy update um not much today um re-logy update um not much today um re-logy update um not much today um except for what we were just talking about with singles in maya so hope you find that amusing if not that's okay usually you could skip the beginning uh if that's what you're into um but yeah but hit the like button hit the subscribe button and come to discord if you want to chat about anything like that anyway okay let's get to it so you have a stack that's in first i'm using two cubes oh i have a funny thing about this uh this was something that i was given this problem um on my on an interview that i had in 2005 say uh wow just saying that yeah allow makes me like age myself uh so i remember this problem uh and i also remember it because i messed this up because at the time i just didn't well i mean just to be clear there was no lead code and stuff like that and i was very good you know even that i mean maybe not very good but like good enough in competitive programming per se that like at least at the job interview level right like yeah like i they filled out really good um i was just like merely really good at he's good enough to pass job interviews because they weren't really that popular at the time with respect to uh competitive programming e problems except for say google or something like that um so yeah uh i got this problem not as a coding problem but more of a brain teaser problem and i didn't get it to be honest because this type of problem doesn't really come up in competitive programming right it's about like problem solving and less about like you know data structures i mean i did get it but at the very end but it took way too long and it was just a no-brainer i suppose no-brainer i suppose no-brainer i suppose but yeah so i do remember this very well uh and it's kind of really like a cute idea but i just beat myself up because i you know like i said it was like 17 18 years ago and i still remember because i was like larry should have gotten it good um because i was doing some thing where like you have two cues but you just keep on uh moving the items back and forth and i wasn't able to prove at least to myself at the time because i know i was just younger and maybe a little bit more nervous you know during an interview um like this idea that like it's that uh like this idea of invariance and how to kind of handle it um so yeah uh but that's basically oh actually i think i lied to be honest now that i read this problem maybe correctly i think my problem was implement cues using two stacks where this one is using uh implement a stack using two cues so okay so i lied a little bit but the idea is still the same so hopefully you find this story interesting uh and it still have the same premise that like you know it doesn't really come up so let's think about what it me and now it's funny because we see it and it's an easy problem right so we'll see how i will see if i actually solve it because it's still not the type of form that comes in competitive programming okay so now we have two cues you want to um you want to simulate a stack or implement a stack okay so then now i guess you know for a stack the only well i was gonna say two uh operations but i guess peak is an operation as well um so or i guess top end peak is like these two uh operations but not really the only two that i was thinking of is push and put pop so first of all let's have just two cues i imagine there's some way of putting them um but yeah i mean i don't think it's that bad basically you just want to make sure the last number you're in is out okay so let's just even write it out just like q1 solve that q2 right um and we'll use collections. like uh also i see that sometimes people on my discord channel you know we share solutions just to kind of like get code reviews and feedback and stuff like that another reason why you should join um people definitely sometimes just like get a little bit like i don't want to sell it this way i'll just like you know use a stack and then just literally do it i mean at the end of the day um no these things are for you right like the things that you challenge yourself the time that you spend on these problems exploring and discovering things um these are things that you know you're gonna learn for later and if you do a shortcut or like you know just to get a streak contained but not really learning anything and we didn't think it through you know at the end of the day only you know and only it only matters to you so you know uh it is what it is there's no uh right wrong answer in well i mean and you could we if you have to ask whether an interviewer is gonna ask you probably already know the answer for that one so like you know prepare for it or whatever but that's really up to you okay so let's talk about push right so in this point uh let's say we start with an empty state right so i'm just thinking about it all just all the combinations one by one so let's think about it from empty states well there's only one thing you can do um i mean and of course there's some symmetry here so it doesn't matter which one you append right and then now let's say you apply the second one right well what does that mean okay so let's actually visualize this a little bit i know the other solution but i don't know so let's say we have two cues how do we put them in a good way so let's say we add number one and then let's say now we add the number two right um how do we use the second or do we use the second queue right all right let's say we have a number then we use the first queue and then we use the second queue right uh i mean in this case it's gonna be o of n so i think oh wow one q well i'm trying to think for a second because i mean uh on what i can do here right um i mean so the other i would say that the other solution the cue using two stacks you know uh something that you do find out in computational theory for example is that it is turn complete so you could do everything i'm actually not sure about two cues so i'm not super sure here but i would also say that i don't know if they want us to have a linear solution that's why i'm like contemplating a bit right because if we can have like an o of n solution for push and pop like that also makes it kind of trivial so i don't know if i can do this in all of one but let's play out with some ideas first um let's say we put in the numbers one and two what is a possible way for us to do it right one two um so the idea that i had that over n is that every time we add a number we just kind of uh can we do that let's say we have a 3 right with three and then now one two well that's not well okay let's try it from beginning i think my states are weird so let's say we have two cues um so the idea i have is that let's say we have two then now it's two and then now you take the one from the other one so it looks like this and then the other you know let's say you added three so now you have a three here and then now you have two and one right so you have kind of like something like that but this is going to be o over n every time because you have to uh um you have to get rid of the entire kill every time right so you know of course that's going to work because we have at most 100 calls but i'm trying to think whether we can do better and also but i can do it with only one queue doing it with one cue is interesting isn't it well i mean doing it with one q if you can do o of n is the same in that yeah you don't need this you just on insert let's say you have one and then now let's say you have a two well yeah let's say you have a two then you put this in one two and then you just keep on rotating the array essentially until it's two one and then next now you have two one so then now you add one three to the n um and then now you just keep on rotating so now it's three two one right so that's not that bad um to use one q i'm just trying to think whether or n is necessary and when i can think of a constant solution for this one or a constant time solution for this one because otherwise this is probably it and pop is straightforward in that sense um i think the thing is that and i'm also trying to think whether we i mean this would be very pop optimized but i was wondering if we can do some kind of delayed thing and then maybe the amortization makes it all of one even though you do it but no it's tough these forms are tough for me because in many times you know like it's just about creative and using your tools and versus like here the key part of this is that it's restricting your tool in that like well you have to implement a stack uh well you just implement the stack the normal way right so um obviously not the case here though um and these two are also input so in this case push is going to be o of n and all these are going to be over one is that good enough can i do this in all of one this is also a little bit harder because i'm at home doing it by myself right because obviously if i have an interviewer um i think this is something that we'll talk about and then i could maybe see if i can figure out uh what the intended solution is right like if i need to do better then i need to do better if not then you know but i don't know and it is tricky that this only like if this was like say like a million calls would be made then i'll be like okay oh if n is not going to be fast enough right but the tricky part is that all event is going to be fast enough so that's why i'm like is there a better solution i don't know uh let me think um i mean while we're using one q i feel like the one q is kind of a hint in that way and that i don't think there is a like i don't think you could do an of one otherwise you would just never have a stack you just have one queue right so okay fine let's try it this way and then maybe we could see if we learn anything um from or maybe even past larry i don't know if i've submitted this problem before so yeah so basically let's say um okay n is equal to link with self.q okay n is equal to link with self.q okay n is equal to link with self.q um so then now what we want to do is self.q dot append x and remember that n self.q dot append x and remember that n self.q dot append x and remember that n is the last number so then now we do something like this where x is equal to sub.q dot pop this where x is equal to sub.q dot pop this where x is equal to sub.q dot pop left and then self.q dot append x uh left and then self.q dot append x uh left and then self.q dot append x uh maybe i'll use y in this case because yeah and you could technically put in one line but you know that's what i do and then pop is just self.q dot pop left and then pop is just self.q dot pop left and then pop is just self.q dot pop left and then return it top is return sub.q.z top is return sub.q.z top is return sub.q.z don't know if i'm supposed to return like if this is empty um maybe for an exception this was an exception but in theory supposed to re-cast the exception in a more re-cast the exception in a more re-cast the exception in a more understandable kind of way but yeah whatever it's fine for now all right let's see uh i mean this is going to be right i think other than maybe off by one which is possible um this should be right um yeah let's give it some minute it's i should probably test more cases because it's very typeable but um yeah 765 days so yay uh yeah like i said i think the difficult part for me in this one is just not knowing whether this is optimal and very often these things are kind of tricky to prove optimality um let me see if i can create solutions and see yeah that's basically what i did except what i did with one queue uh okay same thing but with one queue okay i mean this is just different operations okay so it seems like this is the intended solution and we spend a lot of time talking about it because i wasn't sure if this is the intended solution um and the reason is because like i said on a real interview you'll probably like suss it out and you know but in here like i am talking to myself i know that you're watching and it seems like i'm talking to you and i'm trying to but i cannot read your mind or maybe you know uh but okay i mean yeah wait there is a maybe all of one amortization that's what i was saying that's what i wondered yeah that's what i thought i mean now i'm reading solution comments but i mean i think this isn't that bad to be honest like i think easy as pride i'm just reading the comments i think ec is probably the okay um like classification i think the tricky part comes from not knowing how fast you want push right because we knew then we got it pretty quickly if we you know if we like i was trying uh earnestly for a while to see if i could have an over one either amortized or not amortized but i couldn't really figure it out and also like i said if you could do a one q over one solution then you wouldn't need stack as a data structure you just use a queue every time right so i feel like that was my thing to say like that doesn't really make sense um and that's why they're two different things right um so yeah anyway that's all i have for today let me know what you think hit the like button hit the subscribe wait i did submit it's correct right i want to make sure because sometimes i forget and then i miss the day uh anyway that's all i have done hit the like button hit the subscribe button join me on discord i'll see you later take care and goodbye
|
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
|
509 |
at lead code 509 fibonacci number and we're just going to solve this in the context of looking at recursion as a tree we're not going to look at the most efficient way to solve this we're just going to look at the recursive way and the idea behind that is i just want to give a little bit of a primer or a warm up into the next problem sets that we're going to be doing which is dealing with combinations permutations and subsets so just want to do a quick refresher on recursion and also how to look at recursion as a tree so here we have fibonacci numbers denoted by f of n from form a sequence called fibonacci sequence and it's such that each number is the sum of the two preceding ones starting from zero and one that is so here fib of zero is zero fib of one is one okay where f of n is equal to f of n minus one plus f of n minus two for n is greater than one so here fib of two is going to be one fib of three is two and fib of four is three okay so let's say we have fib of four okay so n is going to equal well let's calculate what that what it's what our answer is going to be so fib of 1 is 1 then it's going to be 1. then we're going to take the next two and that's going to be 2. we're going to take this one and that one so we're going to take the previous two numbers and add them that's going to be 3 and then we'll get our fourth number which is 3. okay and so we're just going to use recursion here and the way we want to do it is if our main function is fib of four then there's two choices we can make on this okay we can create a recursive tree there's two choices we can either subtract one or we can subtract two right so here we're going to get fib of three and here we get fib of two all right so moving forward we're gonna get to three and we have two choices we can subtract one or we can subtract two so here we'll get fib whoops fib of two let's see here and fib of 1 and now our base case is going to be if the input if n equals 1 we return 1 and if n equals 0 returns 0. so here when we subtract two from three we're going to get one and so we're going to return one all the way up the chain okay and then here on our left side we're gonna subtract one and subtract two so here this is going to return 1 and then this is going to return 0 up the chain okay similarly here we're going to subtract 1 and subtract 2 this is going to return 0 and this is going to return 1. and so you can see at the base case it's going to return one and that's going to add up as it goes all the way up the call stack and then we finally we return that okay so i just wanted to quickly do this just to give you a refresher on how to view recursion as a tree all right so we're just gonna have our two base cases here so if n equals zero we return zero if n equals 1 we return 1. and then all we do is we just return fib of n minus 1 plus fib of n minus 2. okay we can run that and we're good now this is not the most efficient way it's actually a very inefficient way you can look into tabulation memoization or even a dynamic or a greedy approach that's much more efficient but i'll leave that for a different video i just wanted to take a second to review recursion that would be a good little primer on the next couple questions we're going to do okay so that is lead code 509 fibonacci number hope you guys enjoyed it and i'll see you all on the next one
|
Fibonacci Number
|
inorder-successor-in-bst-ii
|
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given `n`, calculate `F(n)`.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1.
**Example 2:**
**Input:** n = 3
**Output:** 2
**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2.
**Example 3:**
**Input:** n = 4
**Output:** 3
**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3.
**Constraints:**
* `0 <= n <= 30`
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
285
|
8 |
hello and welcome back to this cracking fang youtube channel today we're going to be solving lead code problem number eight string to integer let's read the question prompt implement the my a2i function which converts a string to a 32-bit signed integer 32-bit signed integer 32-bit signed integer what we want to do is read in and ignore any leading white space then we want to check the next character if not already at the end of the string is a minus or a plus we can read this character in if it is either this determines the final result being positive or negative assume the result is positive if neither is present then read in the next characters until the next non-digit characters until the next non-digit characters until the next non-digit character or the end of the input is reached the rest of the string is ignored convert these digits into an integer ie the string one two three should become 123. if no digits were red then the integer is zero change the sign as necessary from step two where we parsed whether it was positive or negative if the integer is out of the 32-bit signed integer range out of the 32-bit signed integer range out of the 32-bit signed integer range then clamp the integer such that it remains in the range specifically integers less than minus 2 to the 31 should be clamped to minus 2 to the 31 and integers greater than 2 to the 31 minus 1 should be clamped to 2 to the 31 minus 1. return the integer as a final result note only the space character is considered a white space character do not ignore any characters other than the leading white space or the rest of the string after the digits okay so we read the really long question prompt let's look at an example now okay we read the question prompt now it's time to look at an example let's look at this input s equals four one three nine with words so we should parse one uh four one three nine why is that remember the first thing that we do is handle any leading white space which we don't have here then what we want to do is we want to check for any positive or negative signs in our string we don't have that here so we don't have to worry about it then we start parsing so first we're going gonna parse our four then we're gonna parse the one then we parse the nine then we parse the three and then we get to a white space which it tells us okay the second we see a you know non-digit the second we see a you know non-digit the second we see a you know non-digit character here then we just stop so our iteration stops here and we simply return this as an integer and since you know we convert it and we check okay well you know this is still within our signed integer range so we don't have to do any sort of clamping so we're good so we can simply just return 4193 what about this string s equals you know some space here minus 42. well remember that the first thing that we do is get rid of any leading white space so we can think of this string as actually just being negative 42 after we strip out any leading white space now what we want to do is check for any positive or negative signs this problem does have a negative here so we'll have to return our results whatever we parse from the numbers as a negative so then we start parsing so first we parse the four then we parse the two and then we actually reach the end of the string so it's time to return our results now we parsed 42 but remember we had the negative sign so we need to say negative 42 and we also need to check whether or not you know negative 42 is between um the you know signed integer range so is it in this range yes it is so that means that we can simply return oops there's negative 42. uh so we can simply return 42 here so that's the approach we want to take for this problem let's go over kind of the algorithm the first thing is going to be you know strip white space right strip leading um leading spaces and this is really painful to try it out and then the second thing we want to do is check for positive or negative right positive or negative sign in the beginning and then we want to parse um you know digits and then after we parse our digits we want to check the you know integer range right check num you know between what is it going to be negative 2 to the 31 and you know 2 to the 31 minus 1. so that's what we want to do right uh we want to make sure that it's in that range and if it's not then we need to clamp it down so well i guess yeah so that's the algorithm that we want to use here it's relatively simple this problem is annoying because there's a few edge cases but once we go into the editor we'll handle all of those one by one and you'll see that this problem is actually really easy to solve so let's go to the code editor and we'll write it out we're now in the code editor and it's time to write the code remember that the first thing that we want to do here is to strip out any leading white space in our string so let's do that now so we're going to say string is going to be equal to string dot l strip so l strip will get rid of any of that leading white space now what we need to do is we need to check another edge case this problem is more of a question around edge cases than it is the actual parsing of numbers so i can see why interviewers like to ask this one now what we need to do is after we've stripped out the white space we need to check whether or not we actually have a string here it could be the case that the string was entirely white space we got rid of it and now our string is empty so there's nothing to parse so at this point we simply want to return 0 if the string is empty so we're going to say if not s we're going to say return 0. now what we want to do is we want to start processing our string and we're going to do this with a while loop and then parsing it index by index and accumulating uh while we you know still have valid things to accumulate so we're gonna say i equals zero and remember that what we need to do is check whether or not we have a positive or a negative sign at the beginning this is the only time that we're allowed to have one of those is at the beginning of the string so we're going to use sine equals 1 to signify that we have a positive number and it'll be negative one if the sign is negative right because then at the end we can take whatever number we parsed and simply multiply it by the sign if it's positive no problem it'll stay the same if it's negative obviously multiplying by negative one will turn any positive number negative and this return the same number so that's why sine is going to be one now we need to check for that character so we're going to say if s of i equals to a positive then we're simply just going to increment the i point uh index by one we already have the fact that you know sine is one so we don't need to reset it otherwise we're going to say if s of i so basically if the first index is a minus sign then we need to you know still move i up and now we need to say that sine is going to equal to negative 1. cool now we can start parsing our value so we're gonna say parsed is gonna be zero and we're gonna say while i less than len s so we're gonna parse you know from left to right and we're gonna say that the current number is gonna be s of i and we're only allowed to parse digits at this point if we see anything other than a digit then you know we know that we have to get rid of it we can stop our iteration here we know that we can't go any further because something's wrong with our input we can only parse digits we're going to say if not cur dot is digit so basically we're just checking whether the current number is a digit then what we want to do is we would just want to break out of this loop we don't want to do anything here we just want to break out because that means that we've seen some sort of invalid input so we should just return whatever we were able to parse and ignore the rest so otherwise if we have a valid digit then what we want to do is we want to say parsed is going to equal to parsed times 10 plus integer value of whatever cur is so this is how you parse uh numbers when it's you know going serially through a string so if you've never seen this before i'll just do a quick introduction to why this works whoops uh so say we have the string one two three and we're parsing from the left so you know the first thing that we're going to parse is this one so you know our parsed you know initially starts at zero and now parse is going to be assigned to whatever parse times 10 is so obviously 0 times 10 is 0 plus the integer 1 right so that means that parse now equals one then we get to this two so you know parsed times ten will now give us ten plus you know the integer whatever curve is so it's two so this means that parsed is now 12 right cool then we get to the 3 so we multiply this again by 10 so we have 12 times 10 plus the integer of whatever curve is so 3 and we get 1 two three so you can see how it works to basically you know handle the fact that we parse the one first except for this is like you know the largest so this is the hundredths value but we parse it first so that's why we multiply by 10 each time to account for the fact that we're parsing from left to right except for that you know it needs to be multiplied by 100 actually so that's how we handle it so if you've never seen this before this is usually the pattern for parsing out an integer from a string when going left to right so getting back on track that's how we handle parsed here and at the end what we want to do is we just want to increment our i to continue parsing through our string so at this point either our while loop will end because we reached the end of the string and we were able to parse everything that we needed or we hit something that wasn't a digit and we just need to return whatever we were able to parse remember that we can't just return parse times the sign we actually need to check whether parsed is within the valid uh where does it say if it's in the uh 32 signed 32-bit sign integer range so right 32-bit sign integer range so right 32-bit sign integer range so right negative 2 to the 31 to 2 to the 31 minus 1. so we have to make sure with we're within that range and if we're not then we have to clamp it down to fit inside that range so now we need to apply our signed so we're going to multiply parse by whatever sign was so it's either going to be positive or negative and now we can do the clamping so we're going to say if parsed is greater than 2 to the 31 minus 1 then we need to clamp it down to 2 to the 31 minus 1. so we're simply going to return 2 to the 31 minus 1 in the case that it's too big on the positive side and then we're going to check if it's too small we're going to say else if parsed is actually less than or equal to minus 2 to the 31 um yeah minus 2 to the 31 oops to 3 to the 31 then we want to return 2 to the 31 minus 2 31 sorry about that and uh keep double here uh otherwise what we need to do is simply just return parsed because it's within the range so we're all right there so what we're gonna do is submit this make sure that it works and for some reason i seem to have made a bug um what did i do here oh i didn't even return parse whoops okay that's embarrassing or anyway okay so once we fix that bug we can see that um we fixed the code here so what is the runtime complexity of our algorithm well this l strip is going to take big o of n time in the case that our entire string is actually white space it's going to take big o of n time to do that so this l strip is going to cost us you know big o of n and what we need to do is we need to parse the entire string so even in the case where we don't have anything to strip um we still have to go through the entire string so we're still bounded by big o of n in the time complexity because we'd have to parse out the entire string s from left to right so time complexity wise is going to be you know big o of n um space complexity wise we're not actually defining any extra space here all we're doing is creating a pointer i uh and i guess assign to n parsed which is going to hold our um you know data here but these are all just constant space allocations right they're just integer values so we can consider this as big o of one space um so that's gonna be how you solve this problem it's not too complicated i think it's relatively simple you're just going from left to right parsing values i think the complexity of this problem really comes from the edge cases right you first need to make sure that you stripped all the white space then you need to make sure that you actually have a string to parse then you need to handle the signs then you need to do the parsing make sure that you break when it's not a digit then handle the fact that you need to clamp things down there's just a lot of things floating around and it's easy to miss one of these so make sure you kind of study this problem understand what it's looking for this is definitely one where you want to work with your interviewer to like really establish you know all the edge cases and understand what you're really trying to solve because if you just try to jump into this and you miss something it's going to be a really bad coding signal for you the interviewer is going to be like okay this guy just doesn't ask enough questions he jumps into the problem um without knowing what he's doing then he has to go back right it just doesn't look too good on you as a candidate if you're doing that so you want to establish all the things that you're looking for identify those edge cases before you start writing the code because if you don't then you know it's going to look bad on you as a candidate and if you make mistakes it's going to weigh you know twice as heavy because the interviewer is like well you know you didn't even ask these questions you jumped right in you know sucks to be you so that being said you know be careful with the edge cases ask your interviewer uh you know any clarifying things that you need to and then start writing the code once you have identified you know your plan of action so that's gonna be this problem i hope you enjoyed this video if you did please leave a like comment subscribe if there's any other videos or topics uh you'd like me to make videos on please comment in the comment section below and i'll be happy to get back with back to you with those videos and otherwise happy coding bye
|
String to Integer (atoi)
|
string-to-integer-atoi
|
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function).
The algorithm for `myAtoi(string s)` is as follows:
1. Read in and ignore any leading whitespace.
2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Convert these digits into an integer (i.e. `"123 " -> 123`, `"0032 " -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2).
5. If the integer is out of the 32-bit signed integer range `[-231, 231 - 1]`, then clamp the integer so that it remains in the range. Specifically, integers less than `-231` should be clamped to `-231`, and integers greater than `231 - 1` should be clamped to `231 - 1`.
6. Return the integer as the final result.
**Note:**
* Only the space character `' '` is considered a whitespace character.
* **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits.
**Example 1:**
**Input:** s = "42 "
**Output:** 42
**Explanation:** The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42 " (no characters read because there is no leading whitespace)
^
Step 2: "42 " (no characters read because there is neither a '-' nor '+')
^
Step 3: "42 " ( "42 " is read in)
^
The parsed integer is 42.
Since 42 is in the range \[-231, 231 - 1\], the final result is 42.
**Example 2:**
**Input:** s = " -42 "
**Output:** -42
**Explanation:**
Step 1: " \-42 " (leading whitespace is read and ignored)
^
Step 2: " \-42 " ('-' is read, so the result should be negative)
^
Step 3: " -42 " ( "42 " is read in)
^
The parsed integer is -42.
Since -42 is in the range \[-231, 231 - 1\], the final result is -42.
**Example 3:**
**Input:** s = "4193 with words "
**Output:** 4193
**Explanation:**
Step 1: "4193 with words " (no characters read because there is no leading whitespace)
^
Step 2: "4193 with words " (no characters read because there is neither a '-' nor '+')
^
Step 3: "4193 with words " ( "4193 " is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range \[-231, 231 - 1\], the final result is 4193.
**Constraints:**
* `0 <= s.length <= 200`
* `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
| null |
String
|
Medium
|
7,65,2168
|
882 |
hey what's up guys uh this is sean here so this time lead code number 882 reachable nodes in subdivided graph okay so apparently this is a graph problem right so we're given like graphics unknown labeled from 0 to n minus 1 and then we will subdivide each edge into in the graph into a chain of nodes with number of the new nodes based on the count of this edges right so what does it mean it means that you know for each edge right so each edge like this one from u to v right we have u and we have v this is h right so if for you uv and count so let's say if we have a count equals to equal to two here it means that we're going to add two more nodes in between these two nodes and into this uh edge like this okay right if it's zero it means that there's no new node that's so that's it right okay and then okay so we have the edges here and we have a node n here and we also have like this max moves here so max moves means that our task is in this new graph right after dividing each node based on this column here we want to know how many nodes we can reach right within this max moves right so what does it mean it means that let's say we have a many nodes here let's say we have a lot of nodes here okay so let's say the max move is two okay it means that we only we can only move uh max uh to two nodes first to two nodes right uh let's say the maximum is three here right so it means that you know from here to here i oh we start from zero right i reach for from zero so let's say this is not zero let's say we have another node here okay you'll be uh k here right so as you guys can see we can arrange uh which uh what are the notes we can reach we can this one is fine because to move to the this node we only need one move right to move to here we only we need two moves right but how about this node in between here right i think we can move uh reach to this one because that's one two three right so this these three are fine and this one is also fine and why is that because we can reach this one from this path one two three and four right but for this one no matter which way we go we'll never be able to reach this one which this max moves right so that's why the total is like what one two three four five six seven so the answer for this graph is this maximum equals three will be seven right i think that's what basically this example one is telling us for this one we have a like from zero to one we're gonna add ten more new nodes uh in between right and for this one we have one and then we have two right so that's that and we have some like basic constraints here right so for this kind of graph problem you know since we want to know if we can reach this node within smax moves it means that if there are multiple paths that can reach this node apparently we're going to take the shortest path right then which leads us to like the shortest path uh algorithm which is uh tax room right basically the doctrine can tell us the what the um the shortest distance right between zero to each node right and then for this one the weight will be the count right it means that you know basically if from zero to two right we need to uh use uh the weight will be one right but actually it should be two it should be a one plus one because uh this count this the second the third parameter here is the new nodes it's the new node we added in between right but to reach the to two we need to do a plus one to make it at the real weight right because with one more uh notes here we need a one plus one we need the two moves right to move from zero to two so this is one thing we need to be uh careful when we create the graph right so um so what we should do is that you know let's forget about this splits here right let's only consider this one as a weight right in that case uh we can easily use diagram to calculate the weight right the weight uh for each of the note uh given i'm sorry the shortest path three for each of the note okay and then with that we can then try to calculate how many uh nodes we can write it in between those right and how can we do that right so let's say we have this one we have this zero right no we have this one and we have this one right they're like uh let's say they're like ten nodes in between okay so this is u right and this is v right so for each of the edge so let's say the distance right so the shortest distance for u and v so the first scenario is what if both of them are greater than max move right so if that's the case that apparently we cannot visit any of the nodes in between right is what second is actually second is that basically it will be either of them will be uh within the max move or both of them will be in the max moves so in this case we have several scenarios basically we can reach any of them from left from right or there could be over overlapping right so in this case you know there's no overlapping between the left and right so this one means that from left we can reach uh six right then from right we can reach one in this case seven is fine but what if there are some like overlapping let's say from the left we can reach this part and from right we can reach this part right then there's some overlapping so apparently we can just simply use the left the minimum of the left and the right and then and also what our left plus right and then the weight here weight is basically it's a note in between yeah i think that's it right so basically by using this kind of uh a shortest path right and what's the left is the maximum max minus the shortest distance the distance of u right and the right similarly is the max minus the distance of v right so that's the basic idea here um yeah so that after calculate uh so that's the way we how can we uh count the note in between the edge right uh yeah let's start coding right uh let's finish let's write the diagonal algorithm first so for the x0 you know we need the diction we're in the uh the graph right so it's going to be a list so for you right now we have u v and we have weight right in address okay so for graph we have a u dot append right so like i said you know here uh when we create the weight for each node for each edge we do our w plus one right because that's the uh w is the new it's a new node and to be able to transfer it into moves we need to do a plus one right and then we have a similarly thing for v here right and this time it's going to be a u w plus one okay and then we have a distance right so we have distance for each of the node uh between each node is the node zero right so at the beginning everything is the biggest and then we have this one is at the beginning of zero to zero is zero right now we have probably q right the parity q is it like this so for darkest row so the first one is the uh is the current distance right to node u right and then we have what so let's do the texture first so while priority q so we have uh the first one is going to be the weight right it's going to be the weight second one is going to be the note right so remember we need to put the weight the current a distance yeah actually you know let's call it let's call distance okay maybe distance is better so yeah weight or distance uh you can use either one so we have distance here right uh put this in the first one so that we can uh sort right by the distance and then we have heap pop of the product queue right and then for v and then we have the new distance okay new distance in the graph of v of u right so this is all part of the dykstra uh template so if the d plus the new d is smaller than the distance of the v right and then we uh so first we update the distance of v to this d plus nu d right and then second we push this new distance right d plus new distance actually this is the next distance right along with a v into that priority queue okay so now after this while loop after stack stroke we have the shortest distance for each of the node right and now let's do then let's check the address one by one right so what will you be uh w right in the address okay so first like i said so if the distance of u right is greater than the max moves and the distance of v is also greater than the max moves uh actually you know what so for this one uh we need to first uh count if we can reach the current node first right uh it means that if the distance of u right is within the max move right then the answer will be oh we need the answer here right be zero right so if this one is going to that right similarly right if the distance of v right smaller than the max moves right and then we do we need to do an answer plus one again so these are the like uh oh sorry i actually uh we cannot do this here because you same u and v might be this uh appear in this address multiple times right so we cannot do this uh so we have to do it uh at the very beginning here so for u and w right in edges okay basically something like this another hydrate sorry in the distance yeah this is going to be a enumerate yeah so that's why we need to remove this part here like i said we have to enumerate the distance inside of edges right so now we have uh already counted all the original node we can reach right so the next thing will be to check the uh the nodes in between each edge right so like i said the first one is like this so if this one is that we continue it means that there won't be any edges at the start there won't be any notes in between that we can reach right and then let's do a count one right and then actually i use the left and right uh while i was drawing the diagram so i actually should be there's actually there's no left and right except instead there should be a count one and count two so one equals to this gonna be a max of moves oh actually let's do this max moves minus distance of u right and then we have count 2 equals to the max minus descent of v right now like i said uh we do this right minimum of count 1 plus count two and this w right in case there's a like overlap so this one means that you know if there's overlap uh between second one and count two we do a minimum because the most the maximum we can add this as w right but here you know since this uh distance of this u could be greater than the max moment in the so which means that either con one or column two could be an active values in so to make sure it will not uh affect our final answers we should do a max of zero right so which means that if we cannot reach this uh this u here right then this count for from this side will be zero similarly for this count too okay return answer so i think that's it um yeah okay so let's run the code default okay particular okay cool so it works right uh so as you guys can see so these are like just a little bit variation of a standard uh tax room and so that's why the time complexity for this one is going to be uh same as the texture with the e times log v right so that's the adjacent the number of edges and the log of v is number of nodes which is going to be a n right so in this case yeah because that's the diagonal algorithm and here just like the two for loops right cool yeah i think that's it right i mean as you guys can see so this one well we start with the very basic texture right uh to calculate the shortest distance between uh for each nodes right between each node and zero and then with those uh shortest distance you know up for two side of each edge we will be able to find out how many uh nodes in between we can reach right and then so we just uh so first is that we when we create the graph we do a w plus one right in the end when we do uh the count in between we do a little bit of uh manipulation here just to handle that uh overlap case right um yeah i think that's it okay thank you for watching this video guys stay tuned see you guys soon bye
|
Reachable Nodes In Subdivided Graph
|
peak-index-in-a-mountain-array
|
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will **subdivide** the edge into. Note that `cnti == 0` means you will not subdivide the edge.
To **subdivide** the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti-1, xcnti]`, `[xcnti, vi]`.
In this **new graph**, you want to know how many nodes are **reachable** from the node `0`, where a node is **reachable** if the distance is `maxMoves` or less.
Given the original graph and `maxMoves`, return _the number of nodes that are **reachable** from node_ `0` _in the new graph_.
**Example 1:**
**Input:** edges = \[\[0,1,10\],\[0,2,1\],\[1,2,2\]\], maxMoves = 6, n = 3
**Output:** 13
**Explanation:** The edge subdivisions are shown in the image above.
The nodes that are reachable are highlighted in yellow.
**Example 2:**
**Input:** edges = \[\[0,1,4\],\[1,2,6\],\[0,2,8\],\[1,3,1\]\], maxMoves = 10, n = 4
**Output:** 23
**Example 3:**
**Input:** edges = \[\[1,2,4\],\[1,4,5\],\[1,3,1\],\[2,3,4\],\[3,4,5\]\], maxMoves = 17, n = 5
**Output:** 1
**Explanation:** Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.
**Constraints:**
* `0 <= edges.length <= min(n * (n - 1) / 2, 104)`
* `edges[i].length == 3`
* `0 <= ui < vi < n`
* There are **no multiple edges** in the graph.
* `0 <= cnti <= 104`
* `0 <= maxMoves <= 109`
* `1 <= n <= 3000`
| null |
Array,Binary Search
|
Easy
|
162,1185,1766
|
1,296 |
let's go to question number 1296 divide array in set of k conjecture numbers this is medium question let's get into it given an array of integer norms and a positive integer k find whether it's possible to divide this array into set of k conjecture numbers return to if is password or wise return first let's check the example one okay is this okay um okay uh today i'm gonna use the math as the counter on number e the key is the number and then value is frequency of the number so first i would like to make the count and that one is one two is one three is two four is two five is one six is one so i will iterate from here the first i will check this one is the four right one two three four is four and that this one is very the right so i will deduct one by one and then move to next this one i will check this one is zero yes this zero mean is no need to check right and then move to next here is direct so deduct zero skip everything is valid i will listen to so in this case the return to okay uh let's check the several cases first case if this one is too big like 10 11 1 in this case if we deduct one is it still remain nine right so in this case i will i would like to make the temp and then tempo is same as this one and that means i will deduct the 10 instantly so 0 1 and that number is the same as before but this makes sense so when i find finding if this one is zero that means we could not make the conjunctive number length is four so at this time uh we gonna return okay let's make it first we make the couch irish collections counter and then names import collections okay next we will iteration which one this one no it is time we need we just iteration uh number uh the key right so this time for n in so let's see in this case the dom is the digital solid so if we do that we need to solve this first and then count let me get count one by one first if not count zero count n is zero and then i will continue skip this iteration that is the this case right in this case the n is zero no need to check and then next let's make the time 10 pennies count and therefore i organize iteration range to n2 and plus k and then fourth last check if count n minus k and because i is below 1 we need to return first because that is this case right and then otherwise i will let count i minus 10 surely maybe okay awesome so okay good and then let's read okay but in this case one if this one is still ended it is a smaller than maybe we need to solve this better so after deducted this one is still in mind bigger than one zero only first that's right so in this case no it's not good ok let's choose the first cases and then the right return first okay right first and then plus k count number okay solid count okay count to number zero continue um twisting solid count don't get not one by one oh sorry that is little true okay looks good okay time complex storing is endogram iteration and so time complexities and login and that's very space complexity is linear space because we use counter hash map thank you
|
Divide Array in Sets of K Consecutive Numbers
|
kth-ancestor-of-a-tree-node
|
Given an array of integers `nums` and a positive integer `k`, check whether it is possible to divide this array into sets of `k` consecutive numbers.
Return `true` _if it is possible_. Otherwise, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,3,4,4,5,6\], k = 4
**Output:** true
**Explanation:** Array can be divided into \[1,2,3,4\] and \[3,4,5,6\].
**Example 2:**
**Input:** nums = \[3,2,1,2,3,4,3,4,5,9,10,11\], k = 3
**Output:** true
**Explanation:** Array can be divided into \[1,2,3\] , \[2,3,4\] , \[3,4,5\] and \[9,10,11\].
**Example 3:**
**Input:** nums = \[1,2,3,4\], k = 3
**Output:** false
**Explanation:** Each array should be divided in subarrays of size 3.
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `1 <= nums[i] <= 109`
**Note:** This question is the same as 846: [https://leetcode.com/problems/hand-of-straights/](https://leetcode.com/problems/hand-of-straights/)
|
The queries must be answered efficiently to avoid time limit exceeded verdict. Use sparse table (dynamic programming application) to travel the tree upwards in a fast way.
|
Binary Search,Dynamic Programming,Tree,Depth-First Search,Breadth-First Search,Design
|
Hard
| null |
1,010 |
Hello Hi Everyone Welcome To My Channel It's All The Problem Players Of Song With Total Duration Divisible By 60 Is Problem Thursday Songs Time Duration In Time And Where To Find Number Of Players At That Time Duration Tyohaar Molu 60 subscribe and subscribe the Channel U Will Start From It will start from plus one time watch turn off i plus time for a day i is cord visible light small businesses and individuals painter which will contest all subscribe solution for this problem in the time complexity subscribe and subscribe the 38.6 subscribe what will and subscribe the 38.6 subscribe what will and subscribe the 38.6 subscribe what will Ooo think you can you me one to this I'm processing this first festival what I need to look pass i.e. previously known for it's festival what I need to look pass i.e. previously known for it's festival what I need to look pass i.e. previously known for it's not slow 3230 subscribe person subscribe and will reduce the time duration of song and will count number of subscribe recording Brigade Friends Desi Boys Map And Will Update Entry 35th 400 13131 Update Number 90 Degree Of 235 Want To Talk With 6000 Mode Can Be Updated And Chief Fati Over That I Special Nodule Shy Nilbit Subscribe To Channel Indian Middle Total Number Of Share And subscribe The Amazing Subscribe Indian map happened that elections like traded songs anti in time and nor will first time at this time when meanwhile example egg check mode ko 206 Vikram subscribe 960 update plz update and liquid gas subsidy in difficult 90 16 - Team and Invalid you and judgment of six robbers 16 - Team and Invalid you and judgment of six robbers 16 - Team and Invalid you and judgment of six robbers half hour mode 600 easy and difficult me aa team and 600 easy 210 will update entry plus one middleton subscribe to a fancy this website is walking left side us loud solution this is accepted servi and subscribe from appointed side New in this may also be in the year will just cut map of 0 clear vision candy a map of this is just give the name city map will visit indiscriminately automatically 15204 hair business idea is map of team and 6 a plus sequence is this lineage safe and we can decide plus 116 tried to compile and siddhi are fancy that i have tissue walking with the reaction when can submit disco dancer ki neeti safal so isi live solution hit the like button and subscribe my channel and share fun middle aged problem like this
|
Pairs of Songs With Total Durations Divisible by 60
|
powerful-integers
|
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds.
Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`.
**Example 1:**
**Input:** time = \[30,20,150,100,40\]
**Output:** 3
**Explanation:** Three pairs have a total duration divisible by 60:
(time\[0\] = 30, time\[2\] = 150): total duration 180
(time\[1\] = 20, time\[3\] = 100): total duration 120
(time\[1\] = 20, time\[4\] = 40): total duration 60
**Example 2:**
**Input:** time = \[60,60,60\]
**Output:** 3
**Explanation:** All three pairs have a total duration of 120, which is divisible by 60.
**Constraints:**
* `1 <= time.length <= 6 * 104`
* `1 <= time[i] <= 500`
| null |
Hash Table,Math
|
Medium
| null |
889 |
Ajay Ko Hi Products Dinesh Kumar Website For Wedding Within the video, I will show you the method by generating the binary Jio SIM free and poster and Sir, you will get pre-order and poster and Sir, you will get pre-order and poster and Sir, you will get pre-order and post graduation and I will use the same to regenerate the identical to show you again. So make it very slow, how does the chooser do it even in the job? Then in this post, some children commented at the time and said that today they should solve these questions and it is possible that you can also take this as a starting point and add it. Now you can post, I know that he can be a king but I am not using yours because according to this method, people lying aside get angry, use this method in the same way, although I will explain it in the third part. After completing these questions, now it's okay, so now we are going to see the districts, we use free and post reversal, how to make it, so let's watch the video, I will give you a mix of this cream here, hands, we get this okay So I bring this free and post inside it, I was in 2018, okay here, first of all write the free mode, its please and then its post, sorry, if we talk about this, then here it is A B C D LTD. If we talk about I Ujjain ch4 photo, then here if you put DP on I Ujjain's lead and CT scan, the first thing for me is definitely mine. Now if you talk about your special thing here, then the last thing in it is travel. So all the children who have been there before the note, all of them must have been there before, so we are going to use this thing inside the solar panel, here I am the first to make the note the root, then I am the most. The first note is made in the form of Roop Note on last Sunday and you will delete it like you will after declaring the routine and sulking. What will we do now? Now let's see, it is also a water note because I am going to get the note just after the woman. My Africa lessons and because I will be zooming, which is military, I have taken full length, now we are military full bunny trick, so what will happen with this that if you get the first wave, you will get Android phone, then there will be aspects, after that, I am going to get a ride, so whatever my note. The one after Hoga will be that permanent writing and if I die after Hoga, then my writing is different, that is, whatever note has the part of electric in it and whatever note is there, if it gives me the lesson of electric, then inside this I will get the poster here too. All the notes that would have been there before that will all be Africa's partners. Why is this because what is there in post solitaire game degree? B.Ed.D.J is doubled in this way, B.Ed.D.J is doubled in this way, B.Ed.D.J is doubled in this way, whereas inside the post, first wash, then come and then go, still there is travel. It means that being a journey, all the notes have already traveled, this is the same thing, there must have been people who used it here, so before that, if I found out in which Intact I got it, then I have found the address of Intex here. I thought that whatever is the note, which is my first note, what induction will I get it on fax, as I have already received it, so I have to find out how many people are there in total from the forces till here, that is, whatever I get at the time. Have they got the starting index? How many total people are there till now? How many total elements are there? I can find out this very easily if I get this information here that the starting index of pre-order is its starting index of pre-order is its starting index of pre-order is its index for starting index and that is the poster end. If I have done events then I find out from the ID where I got it and all the notes that may have been there before that, I cut them all in Africa, scientific wash IJ's also this is my electric reports and travels Nokia and till now preorder traversal are people so many on 12345 There are five people, so I will have to find out the country in this way. How many total people? I found out the five people sleeping here and 12345. I passed these first five cloves here to the B.Ed.D. Peeth here to the B.Ed.D. Peeth here to the B.Ed.D. Peeth who will now fold it in the grinder. Hmm, okay. What are you doing to it, now simply accept the end and let us rub its form, with this I will puncture the fully developed cheese. If we will try to extract the history writing, then this will be my first curved one. The second one will be from the posters. Now all the notes after G will be there. All of them must be saying tight saptari and here also after the last one has to be left, this is the subscribe method part, inside this, make the first note a fruit note, first make a don't and the next no data, go to this in the post. Come and search wherever you find it. On the left, he was given the lesson of South Africa and also improves BDO. On the left, there has been a teacher i.e. Premchand Vishwa has given the i.e. Premchand Vishwa has given the i.e. Premchand Vishwa has given the body and the rest, whose lesson will be left. Right, everything is fine, IGL and Uday's here, as if the first note on this side was made a form of 'G', come here and search and there is nothing made a form of 'G', come here and search and there is nothing made a form of 'G', come here and search and there is nothing before 'G', that is, it is the Africa part, before 'G', that is, it is the Africa part, before 'G', that is, it is the Africa part, Jio 4G price is the Africa part, this inch. And now look, the ones made here will also be made in the form of a minute here, or they will make the other one in the form and if they go and search for Aai, then I found Aai, from here onwards, all the people from Aai till the first, all of them are part of Africa. Whatever is there after the sweets, it is a subscribe method part, so the form made here, I have made it here, I will make it here and back again, it is exactly the same Trident Country, our channel, now what is its analysis, see how it is written, whenever you want. If you want to write a request letter, then you always talk to the Intex customer in the pre-order cast always talk to the Intex customer in the pre-order cast always talk to the Intex customer in the pre-order cast and X factor, so what I am going to do here is that the index gives so much to write the request letter in such a way that now here But indexing is something else Election 2012 itself has written for us but here we will take it out like this Dear starting index comma goat's end inventors have passed me and one of mine has got that starting index of roast Roma post's index so this is They will be provided to me, with this kind of help I have to return to the estrangement. Okay, if a slap toe right Africa is causing problem, then the first note which will be here, what will be the first note for me, will be the root note i.e. Who will we make in the form? root note i.e. Who will we make in the form? root note i.e. Who will we make in the form? Made in these eyes with pre-order. Made in these eyes with pre-order. Made in these eyes with pre-order. Celebrated as the root itself. Now what problem should I do in my left-to-right ways? what problem should I do in my left-to-right ways? what problem should I do in my left-to-right ways? So what do you have to do first? Take the note with it. Go to Next9 and search inside the poster. Wherever I want to do this, I will have to find out the account before getting it, so whatever side, apart from this, like this side, such wife, and so I will have to find out that the total people before me are like so many accounts, so I will have to find out the account from this video till for If someone has to be put towards the end and if someone has to improve, then how many total people will come inside it? Will it be the total number of elements or Yo will go ITS - The starting index of the pre poster will be Yo will go ITS - The starting index of the pre poster will be Yo will go ITS - The starting index of the pre poster will be plus and the total will be Robin. Total number of elements will be I have found the account, see. Select low problem and will do for - G4 Plus Mangana or Face Total there are for - G4 Plus Mangana or Face Total there are for - G4 Plus Mangana or Face Total there are five people inside the black factory, we have electrical, we have found out the total number of element, now Adi has to write free water can, Bhaskar has arranged from which room to where. From here till here people will be in Africa part From here till people will be in Africa part 2 How to pass buffalo in Africa part-2 Africa part 2 How to pass buffalo in Africa part-2 Africa part 2 How to pass buffalo in Africa part-2 We will go in free mode on custom inch plus one till the next increase will be the starting of pre-order one till the next increase will be the starting of pre-order one till the next increase will be the starting of pre-order and total number in express Of elements and posting religion will pass post order's starting index to post ID exposure to get started to we here id one will be yours our Africa lesson and write all grease will be made here that life will become free mode of in your express Total number of elements plus from lineage to post totally free and required in this up and here we will press from id If we do, then we can re-develop this trick written in this very written article, re-develop this trick written in this very written article, re-develop this trick written in this very written article, so once I write this chord according to this relation, after that I will type on the methods and above this I have made the first video that Why is it always necessary to be a flower bunty or not, then look at the natural in some other way, whether it will be a flower bun or not, at that time the idea will arise that why it is important for us to have a successful actress here, if it is not full bunty, then what type of dress will be made, why arrangement. It is formed, let's take a look at it and see, we will find out properly, first we will break it and divide it in a good way. If the flowers are not billeted then it is simple. Now see, give 200 here at home, I have my code. I will bring the cord, I want to make a tree, I will make a puppy from here to here, Ajay has been robbed that look, here you will have to do Rinpass first, precast induction will be one, you will be the president and the post Chandra Prince will reside here, the crown of this post. Lends A nutritious repass that you are the end induction question of the post, now by searching on the depositors again and again its quantity and Mohan Roy goes, now in which channel his discuss currency goes, then I can reduce it and come. If you try to do it the smartest possible, then you will save time. Push forward, this small spoon will go white. If you want to save time, then sit and pay attention to it. You will go to tell on the gas and if you go to put it as we were, then it will always be so. Almost the balance is not working. Okay, let's come here, the first thing is that I will be my group member of duty as soon as I come. New MP3 note for those who are my first disease, we will make it loot note i.e. we will make it loot note i.e. we will make it loot note i.e. starting of pre-order. I got starting of pre-order. I got starting of pre-order. I got angry when I refused to give it with free and in the index, so I have got my first form, now I have to decide the left or right Africa of the route I have got, that is, I have to find the gift gallery and the website for soft. Have to find out and then the one linked here will be the one we are like from where we will compete and loot the money and return it on Friday by keeping off water testing on these tracks and here choice lock it increase it till velvet Hai Jhala that hotspot hydrate is not equal du prez and free water wasted plus and here the network will come see I have to run low till 4000 shooting induction I get the index inside the post order where the suicide of pre-order Note where the suicide of pre-order Note where the suicide of pre-order Note whose shoulder i.e. till whose shoulder i.e. till whose shoulder i.e. till how long do I wait until I get B here, I keep Friday here and in that area, till when I too get it, like I will also get it, I will come to know, all the notes before the middle All the articles are from the factory's text but the problem here is that if there is a little more pressure in the matter then I have an inquiry if it becomes of one lens then please contact me if I can't then I Four should be written here if the setting of the free mode makes the person get a job and Indian Tech or post a comment in the chart of the post and it gets mixed i.e. when there is a lens flare, exactly this i.e. when there is a lens flare, exactly this i.e. when there is a lens flare, exactly this officer, you do not need four from going further. Okay, so here you have to keep laughing every time, just one plus comes to Abhidha and after coming here, the first thing we have to do is to find out the total number of elements. If the total number of elements can be saved then the total number of elements is equal to two sides - in five 8. Why is Inch Plus app's portion equal to two sides - in five 8. Why is Inch Plus app's portion equal to two sides - in five 8. Why is Inch Plus app's portion starting and displacing? See, when even a businessman does the total in the fridge, how many people exit. If you want to calculate it, how did you calculate it even now? By doing A +1, then inputting the ID inside it. +1, then inputting the ID inside it. +1, then inputting the ID inside it. Portion starting is an incorrect total. How many people do this? If it is B minus plus people, then let me know the total number of elementary. Now that I have got all the information, now I have taken the thing and can also cost it. How will you post it here for free? You will pass the chart of free and plus one to the scenes of selected total number of elements for Prakash technicals, Mama side effects were on and in exactly the same way, I have set the total number of elements in a 200 free mode, if it is total number of elements, then in exactly the same way, we Here you can select the second one, how the first one for the math subject will become the starting index of our post order plus the total number of elements total number of in this, please send the form of post free and tha n x 480 x plus one to a Heart and Enzyme Index - and Yoga on our a Heart and Enzyme Index - and Yoga on our a Heart and Enzyme Index - and Yoga on our platform and done the route from here. It is okay if it ever happens that after washing the post, you cannot increase and add the starting index free mode's setting minutes, then we fill your face with returns. This is your no will send sugar screen every time, now let's see how the unit is going to be free 200 I should call the institutions and get these chemicals 228 A return to Ajay and here we will talk ok Maji Roma and minus one post from 80 ML - - - NDA has happened, you should drink cold drink, it means that it is MP3, then try it once again, let's see the status report of A. So we are passing now, let's see that it is necessary for it to have full battery, that it is middling. If the flower bunny is not right then you will face problems. Let's move our eyes back towards our court and we will pick it up from here to reach the consciousness that we should see only one such thing which is a flower bunny. It was not a woman, I have it here that K B C D E F G. Okay, if I talk about its opposite and then free mode will come out, its ABCD is the back and if you talk about its post then you will get DCB. Chief is fine, so first of all, what did I make of the note that did not appear? Inside it, first of all was not appeared in the starting index. You made it your fruit, then I searched for Predestination Plus One. After starting the ID scanner, write in the index that If you go to Bigg Boss and get subscribed, if you search then which edition will you get? ID time, post, I started from get started, I started from zero, I got plus by becoming plus, I got above military, that is, when my ID is active here and is free. Gayi total number of elements, how much will it be free - hero plus free - hero plus free - hero plus unicode-to-chanakya, four people including absolutely unicode-to-chanakya, four people including absolutely unicode-to-chanakya, four people including absolutely use it, but you are not electric, this lights is part of Africa, but - how did you lights is part of Africa, but - how did you lights is part of Africa, but - how did you fill it this day, Africa that I am not able to disturb I am sure that it may seem that I can go right and there was someone important here myself, what did I pass in the left, all the people who will be there before the middle, they will be in the lesson of Electric only, Kids Pet and here, what will pass in BCD and ice cream, Report Saptari. There is nothing inside from the pre-order Saptari. There is nothing inside from the pre-order Saptari. There is nothing inside from the pre-order Satanic Plus One, you have passed here, from the punch inside the beneficial to the setting of hands free mode, a soldier, there is a total number of elements from zero, I have a poll, even Bhaskar forgive the daily life. And passed us home and sorry the phone and with the poster we passed that here from 80 to the head here we passed okay and in person we will pass from five to hand in because it is and power will pass hydrate Plus one i.e. power will pass hydrate Plus one i.e. power will pass hydrate Plus one i.e. where it was found from for to is next - is where it was found from for to is next - is where it was found from for to is next - is next is office so not both of both like subscribe drishti does not do chakli what is it that I rights activist does in this luxurious does not do because of which what will happen because of which Also Arrangement Mahal will be good, it will be made better, inch white, so here it came, as soon as it came here, it was made in the form of a note and again in it C Vaseline and went and searched for it, found it will say CT and here DC Africa 5 Big Guide 360 does not and here DC Africa 5 Big Guide 360 does not and here DC Africa 5 Big Guide 360 does not do this, here we will make Shivalinga and will put it in the form, we will search here, we will search for the ones here, that is, the battery which you make for free is made in such a way that if you whistle, then this one was a tree, eat it, then this one is a tree and This one which is completely different from the other, so at this time the arrangement is our own screen, if we have created ourselves inside this other arrangement, then the rear has become but some other person has become it is said that when by using free and password traversal If you make chakli, you can also get arrangement. It is not necessary for you to have iodine milk. If you want to share it so that you always get entry, for this it is necessary that your tree should be made of flowers, that is, its left note will get first, dendrite note should come. Left No Deduction Under Right More Raja This can't happen Left No Dendrite But this pattern is following inside the whole no matter how the battery bus is swollen Decisions and whatever pattern the floor is Chiplun and Hai Chalega And Right Notes Loot After Right Mode off will work, only flight mode, this will not work, that is, this method or this cream will work, this method will work, take this remix, it is also not possible to do suicide note, it is necessary to have left note before this, if this will not work, then all these directions came out again. If you can maintain the distance, then the pattern that I was following was free in this post here, my dear friends, if you use the same pattern in all the centers, then the reason for doing this pattern, dear ones, was that I wanted to use the same pattern in the bacteria question center. Now After this, there is a text, inside this we make a back entry using these water level reversals, so I want us to use the same pattern inside that also because that question can also be solved by using the button. So here, when that child commented on YouTube, this question can be said in Chinese also, he was satirizing himself by taking youth, so that question is fine, straight will be fine or he should have brought space there. But neither is that straight, it is going to harm us, we have to search almost in the university also, but if we small it on gas, then only after small this space, it can be ruled out for using pet. That can happen only later, then every question of mine will have a different dirty pattern, so I wanted the answer to each question to be a single pattern. Free in this, every post in the same ref is abe flu nodal and importance of migratory Maggi also pattern. That's why I followed this pattern that Satya Dharma Powder means True After Questions pattern should always remain as SIM so that there is no need to keep it in SIM. If you understand one thing then you can apply it to any new question. This is the reason for doing this pattern, so the voice has to understand in which way its loved ones are by using pre and post reversal and here also the notes can be searched here so it is said that they will Note because it will always be found last even inside the post, if I get the note for free today, then all the notes found 20 cm earlier will be Puck Violets Africa meaning, then the bottom Noda Ne also has all the notes before and I. But if the author is installed, then cook one way, then before the middle, all the road offices, 103rd, how many notes were there, the same number of notes will remain in the text of love satori, inside the free, so I have also come to know who is Lahari, side sir creek and there is When I came to know that Jaipur is Rajasthan method then I could state its trick very easily. So if you liked the video then do not forget to like this video and also if you are on the channel for the first time then subscribe to the channel. I will die without you, see you in the next video Ajay
|
Construct Binary Tree from Preorder and Postorder Traversal
|
buddy-strings
|
Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_.
If there exist multiple answers, you can **return any** of them.
**Example 1:**
**Input:** preorder = \[1,2,4,5,3,6,7\], postorder = \[4,5,2,6,7,3,1\]
**Output:** \[1,2,3,4,5,6,7\]
**Example 2:**
**Input:** preorder = \[1\], postorder = \[1\]
**Output:** \[1\]
**Constraints:**
* `1 <= preorder.length <= 30`
* `1 <= preorder[i] <= preorder.length`
* All the values of `preorder` are **unique**.
* `postorder.length == preorder.length`
* `1 <= postorder[i] <= postorder.length`
* All the values of `postorder` are **unique**.
* It is guaranteed that `preorder` and `postorder` are the preorder traversal and postorder traversal of the same binary tree.
| null |
Hash Table,String
|
Easy
|
1777,1915
|
1,881 |
hello friends welcome to coding interviews channel hope you are doing great if you haven't subscribed to my channel yet please go ahead and subscribe i have created bunch of playlists to cover various categories of problems such as bfs dfs stacks cues dynamic programming and so on please check them out i have uploaded the code for this problem to the github repository you can get the link from description below this video let's jump into today's problem maximum value after insertion you are given a very large integer and represented as a string and an integer digit x the digit in n and digit x are in the inclusive range 1 to 9 and may represent a negative number so the inputs are 2 n and x n is in the string format and it's a very large integer but it is given in a string format x is a single digit basically and all the digits in the number and x are in the range of one and nine so and the number could be that means n could be a negative number also right so and now you want to maximize nc numerical value by inserting x anywhere in the decimal representation of m you cannot invert x to the left of negative sign so that actually makes sense right so if you insert into the neg left of the negative sign it cannot be called as number so you have to insert between the digits it could be after the negative sign also right so that means that's what it is and we are supposed to return a string representing the maximum value of n after we increase so that's the problem statement right so let's take a couple of examples and try to understand what it is actually so if number is a positive number as we know there are two different kind of numbers right so the number may represent a negative number and it could be positive numbers so let's look at the positive keys first so if the number n is 73 as given as string as it said right and represented as a string and x is equal to six this is a single digit right so if that is the case right so how many places the six could be inserted right so i have a little formula here if the number is positive right and we are calling length of n is l then we have l plus one number of positions that we can insert in right the x right so if the number is up length two digits then you can have three insert input in fitting positions so six can be inserted at the first position and before seven and six can be inserted after seven six conventional after three so that means three positions so likewise these are the outputs but out of all these three things right what is the maximum that we need to give because we are supposed to write the maximum value right so 763 is the maximum right similarly so let's take another example three four six two and if you insert five these are the five examples and the maximum value is the first one and if x is equal to one for the same thing for 3 460 if x is equal to 1 if you insert 3 461 is a maximum right so that's how uh the numbers that we have to come up with but from these numbers right let's identify a little logic right so when we what is the actual position that we will be inserting x is the question right so that's what it is so the logic is find first number c such that x is greater than c right so this is a logic find first number c such that x is greater than c what is c is representing each digit in the number n right so find the first number c such that x is greater than c so let's apply this logic and see where we are going to insert right so six right x is six so six should be greater than the number c so is 6 greater than 7 no is 6 greater than 3 yes so this is where that means in the position of 3 we need to insert so after 7 units if enters insert 6 that will be our number 763 so that's what the answer is right so this is essentially the logic that we need to implement let's see for another thing so x is equal to 1 this will be an interesting case right so here what happens is let's copy this number because we are trying to get that number basically right so this is what so find c such that x is greater than c so 1 is 1 greater than 3 no is 1 is greater than 4 no it was 1 greater than 6 no is 1 greater than 2 no so we have exhausted all the numbers right so in that case where you are going to append x obviously at the end of the entire number so that's what we are printing we got 3 4 6 2 1 obviously that will be the maximum number after insertion so that's how and that's a special case everything else is fine so there are two cases one is x is greater than c right so you will be inserting that the replacement index but otherwise you will insert at the end so this is for positive case positive numbers but what if the number is negative so if the number is negative the zeroth index in n will have a negative sign right so we will just look at the same example number is negative 73 so that means zero with index will have a negative sign and that means we will have the digits starting from index number one so in this case how many positions that we can really insert right so if the number is negative i have another formula here so what we are essentially doing is the length of n we are calculating that and subtracting 1 from it why because we cannot insert before negative number and negative sign so all we can insert is these two right before 7 after 7 and after 3 that's it so that's why we will say okay this is what it is length of n minus 1 is a 1 so obviously l plus 1 so whatever the length that you calculate so when the negative when the number is negative you are removing the sign and minus one for the sign but if it is positive just take that whole length and add a one that's it so that's what it is going to right so minus 73 as we said six could be inserted before seven that's six minus six seventy three six could be inserted after seven minus seven six three six could be inserted after three minus seven thirty six so out of all these right what is the maximum number which is minus 673 right so that's what the answer that we need again let's look at another example minus 55 x is equal to 2 so if it as simple as this right so you could insert 2 before five after five and after the second five so if you insert like that right so these are the three numbers that we will be generating and out of all this what is the maximum number negative to 55 this is what we want to return so if we closely observe right what we are essentially doing is we are trying to find first number c such that x is less than c 2 is less than 6 c is each digit in the number m so that's what it is so essentially we are going to implement these two logics for uh positive and negative numbers respectively let's go and look at the code in order to understand it in a better fashion right so and first thing is we are going to assume the input is valid that means there are no negative signs and there are no multiple negative signs and there are no decimal points all that stuff so we are assuming the input is valid otherwise what we will write is a validate input kind of method so which will validate for all that stuff right but in this case we are just blindly assuming that input is valid right and i'm declaring a local variable a replacement index as negative one so first case i'm going to tackle the negative numbers right and for i in the range of one to length of n right while we're going starting from 1 because 0 with index in a negative number is minus sign right that's why we are starting from index 1 okay we are just putting this in a little variable here right and if x is less than order of c minus our gloves is already of zero so why i'm doing this is because the representation of n is a string i want to really get the value of the particular uh character particular index right so that's why i'm doing order of c minus r naught of zero so this will give me the actual value actual digit so i am comparing the x is less than that digit or not if it is so then we got the repetition index and you just break down from there all we need is just first replacement we know where we want to replace competition but in the case of a positive number right all we go we're going to change is the logic in the for loop so we are going from 0 to length len of n so 0 is optional so that's why we are going len of n in the positive case we will be starting from index 1 but in the negative case we will be starting from index 0 so that's the change here and the other change is if x is greater than c that's what we said right if x is greater than c we found the uh replacement index and then break out so as and when actually this repetition index is not necessary we can take it up because we have already declared good and if repetition index is equal to minus 1 that means we have not found so if you recall this is the case 3 4 6 2 right that's the case 3 4 6 2 that means we are supposed to insert the x at the end of it right that's what we are doing we are inserting x at the end of it and returning otherwise what we are doing is we are splitting so we are going to get the first part until repetition index and put x in between and put the rest of the stuff from the n that will be the result right so just to recap right so the basic thing is as long as your x is less than c you skip those numbers right as long as x is less than c you skip the numbers so x is x 6 is less than 7 right skip it but 6 is less than 3 no that is where unity is that is the simple logic here i wrote it in a different way basically you are trying to find the first number such c such that x is greater than c so that's how it is and for the negative numbers it's quite opposite of it right so that's the crux of the algorithm and let's go ahead and look at the time and space complexity right time complexity we are saying time complexity the total time that we are running here is in this particular case we are going to exhaust the partic uh the given number right so that means length of n so we will be going through the length of how many our characters that are given in the end we will be exhausting them so that's why time complexity is order of length of m and what is the space complexity are we really using any space here yes we are using index and are we using any other space we are not explicitly using the space here we did not look there but we are using it to return this not this basically right because this will create a new string when you offends uh when you join two strings so for that purpose we need to account the space right so what we are doing is length of n is length and we have one character right so length of n plus one but when we actually give the bigger notation right we will knock off once that's why we are saying the total space complexity is order of length of n that's it that is as simple as that so time complexity is out of length of n and space complex it is also order of n so uh you understood the problem if you have any further questions please post them in the comment section below this video i will get back to you as soon as i can i posted the code uh on the github repository you can find the link in the description below this video if you haven't subscribed to the channel please go ahead and subscribe and share among your friends please click on the bell icon so that you will be notified about my future videos thank you for watching i will be back with another problem soon till then stay safe and goodbye thank you
|
Maximum Value after Insertion
|
closest-subsequence-sum
|
You are given a very large integer `n`, represented as a string, and an integer digit `x`. The digits in `n` and the digit `x` are in the **inclusive** range `[1, 9]`, and `n` may represent a **negative** number.
You want to **maximize** `n`**'s numerical value** by inserting `x` anywhere in the decimal representation of `n`. You **cannot** insert `x` to the left of the negative sign.
* For example, if `n = 73` and `x = 6`, it would be best to insert it between `7` and `3`, making `n = 763`.
* If `n = -55` and `x = 2`, it would be best to insert it before the first `5`, making `n = -255`.
Return _a string representing the **maximum** value of_ `n`_ after the insertion_.
**Example 1:**
**Input:** n = "99 ", x = 9
**Output:** "999 "
**Explanation:** The result is the same regardless of where you insert 9.
**Example 2:**
**Input:** n = "-13 ", x = 2
**Output:** "-123 "
**Explanation:** You can make n one of {-213, -123, -132}, and the largest of those three is -123.
**Constraints:**
* `1 <= n.length <= 105`
* `1 <= x <= 9`
* The digits in `n` are in the range `[1, 9]`.
* `n` is a valid representation of an integer.
* In the case of a negative `n`, it will begin with `'-'`.
|
The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary search to get the nearest possible value to goal - x in the first part.
|
Array,Two Pointers,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
|
2108,2162
|
1 |
hello everyone in this video we're going to see the solution for the leak code problem to some so basically we're given an error of integers and we have to return the indices of the two numbers that add up to a specific target for example given this integer array and the target is 9 you can see that 2 & 7 add target is 9 you can see that 2 & 7 add target is 9 you can see that 2 & 7 add up to 9 & 2 & 7 are at indices 0 up to 9 & 2 & 7 are at indices 0 up to 9 & 2 & 7 are at indices 0 & 1 so the answer to be determined is 0 & 1 so the answer to be determined is 0 & 1 so the answer to be determined is 0 & 1 so we can do it in using we can do & 1 so we can do it in using we can do & 1 so we can do it in using we can do it using brute force but it will take over n square time which won't be official so we're going to do this in a very efficient way using hash map so let's first create the integer array in which we're going to show the dices and then the map so let's name the map as map itself it's quite a new hash map integer coma oh it's not needed yeah so what you're going to do is we're going to take all the values from the array given which is numb so numb start and I plus and the first thing that we're going to do is we're going to see that whether we have already gotten the other part in the map so what is the other part other word is target - numb other part other word is target - numb other part other word is target - numb so I so for each numb so Phi for each value in the rhythms we're checking whether we've gotten the compliment of it in the map already so we'll check that if Matt thought contains key a depart so if nap already has at the part then we have already got not answer because each input has exactly one solution so in that case what we do is simply say B of 0 is equal to nap dot get other part the index of other part and B of 1 is equal to a correcting current index I then break so if you find such a value in our map such that the current value in that add up to be the target then we got no answer else we put in the current we add the current element in the map it's a map that put numb so if I gamma I and then return our answer B so basically what we did was we made a map for integers and we're adding the values from array nums into the map and at any point if we found a value in map so that the gain value and that add up to be a target we showed those indices in B of 0 and B of 1 so let's try to see if the spokes okay yeah so as you can see the rent time is 1 Ms for sure the ninety nine point eight nine percent because we did it in a very efficient rate and did I do using only one loop in OFN time
|
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
|
141 |
hello everyone in this video we're going to be going through lead code problem 141 which is linked list cycle this problem States given head the head of a linked list determine if the link list has a cycle in it now there's a cycle in a link list if there is some node in the list that can be reached Again by continuously following the next pointer internally POS is used to denote the index of the node that Tail's next pointer is connected to note that pause is not passed as a parameter return true if there is a cycle in the link list otherwise return false all right what is this saying basically we're going to pass in a list node 3 2 04 in position one so index zero index one and they drew a little arrow here meaning that -4 is next value is two and meaning that -4 is next value is two and meaning that -4 is next value is two and so this is a cycle in example two same thing one and two position zero uh goes back to the one in the third example position is negative one which there isn't a negative 1 position so the output is false all right now as a follow-up false all right now as a follow-up false all right now as a follow-up fun uh addition to this problem is Can You Solve IT using o of one constant memory so this means we can't create any new data structures like a hash set or an array list so we have to do it using the existing uh data structures okay so how are we going to do this well we're going to do we're going to have two pointers so we got the tortoise and the hair here so we're going to start them at position zero now we're going to move the tortoise one position and we're going to move the I'm going to call it a rabbit the rabbit two positions so the rabbit's going to be faster than the turtle so the next time we move the turtle one position the rabbit is going to go back to its original position if this is in fact a cycle then the turtle moves to this position and the rabbit moves two more positions the rabbit is back here and then finally when the turtle moves one more position the rabbit moves back to the original position and meets up with the turtle so this um closes out the cycle so once around takes four turns for a turtle and two turns for a rabbit but after four turns the rabbit meets up with the hair all right so we pass in the list node and we want to return true or false so if the list node or the head is null just return false so we're going to Define instead of tortoise and hair I'm going to use slow and fast so we're going to define a list node called slow and make that equal to the head which it'll end up being the first value in the Headless node and then we'll have a fast which will be the head next so I know I have the tauris and the hair start at the same position but uh for what we're doing here we're going to make sure slow is not equal to fast we can't have these equal each other in the beginning U and so basically we're going to go through a while loop until slow equals fast and if it never does then we return false otherwise we turn true so if fast equals null or fast. next equals null then we return false meaning that because the fast is going to get to the end before slow is and if fast doesn't have a next um then it's not a cycle and we can return false if that check does pass then we're going to sign slow equal to next and fast equal to next so the fast moves twice as fast as the slow and that's going to conclude the wild Loop so if eventually if slow equals fast then we're just going to return true and that ends the method so let's debug this and see what we get all right so I use that first example 3 2 04 and the position of one all right so let's see here okay so the head is not null so we're going to sign slow equal to head and fast equal to head next so slow is equal to three which is the first number and fast is equal to two which is the second number so slow is not equal to fast is not Al now slow becomes slow. next so slow becomes the two moves one space with the fast becomes where is it fast will become the ne4 so it moves two spaces slow is not equal to fast and Fast is not null and fast next is not null okay so slow becomes slow. next so slow becomes the zero so it just moves one now look at this here fast becomes um also becomes zero because it moved two positions keep in mind so ne4 it was here and one two but it's saying that the position is one so this is actually position one and so fast does move two spaces but it starts at position two so one two and ends at zero and so now they are the same and we can return true which is the result all right let's run this through leite code and is successful see down here the input and then this is the POS variable which is never passed in the solution that we built and submit 100% love it less than 25% so a submit 100% love it less than 25% so a submit 100% love it less than 25% so a little bit heavy on the memory but we'll take it all right the last thing we'll do is the space and time complexity so time complexity is O of one we have one wild Loop so if you increase um the list node size then it's going to take more time to go through that while loop but we did satisfy the O of one we use two existing nodes and we don't create any other data structure so that is O of one and that is it so thank you for watching and leave comments if you have questions or concerns and we'll see you next time
|
Linked List Cycle
|
linked-list-cycle
|
Given `head`, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**.
Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** true
**Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** false
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
142,202
|
289 |
um hello so today we are going to solve this problem called game of life um it's part of lit code daily challenge uh so it's called april challenge so the problem is basically um about the game of life which the kind of the rules are described here so we have m by n grid of cells each cell has an initial state which is either life or dead life is marked by the value one and that is marked by zero and each cell interacts with its neighbors and we have eight neighbors we have the neighbors horizontally so left and right vertically so up and down and then diagonally all four sides of the diagonal so the rules are of the game are that any life cell um with fewer than two live neighbors dies so basically we look at the state if it's equal to one which is live and we count its eight neighbors if it has um less than two live neighbors so less than two neighbors of value one that it dies which means we set its value to zero um the second rule is that if your set is live and two or three of its um of its live neighbors uh and two or three of its neighbors are alive have value one then the cell lives so we keep its value at one uh the third one is any life cell with more than three live neighbors dies so if we have a cell that is live and we count its life neighbors and they are more than three then we set its value to zero the last rule is that for a dead cell which is a sum that has value zero if it has exactly three live neighbors then it becomes a live cell so we set its value to one we change it from zero to one so those are the rows the main thing here to pay attention to is that the next state is created by applying these rules simultaneously so at the same time which means that once we have we don't take into account the update of the updated value we only take into account the initial value which makes uh solving this problem in place trickier because all of it simultaneously so all of the changes are done at the same time um birth and deaths occur simultaneously and the goal here is giving an initial state for a board we want to return the next state after applying all these rows simultaneously um so that's the problem um now let's take a look at uh one way to solve it is definitely like with extra memory um that would be uh pretty straightforward so we have a new board and then we apply these rules um and get a new board and then reassign it reassign the old board to the new one um so that would be using extra space another way to do it is just to have two arrays one for live cells and one for life for cells that changed from dead to life um and one for cells that changed from life to dead and we started in these two arrays and then we do another um two for loops uh to change their values in the board in place right um and so yeah let's look at that simple solution first and then we can take a look at a more um advanced solution that for example uh that does what's being asked here in the follow up which is to solve it in place um okay so let's take a look at that solution i'll just like show it here because it's a it's pretty simple solution um so let's see uh so that's solution we just apply the rules right um we so we initialize the size and then we have to erase one for live cells and one for that cells and then we loop through the board we count the live neighbors for each for the current cell we'll take a look at this function later um but it's a pretty generic function that gives us the neighbors of a sub um now we have the cell and we apply the rules if the value is equal to one and so that basically we apply these rows here which says that um any life cell with fewer than two neighbors dies so that's what we are doing here and so we add it to the dead list of um of cells um any live cell with two or three live neighbors lives so here the value doesn't change so we don't need to do anything now any live cell with more than three live neighbors dies so we need to add it to the dead list so we check so that's what we are doing here um and then if uh now for the dead cells so if any dead cell has exactly three live neighbors which is what we are doing here then it lives so we need to change its value to a lip so we add it to a live list of um of cells right um so now we have the things that i need to change so we can just iterate on this one and that's what we are doing here um so iterate on the date values that cells and we assign it to them zero and for the ones that change it from that to life we ascend that values to one and everything else we keep it the same so this uh because we don't change the part here um nothing gets impacted and all of the changes happen simultaneously which is what's been asked for us now let's take a look at the neighbors function so we need to look at neighbors horizontally vertically and diagonally and this is what it does it so eight neighbors we have eight changes and the way i'm doing it here is this is just to add to the current position to get the neighbor value so to go left to the right we need to add one to the uh to j value um and we need to keep the row value um the same uh and similar thing for going left um and you can yeah that's the same that we are doing here we just have the in the values for what we need to add to x and y uh to get the neighbor and then we loop through it um we get the new indices for the neighbor and we check that it's valid index that's what we are doing here that the row is within the bounds of the rows um and the same four column and then if only if it's like that we counted and then at the end would attend the count so pretty straightforward actually there are different ways to do the computation for neighbors um you can do a range from let's say one minus one to one for both uh di and dj instead of doing this um but yeah all of them work um okay so now in terms of time complexity so we know that this for loop here is of rows by columns um we have at most if everything was transitioned from being live to dead then we will have at most of rows by columns which is the number of cells same thing here so you can see that overall um this here is at most eight right so it's of eight so that's really just eight multiplied by this and that's fine that still arose by columns and so overall it's of rows by columns time complexity in terms of space um it's also similar of rows by columns because live and dead will have at most rows by columns so we can also say this is just n by m and same thing for space complexity um yeah so this is the solution that just um does a simulation um andrew uses extra space uh next we'll take a look at some other solutions and that don't use extra space in modify in place um okay so how can we solve this problem so the main idea here is that we want to change cells that became that moved from life to dead and cells that moved from that to life we want to change them in place without impacting other cells right because we are moving everything simultaneously we want for every cell to use the previous state live and dead states of um of the other cells the other neighboring cells so what we are going to do is we are going to choose new values that mark these two states that marks some that was alive and moved to dead some of that was dead and moved to life because what we want is that for these cells basically for cells that we're alive and are dead now we want to consider them life for the cells they are neighbors of right because we want their original states and for cells that used to move to dead to life we don't want to consider them life right we want to keep them as dead okay so what we are going to do is mark with new numbers mark this difference right so some that used were live and became dead according to the rules we are going to mark these with the value three and such that were dead and became live we are going to mark them with two with these two numbers you can choose any numbers you want um you'll just have to later in a second pass um to put the right values zero or one um you would have to check this so those that were at the in the second pass those that were that had value too um we will assign value because three left to that so zero and those though are two because they are live and i will assign one in the second pass okay so this is the main idea here so let's run here on an example so what i'll say is zero right so the rules that we have is that um a cell that has um let's pick it some that will change like this one so it's a sum that has neighbors so it's neighbors that are live we have this one so basically its life count is two here um and it has this one so these are all neighbors that are alive so three and we know that a dead cell that has um three live neighbors should become life according to the uh fourth role so we know that this sum needs to become life so um what is this 0 1 2 3 so basically cell 0 1 was dead and became life so it's this so we are going to assign to it the value um back to life which is two so it's going to be two and then let's take another example maybe let's say take this one because this one will change as well okay so this one has how many live neighbors so it has one two three live neighbors right and it was dead and so it will become life so this one also will have the value too the same thing now let's take another maybe example for a sub that was live and turn it dead um yeah this one so that one has um how many live so it has this one live and then has this one two we don't we count it as dead so we count the value to us dead in the other state so this one is 2 so basically let me write this roll down so with this we count two as dead because initially it was dead and we count three because three represents life to death we count three as like because the initial state is life right and so for two it's dead so we don't count it and so one has only uh one live neighbor right so this one has only one life neighbor which is this one and so its life count is equal to one and so this is a life cell with less than two live neighbors so it needs to die right so according to the rules so we are going to so this one moves over from uh one to zero sorry not to zero two because it was live and became dead we assigned three and we do this for each one of them and with this way basically what this allows us to do is for cells that were that are now alive we are not going to count them because we are going to count value 2 as dead and so the for each state for each cell the neighbor count will not be impacted by the changes in place to the board so that's the main idea here so this is the first step would be to do this the next step would be to just go over the entire board and values that are three move them to zero because they are dead at the end and then values that are set at two set them at one so this is the main idea essentially uh pretty straight forward once you utilize it and i think this is a pattern also with matrices where um you modify the birth in a way that doesn't affect your logic in place and then you can do another pass to put it in the desired final state um yeah so let's put this up and see if the best test cases um okay so now how can we change our solution that we had earlier to take into account this new change here um our goal is to not use this extra space uh and we want to mark those that were alive and turn to dead with three and mark those that were dead and turn to live with two right so let's get rid of these arrays and so here we wanna sell um this cell here needs to be dead right we're adding it to that so we are going to sorry uh we are going to just turn it in two since it was um live entering today we want to assign three there right so we assign three to it get rid of this append here those this one was dead and it's turning live right because the cell was zero and life count is three um and so we need to assign it the value one the value two right um and this here sub that was live uh but its neighbor's life count is less than two or bigger than three that submits should be dead and so we assign it to three right um the other change is we are no longer doing this we're going to do something different which is uh we'll go do that right now so for i in range so i'm just going to go through the cells and those that are set to three since they became dead we are going to set them to zero and those that are set to two are going to set them to one and so that would be rows here and then a smaller thing with columns and then we are going to do a board at i j so if the value was equal to three then we need to set zero because the cell became dead so this would be 0 otherwise if it was equal to 2 then it needs to become live so we need to set it to 1. and that's pretty much it another thing is for the count here we should not forget that we should take into account those that are set to 1 and those that are set to 3 because 3 in the initial state was live right and so this would be n13 instead of just one um and that's pretty much the only change that we need to make now we are not using any extra space we are modifying in the board so let's run it okay so this is an indentation problem okay so it looks like we didn't change one of them so okay this is jay sorry um okay cool so that passes uh okay so that passes test cases um another thing we can do here is um instead of doing this one and three this is just a simple change we know that one modulo two is equal to one and three modulo two is also equal to one right uh well and we know that two modulo two is 0 and 0 modulo 2 is 0. so basically for 1 and 3 it's the one that the modulo 2 is equal to 1. so here instead of doing this we can change this to modulo 2 equal to 1 or in python since 1 is true and 0 is false it's considered false we can just do this so that's a small change we can do there um okay so this in terms of time complexity this solution here is um of n by m here plus of n by m so number of rows number of columns being uh m um and this is constant we are doing at most eighth iteration so overall the logic here is of an m um so that's the time complexity we have um this is one is the number of rows the other is the number of columns um and in terms of space complexity here we are not using really any extra space um so yeah we are doing it in place and so this is op1 space um so a lot better than the previous solution um yeah so that's pretty much it for this problem thanks for watching and see you on the next one bye
|
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
|
635 |
hey everybody this is Larry this is January 24th of 2023 it is me doing an extra question so let's get to it oh nope any difficulty is fine as long as I haven't done it before and today's problem is 6 35 a premium problem for design log storage system hit the like button hit the Subscribe button join me on Discord uh let me know what you think about this problem and so forth uh okay so you're giving locks it has some format okay what do we want to do we have to support at least two API uh stores the log ID time step okay and then retrieve is to start and then granularly what does that mean how precise the range should be huh oh I don't know that I understand this problem for granularity why don't you just give me the thing um but it seems like we can probably store this thing in like a binary tree type thing and then just binary search that's probably how I would do it's kind of a little bit of an awkward thing because usually um if you have like in real life in real scalable things um you do know that locks generally come in at the same time and obviously there's actually a lot of new ones with respect to kind of you know on-prem respect to kind of you know on-prem respect to kind of you know on-prem machine and emerging and so forth but in general you put you aggregate them on like the same day or someone like that right so uh and then you know uh use some like big data type thing in Apache either aged uh what's it called uh Hadoop or something like that and then you know one uh Hive queries on them if you will or maybe uh you know one of those fancy uh map reduce ee language uh type on top right something like that but um what I'm saying is that you're probably not going to do what you're doing here but you know uh that's just a little bit I still don't really understand what does granularity means foreign s I guess what they're trying to say is that you can ignore the things but that's just like if you're gonna do that you could make it make that as part of the system or like the query right like you just retrieve type of I don't know that's just so weird right but either way that's not that you know uh it's just very silly if you ask me but yeah let's start doing that so here um you know in Python we don't really have a binary search tree type thing or at least not that I know of but we do know of one that I should be using let me know in the comments but what I'm setting up for is that I am going to use um sorted list and yeah and then put what are we supposed to ID do we use ID again now we do retrieve the ID okay I mean that's not that bad but uh yeah um I'm trying to think how do I want to store this but I think storing this just like as timestamp and because we have leading zeros and it's exactly so padded right uh I think this should be fine I could be wrong but I'm retrieving it uh it's just gonna be a little bit silly um I still don't know why they kind of stood like that because in a real thing you just instead of using granularity you just embedded in the story and that's probably what we're going to end up doing is so yeah so okay um this is very awkward but I wonder if you can do it in the new as well I mean I kind of did it said yeah almost 500 could means that we can actually just do 500 squares so maybe I kind of prematurely optimize so let's just um let's just make this a list and then if we have to change then we have to change right so yeah and then here let's just say two so we turn answer and then foreign so basically I'm just going to change the string to basically what we set though it cannot spell it quite right that's basically what you want is just like I'm still looking at kind of this thing it's kind of really weird okay I mean it's fine it's just very weird right um yeah okay fine and it may be a true thing basically what I want to do is like increment or something like this uh t for time achieve for Granary and then maybe like an increment um so that uh when we get the N it will be inclusive and stuff like that um basically if G is equal to um what can GB again is one of these things it is just really annoying okay so then t we can regex this out or maybe just spread it out uh how did I do this again actually how you spit with or t dots but I think that's the that's why I was getting confused and then you have year month day hour uh minutes and then seconds right maybe just one something like this right I don't like kind of what is it between awkward way and then we map that to int of course and then if G is equal to I mean I don't we could probably do this in a slightly smarter way but I don't know I think I don't know if it's worth doing it in a slightly smarter way yeah okay then um yeah okay Dan okay maybe okay so maybe I can do it in a slightly smarter way than I was just thinking about that so in X is you go to do um of uh index of G and then maybe we actually map this into uh a day part or something like this day puts date puts time stamp Parts I don't know too late and then here then if we do increment then date parts of index increment by one and then for I in range of index plus one and we go all the way to length of day parts plus no not plus one and then take part of I is equal to zero because basically we zero our everything after that and then we just return um I guess date year will always be four so then something like join um how'd I do padding that's what I actually should know python zero pad because I think there's a thing with uh oh n Dot is that true zero film so basically um X dots you fill of 2 for X in Day part or something like this right all right let's just print start and end just to kind of see if this is uh let's actually get everything right uh and then see if that actually matches what we expect um map has no land what am I going oh uh okay fine I always forget that one or like you know abdominal Rusty thingy I don't see if it was a thing oh because now there's a number uh okay so let's see what are the queries this one we have 206 2008 okay I think that's fine I think the 12th is a little the zero is a little bit odd because foreign something or something like that um okay so I guess it goes to zero so that's fine and then our we have the hour um is that right I'm trying to think whether like in commanding it will be wrong but maybe not because it just fills everything in between so maybe that should be okay but uh let's see I won't be surprised if there's a slightly inaccurate but I am not about this problem so uh yeah for X in sub dot away uh if uh it's X which one is a tuple this is not a H it's exit upper what do I append on here oh I do append topos in here um so this is actually a timestamp and then ID so here and then I okay yeah it looks okay for the one test case that they give us so let's get a wrong answer okay there we go um all right so what are we doing um I see because the seconds we don't have the increment that's why and I think this should have been this that's why all right because we incremented it so that shouldn't be matching anyway whoops okay so that's good um yeah I mean this is going to be linear time and this is a constant time um I didn't really you can do this in binary search but it'd still be in the worst case linear which is why I changed because you can always just get the entire um you know return order locks with every query um so the search could be a little bit optimized but it's not you know that's why I mean I kind of want to also get it right because I don't know if I was reading this poem correctly because of just granularity stuff so yeah um cool that's all I have for today so let me know for this uh thing so let me know um foreign yeah let me know what you think stay good stay healthy took my mental health we'll do the actual daily problem afterwards I think we have like a minute or two left so yeah see you later and take care bye
|
Design Log Storage System
|
design-log-storage-system
|
You are given several logs, where each log contains a unique ID and timestamp. Timestamp is a string that has the following format: `Year:Month:Day:Hour:Minute:Second`, for example, `2017:01:01:23:59:59`. All domains are zero-padded decimal numbers.
Implement the `LogSystem` class:
* `LogSystem()` Initializes the `LogSystem` object.
* `void put(int id, string timestamp)` Stores the given log `(id, timestamp)` in your storage system.
* `int[] retrieve(string start, string end, string granularity)` Returns the IDs of the logs whose timestamps are within the range from `start` to `end` inclusive. `start` and `end` all have the same format as `timestamp`, and `granularity` means how precise the range should be (i.e. to the exact `Day`, `Minute`, etc.). For example, `start = "2017:01:01:23:59:59 "`, `end = "2017:01:02:23:59:59 "`, and `granularity = "Day "` means that we need to find the logs within the inclusive range from **Jan. 1st 2017** to **Jan. 2nd 2017**, and the `Hour`, `Minute`, and `Second` for each log entry can be ignored.
**Example 1:**
**Input**
\[ "LogSystem ", "put ", "put ", "put ", "retrieve ", "retrieve "\]
\[\[\], \[1, "2017:01:01:23:59:59 "\], \[2, "2017:01:01:22:59:59 "\], \[3, "2016:01:01:00:00:00 "\], \[ "2016:01:01:01:01:01 ", "2017:01:01:23:00:00 ", "Year "\], \[ "2016:01:01:01:01:01 ", "2017:01:01:23:00:00 ", "Hour "\]\]
**Output**
\[null, null, null, null, \[3, 2, 1\], \[2, 1\]\]
**Explanation**
LogSystem logSystem = new LogSystem();
logSystem.put(1, "2017:01:01:23:59:59 ");
logSystem.put(2, "2017:01:01:22:59:59 ");
logSystem.put(3, "2016:01:01:00:00:00 ");
// return \[3,2,1\], because you need to return all logs between 2016 and 2017.
logSystem.retrieve( "2016:01:01:01:01:01 ", "2017:01:01:23:00:00 ", "Year ");
// return \[2,1\], because you need to return all logs between Jan. 1, 2016 01:XX:XX and Jan. 1, 2017 23:XX:XX.
// Log 3 is not returned because Jan. 1, 2016 00:00:00 comes before the start of the range.
logSystem.retrieve( "2016:01:01:01:01:01 ", "2017:01:01:23:00:00 ", "Hour ");
**Constraints:**
* `1 <= id <= 500`
* `2000 <= Year <= 2017`
* `1 <= Month <= 12`
* `1 <= Day <= 31`
* `0 <= Hour <= 23`
* `0 <= Minute, Second <= 59`
* `granularity` is one of the values `[ "Year ", "Month ", "Day ", "Hour ", "Minute ", "Second "]`.
* At most `500` calls will be made to `put` and `retrieve`.
| null |
Hash Table,String,Design,Ordered Set
|
Medium
|
588
|
114 |
we need to convert it to english so let's try to find out quite a question we have given the root of binary tree platinum trend to link this simply says we have given binary tree one two three four one five six we need to converting serial number one two three ascending order with the help of several methods so in this video we are discussing several one method and in a upcoming video we have discussed another method on the same problem so the english should use the central through node class with the right child pointer to the next of the next node in the list and left child pointer the first point is say that we need to arrange in line by line means ascending order like 1 4 and on right side on left side though pointer of the left side is always been okay we have given this and we need to convert into this linked list and always remember we need left this is the right side is always the link a link to each other and left side always been known here is deadline this we need to convert the binary search into linked list serial order so firstly we will try we try to solve with the help of recursion method let's take one example this tree so we need to convert into this one two and five in ascending order firstly we need to shift these two into this side and the five or the remain the upcoming node of this tree is five we need to store in the time variable okay then i go in temporary so with the help of traversal we can transfer in one into this right side so point will be one two and there is five so this time variable i will be storing temporary memory of program so these are only for the two nodes three nodes so we have multiple nodes like one two three there are six nodes we need to continuously iterate and recursive methods apply on that nodes and traverse from left side to right side and we need to always keep in mind our we need to left side will be null there is no point on there is no node on left side so we need to continuously keep in mind with the help of recursive we can arrange this linked list in ascending manner so firstly we need to take our time variable time right and template tap left and right variable to store the left and right variable though are those are not in ascending order the on second point we need to make the node we need to make the left node will be null at point on every node on first order with the exception we need to sorry on first node from first node to last node we need to null left side this all this value will be null there is no tree on left side the flattened left and right will be recursively repeatedly we need to repeat that method again and again up to but all trees are is not in linear form attach the left part to the right so this left part we need to attach on this up this part three two three four and five and this is totally converted into output so we need to show that the binary search today we need to convert into linked list link search with the help of precursor there are other methods we will see in upcoming lectures upcoming videos sorry so i hope this question is understood i mean can frighten to replace with extra space okay we can also see this question in upcoming videos follow-up scan pattern upcoming videos follow-up scan pattern upcoming videos follow-up scan pattern yes we will try to solve this with the help of this complexity space complex let's try to solve this question with our recursive recursion after that we calculate the space and time complexity if the your time complexity space complex should not match to the follow-up question follow-up question follow-up question so we will try to so first we'll try this question firstly we need to check uh root value is left and right let's just make that the root the will be null and transfer to the right side so we will we call the function right side of the note uh so try to submit this question type is units means time complicit of this questioning question is zero login whole organization and time uh space complexity is of height the height is height of tree and recursively stack parallel space equal to or height in next video we will try to solve this question with the follow-up condition question with the follow-up condition question with the follow-up condition can you flatten the tree in place with over one extra space now our space complexity of height is always more than one so we will try to solve it with one space from space complexity thank you
|
Flatten Binary Tree to Linked List
|
flatten-binary-tree-to-linked-list
|
Given the `root` of a binary tree, flatten the tree into a "linked list ":
* The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
* The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.
**Example 1:**
**Input:** root = \[1,2,5,3,4,null,6\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
|
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
|
Linked List,Stack,Tree,Depth-First Search,Binary Tree
|
Medium
|
766,1796
|
203 |
hey everybody today I'll be doing another lead code one two three uh one not one two three two zero three remove linkless elements and this is an easy one and we have already done a problem similar to this in which we have removed the duplicates from the list uh this follows the same concept whenever we reach our targeted value we just do current dot next is equal to current dot next which just remove basically uh the targeted value like in this we are given 6 and we have to remove 6 from the linked list suppose we have reached 2 and the pointer is start two so we will check this is our current pointer at 2 so we'll check if current dot next is the value at the current dot next dot well which will give us the value is equal to our targeted value Target value means the value like we are given here if it is we will just take the reference of 3 which will be current dot next which is 6 dot next which is 3 and put it in 2 and that's it and we have another case in which what if we have to remove the head uh for example if 6 is on the head what we will do is just make to the Head who is the new head and that's it now let's code while there is a head and value at the head is equal to Value we are going to remove then just make the head is equal head dot next and this should work fine while the head is not null now and let me make another pointer so it will be less confusing not confusing so current will be the next pointer it will be holding the heads so now we'll be using current and if current dot next after doing this we will check if value at current dot next dot well is equal to the value we are supposed to remove and if it is we will just jump it current dot next will now hold current dot next our next uh next and in the else case we will just increment our pointer normally uh not current dot next just current dot next and this should work fine and after doing all of this we will just return our head and yeah that's it yeah this works and that's it
|
Remove Linked List Elements
|
remove-linked-list-elements
|
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50`
| null |
Linked List,Recursion
|
Easy
|
27,237,2216
|
771 |
foreign problem and the problem's name is dwells and Stones so in this question we are given two strings dwells and Stones so this string denotes the stones we have so our task is to know how many of the stones we have are also jewels and the characters inside these two strings are case sensitive which means lowercase a is different from uppercase so these two will be considered different Stones now let's take a look at this example and see how this question can be solved so this is the input string Jewels given to us and the second string is Stones we have to count how many stones are also dwells I'm going to use a hash set to store the characters of jewels and then I am going to iterate through the stones string and compare it with the hash set values so I've declared a hash set now I iterate through the input dwells from left to right first I'm going to access the zeroth element and add it into the set and then I am going to access the character at first index position and add it into the set and we reach the end of the jewel stream now let's iterate through the stone string from left to right and access one character at a time and then check if it is present inside the set or not if it is present we increment a variable count so let's declare a variable count which will be our output and initially it will be zero let's start with the first character is a it is present inside the set so increment the count let's move to the second character in character is capital A which is also present inside the set so increment count the third character is also a which is present inside the set so increment count the fourth character is B it is not present inside the set so count will remain the same and we proceed further it's a b again it's not present inside the set proceed further and the last character will also B which is not present inside the set so proceed further and now we are at the end of the string and we can terminate the iteration of the for Loop and finally outside the for Loop whatever is present inside the variable count will be returned as output so 3 is the output now let's take a look at the code this is the function given to us and these are the two strings dwells and stones and the return type is integer so you return the number of stones which are also dwells so I'm going to declare the output variable I'm going to name it count and initialize it to zero because as of now we have counted zero Stones which are also Jewels now let's declare a hash set which will contain character now let's iterate through the jewel string and add all the characters inside this set so I'm converting the string into a character array and accessing each character at a time using the variable CH and now we have to add the CH into the set so set dot add of ch so this for Loop will add all the characters into the set now let's do the same we'll iterate through all the characters present inside the string stones and check if it is present inside the set so again I am converting the stone string into a character array and accessing each character at a time using the variable CH Now using an if statement I am going to check if this CH which is representing the character present inside the string stones in each iteration if it is present inside this set so that check can be performed using the contents method so if set dot contains of that character then we increment the count variable so this for Loop will check for all the stones which are also dwells by comparing it if it is present inside the set and finally outside the for Loop you can return the variable count now let's try to run the code the test cases are running let's submit the code there you have it a solution has been accepted so the time complexity is often where n is the length of the stone string because it might be the longer of the two strings and the space complexity is also more of n because we're using a set to solve this question that's it guys thank you for watching and I'll see you in the next video foreign
|
Jewels and Stones
|
encode-n-ary-tree-to-binary-tree
|
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`.
**Example 1:**
**Input:** jewels = "aA", stones = "aAAbbbb"
**Output:** 3
**Example 2:**
**Input:** jewels = "z", stones = "ZZ"
**Output:** 0
**Constraints:**
* `1 <= jewels.length, stones.length <= 50`
* `jewels` and `stones` consist of only English letters.
* All the characters of `jewels` are **unique**.
| null |
Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
765
|
435 |
hello everyone welcome to my channel coding together my name is vikas ojha today we will see another lead code problem non-overlapping intervals that's the non-overlapping intervals that's the non-overlapping intervals that's the question number 435 it's a medium type question so we are given an array of intervals where each interval states starting and ending point return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping non-overlapping non-overlapping so let's see an example to better understand the question so we are given with these intervals like one two three four one three so if we remove 1 comma 3 then rest of the other intervals will be non-overlapping similarly with this example 1 comma 2 1 comma two and one comma two if we remove two one comma two intervals then the rest one interval that is one comma 2 will be known overlapping so there are there the minimum intervals that we need to remove here is 2. now let's see how we can approach this problem so we can use this in two ways first is the Brute Force where we can do uh using pick and non-pick do uh using pick and non-pick do uh using pick and non-pick way pick and non-pick and non-pick and non-pick where either we will pick the interval and non-pick the interval again so there and non-pick the interval again so there and non-pick the interval again so there are two ways to for one interval and again there are two ways for the other interval pick a non-pick and two ways for third and non-pick and two ways for third and non-pick and two ways for third and fourth so if we go by this root of 4 approach we will reach a time complexity of 2 to power n that is exponential as we have seen for the pick and non Peak pick we will have n 2 to power n parts or the v's so suppose we pick the first interval we don't pick the first second interval don't pick that's one way pick non-pick non-pick another way pick non-pick non-pick another way pick non-pick non-pick another way so there can be 2 to power n permutations combinations for these intervals to be placed so that we reach uh to find out the overlapping and the non overlapping values so is there any better approach apart from The Brute Force yes we will we can use greedy approach so for to apply the greedy approach we have to the with the greedy approach we will also use the Sorting because sorting overwhelms greedy approach As We Know so just a monitor here that instead of finding the minimum overlapping intervals we will find the non ever non-overlapping intervals that would be non-overlapping intervals that would be non-overlapping intervals that would be maximum non-overlapping intervals we maximum non-overlapping intervals we maximum non-overlapping intervals we will find we will subtract the maximum non-overlapping lapping intervals from non-overlapping lapping intervals from non-overlapping lapping intervals from the total intervals that will give us the minimum overlapping intervals that is the way we will you know achieve this problem now let's sort this array in the increasing end time why increasing end time because we want the intervals to end as soon as possible so that we find the maximum non-overlapping intervals if the maximum non-overlapping intervals if the maximum non-overlapping intervals if suppose we don't sort the intervals in the increasing end time the it can be the case that the first interval may keep on going till end till the end and it might be overlapping with others so we will not find the maximum non-overlapping find the maximum non-overlapping find the maximum non-overlapping intervals so here the aim is to find non-maxim so here the aim is to find non-maxim so here the aim is to find non-maxim non-overlapping you know so that we non-overlapping you know so that we non-overlapping you know so that we achieve with the minimum overlapping intervals so as we have sorted the arrays in the increasing end time so this is the line graph 1 comma two one two three one three four that I have drawn let's start with our count as 1 because we know this is at least one interval that is that will be non-overlapping non-overlapping non-overlapping now we'll check the other next interval that is 2 3 because its starting index is greater than equal to the start the end index of the previous interval so that is non-overlapping this interval so that is non-overlapping this interval so that is non-overlapping this is non-overlapping is non-overlapping is non-overlapping so we had started we have taken our start and end as this so we will now keep our start as it is and we will remove foreign we will change our end to this point now because this has been this is greater than equal to 3 so now our ending point is this one now we will check for the other interval that is one two three so as we can see that the starting point of this the next interval is not greater than equal to the ending point of the previous interval that we have the new end that we had done in the previous step so it's an overlapping it's not non-overlapping non-overlapping non-overlapping so we will not take it we will not take this where it's not over non overlapping now we will check the last interval that is 3 4 we will see that the starting point for this interval is 3 which is greater than equal to the last end that is that was three so we will take it as a non-overlapping take it as a non-overlapping take it as a non-overlapping so every time so we started with one here we found one non-overlapping we here we found one non-overlapping we here we found one non-overlapping we increment our count to two here we found one again non-overlapping here we found one again non-overlapping here we found one again non-overlapping we are again increment our count to three and this is the Mac these are the maximum non-over wrapping intervals this one and this one so we will as we had stated in the start that to find the minimum on overlapping intervals we will take total interval minus maximum normal no non-overlapping minus maximum normal no non-overlapping minus maximum normal no non-overlapping interval so the length of these intervals is 4 we have the maximum overlapping interval as 3 so 4 minus 3 will be 1. so this is the minimum overlapping interval that we have to remove so if we remove this interval all the other three intervals are non-overlapping so this is the are non-overlapping so this is the are non-overlapping so this is the minimum value we can remove so let's see the coding part we will first sort the arrays with the increasing ending time will initialize the count as one we will iterate over the intervals starting from the index 1 and we will take the ending the end as the ending point of the first interval will compare if the starting point of the next interval is greater than equal to end so if it is then we will increment our count pointer that will for non-overlapping non-overlapping non-overlapping non-overlapping intervals for this count non-overlapping intervals for this count non-overlapping intervals for this count is maintained for non-overlappings and is maintained for non-overlappings and is maintained for non-overlappings and we will update our end to the end point of the next interval that is in this Loop after the loop is completed we will have a count of non maximum non-overlapping a count of non maximum non-overlapping a count of non maximum non-overlapping intervals we will subtract from the interverse length and we will get a count so let's run this program so as you can see the test cases sample test cases are passing I have already submitted this code so it's passing so hope you like this video keep sharing And subscribe to my channel so that I will get motivation to present more such videos thank you foreign
|
Non-overlapping Intervals
|
non-overlapping-intervals
|
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping.
**Example 2:**
**Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\]
**Output:** 2
**Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\]\]
**Output:** 0
**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping.
**Constraints:**
* `1 <= intervals.length <= 105`
* `intervals[i].length == 2`
* `-5 * 104 <= starti < endi <= 5 * 104`
| null |
Array,Dynamic Programming,Greedy,Sorting
|
Medium
|
452
|
392 |
foreign welcome back to my channel and today we guys are going to solve a new lead code question that is subsequence so guys just before starting to solve this question please do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel so guys let's read out the question given to string s and t return true if s is a subsequence of P or false otherwise a subsequence of a string is a new string that is formed from the original string by deleting some can be none of the characters without disturbing the relative position of the remaining character that is a c e is a subsequence of ABCDE while eec is not so I expect that most of you have understood this question but still I am just gonna explain it to you with some example what actually they are asking is that there's a string s and there is also string T so we will be given two string and we have to check whether s is a subsequence of T so what is actually subsequence mean subsequence means that a b c should be in this string and their order should remain the same meaning that if a b c has the order like a and index or ABC is written this um so we cannot say that a means a should come first in this second then B then third should be C and if they are in this order then we can say it's true however if there is no order if they are not in order we can say that they are in for there the condition is false axc there is no X here so we can say that it's a fall condition and let's understand more of a bit here with a c e in ABCDE so you can see that if Ace is subsequence of a b c d e because a c e are in order of ac they both have the same order but aec is not because C should come first before E so that is or that is all in the question they are asking is that s would be subsequence of t so guys let's start writing the logic here and to do that I will just create a new Str string which will be my empty string and I will create account variable that will be my integer value and this will count the index primarily and to do that I will just have to create a loop so for I in P so I am saying that all the uh or else I can write that letters in letter in t which will be my a h b g h d a d c these will be my letter and I have to write if condition if um count is less than S Lan s if it's the if it's smaller then means the count is less than the length of the uh length of this my variable input s and what uh and letter means that this e h p g d c if these are equal to my S count as count I've just invest in edit the indexing uh like the account will be my zero here first initially it will be 0 so s it will check as 0 means sim a if it's equal to this T and the count should be less than the length of the S and if it's true then just uh new Str plus is equals to just concatenate what uh concatenate me uh letter means this letter okay it will first concatenate this letter then it will concatenate me this letter and this then it will concatenate me this letter because we have said that s count letter should be equal to the index of this index of what in this of uh s variable okay and if it's true then just in concatenate me and we have to also increase the count of count means we have to so means we have to just increase the count also because uh we just if we will not increase the count we will just stick to this variable that is r0 the index so we have to also increase this count and check for all the till date uh all till the length of this and uh if it's there then just return me return s is equals to new Str and that's all in the question guys let's see what we have got so far so see that it has been running successfully so brief you out let me explain it to you from beginning that first of all we have created a new Str variable that will count that is our empty string and then we have created a count variable that will that is of course our uh count to K uh count for counting the index and then we have created a loop and in Loop we have said that for letter in t that these are my letters these are a letters that is ASD uh BG DC these will be later if you talk about example number one and then we have created a condition here that's saying that if the count is less than the length of the S and later letter these are a for this for first of all it will check for a if a is equals to the this as index count as index account if we check count is zero initially so it will check letter is if it's equal to that s count then just increase that's just concatenate the newest here into our new letter into our newest here and then increase the count by one as well because if you will not increase the count it will just stick to the zeroth count so we have to also increase the count as well so after this we have just said that if this is all happened here this if this has uh just concatenate and all this stuff has been done then just return me the S is equals to new Str okay we are seeing that s should be equal to our new variable which we have created that are new string should be equal and if it's equal then return me true if it's not equal then return me false and that's all we have done in this question guys I hope you have understood this question if you haven't understood it yet ask me in the comment section I will try to sort it out thank you guys for watching this video subscribe to my channel and see you next time
|
Is Subsequence
|
is-subsequence
|
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_.
A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not).
**Example 1:**
**Input:** s = "abc", t = "ahbgdc"
**Output:** true
**Example 2:**
**Input:** s = "axc", t = "ahbgdc"
**Output:** false
**Constraints:**
* `0 <= s.length <= 100`
* `0 <= t.length <= 104`
* `s` and `t` consist only of lowercase English letters.
**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
| null |
Two Pointers,String,Dynamic Programming
|
Easy
|
808,1051
|
1,701 |
Hi everyone welcome to my YouTube channel, today we are not very good, the average waiting time is 1701, we will understand what is this problem and what is required from us, there is a restaurant with single. There is one chef in our restaurant and there is only one chef in the restaurant, okay, there is only one chef here, you are given in every customer and this is a lot of our customers, okay, this is the kind of Okay, what is given in this line, take the mains of these customers, this is customer A, customer B or customer C and this is customer D. Okay, their rival time is given and their time I is given here. But then the arrival time of the customer and the time, how much time does it take for his food to be prepared, man, a customer came, some 8 left, okay, he came at 8:00 and he ordered, okay, what did he came at 8:00 and he ordered, okay, what did he came at 8:00 and he ordered, okay, what did he order, pizza? Now the poor chef is alone. This will make the pizza and the time it takes to make this pizza is this time okay so I have customer reverse he gives his order and d chef starts preparing it once he idle d customer wait steel d chef finishers preparing this order means till This chef prepares the order for him, which means that he will have to wait for his order until he prepares it. It is a simple thing, isn't it? We go to a restaurant, just like when we order food, as soon as we order, it does not come to us, we get some food. We have to wait for about 15 minutes, our food is cooked and then it reaches us, give food for more to the van customer, now because the poor guy is alone, they did not even give much load to the chef here and he said that the chef Will cook food only for one customer at a time, meaning if I take this customer of yours at 8:00, it takes 3 minutes for the pasta to be prepared, okay, so now when the order from A comes to him, he First he will prepare pizza and give it to person A, after that he will make pasta and give it to person B, which means he will complete only one order at a time, then 10 prepare food for customer in the order he gives it means if A comes first then A will get it first. A means the way in which A is placed before B. In this, food will be prepared for A only. Return D. Average waiting time means how long all the customers have to wait. We have to find out the average of them. We have to find the solution with these 10 tu di power. -5 From solution with these 10 tu di power. -5 From solution with these 10 tu di power. -5 From D'Actual Okay, so friend, this story which I have written here is what happened to you, the problem statement is that I have explained the problem statement to you, now an example has been given to us here, so let us understand it further. Okay, so look friend, what is given here, the arrival time of the customer of Van Kama 2 is given and the time taken to process his order, that is why I take the processing time, that is given, okay. Let's talk about the technical side only, a little bit about B, what have you given us, you have given his arrival time, five has been given time for his order to be prepared, if I talk about C, then C has given four arrival time. And three, its processing time is given, so this is basically given to our customer, okay, now friend, first forget everything, a, come to us, this is my restaurant, okay, this is my restaurant and in this restaurant, a A van came to me at the unit of time. Okay, I am writing it in units, so a van came at the unit of time. Take it, take the order for the pizza. It took 2 units of time to make the pizza. What happened to you until you ordered it? I mean, if the order is placed in 2 units of time, it takes a total of three units of time. It means when the order of A was fulfilled, when did the share become free at the time of three units of time, the chef became completely free at the time of free time when he got the order. In two units he made it and in three he delivered it, okay now look, the B one had gone to A in 2 units. If I draw here and see, the van one is here, where you are in three. Okay, so the A one had come in the van. Of course it took his order to be made, look at the units of it, we got the order, now it took this much time, one unit, this is how much time it took for the pizza to be made, okay, it took this much time for the pizza to be made, but this Who has gone to A on this 2? B and A has gone. Who has gone to B and A has gone. He has ordered some pasta. What have you ordered? Have you ordered till date? How much time is it taking to make? Some five units of time. It seems okay, so here I am, this is four, this is your favorite order, he got the order for 2, he got the order for sure, Chef B got the order, but the chef is not vacant, is our chef vacant on you? Is he still making pizza and has given in the question that he will solve only one order at a time? Okay, so maybe he is not free right now, so when will the chef be free ? It will be ? It will be ? It will be free, it will be absolutely free, so here what will he start preparing now, will he start preparing the pasta, will he start preparing till today, preparing, will he start preparing till today, meaning at three, he started preparing, here at three, he started preparing the pasta. Now how long will he make? He will make pasta till five units. Okay, it takes so much time for him to make pasta, so when he comes, it means what will he give to the customer of B at the time of coming unit, what will he give to the nearby customer, what will he give to the pasta, okay then friend, see now. I wanted to tell one thing to the customer A here that how much did the customer A have to do that he got the order for free, he came on the van, so many units, he had to wait, now see who of ours had come to you. Tu pe hamara B had come et pe, he got his order, so how much did he have to wait, six units B had to wait, okay, that's it, now look, now if I congratulate him a little more, this timeline here, a little more congratulations here. This van is fine, now look A, our van came on when did it get the order, A got the order here, it is fine, B, our 2nd pay, A had gone, B got the order completed, F, B, I am writing here, at, it is fine. Now, who is ours on the fourth unit of time? The scene has made some demand for whose noodles, my friend, I have to eat noodles and these noodles are prepared in three units of time. Got the order for this. But Friend, look, is our balance free on 4th? Is our chef not free on 4th? Not at all. So now when will he start making C's order? Where will he start making C's order on arrival? Where will he start making C's order? This 8 units. On off time, when he will be free from B's order, he will start making it. He will definitely do it. Now, when he comes, he will start making the order plus three units of time and if he gets it, then at what level will he deliver the total order and at what price will he do it? Friend C had already paid A on the fourth day and on 11th he got the order, how much did he have to wait? 11 - 47, he had to wait so much, he have to wait? 11 - 47, he had to wait so much, he have to wait? 11 - 47, he had to wait so much, then how much was C's waiting time, it became 7, it was exactly seven, so look at A's waiting time. Time is not 6, but the waiting time of A. What is the waiting time of B? What is the waiting time of six and C? We have the average of all these. The average of all these means 2 + all these. The average of all these means 2 + all these. The average of all these means 2 + 6 + 7 / 3 6 + 7 / 3 6 + 7 / 3 A. This is our answer. If there is waiting time, then friend. Example Here, you must have understood a little bit about what is going on, okay now we will talk about how we will do it, so let's see, look friend, these are our customers, okay now friend, I will reduce these customers here. Whenever the order is received or received at any time, you store it in another year. Okay, the order was received at this time, what was the arrival time, what was the van, what was the duration, only one, the duration was 2, absolutely now friend, what happened to you, ours. It is 2 units of time that the order will be prepared. Okay, in that much time it will be prepared, so I am here, write the total time, in all this, in preparing the order, in meeting it and then in delivering it, whatever amount it takes in all. Time taken, he will reach here, so friend, I will take this total time now because I have a customer with A, so I will write the arrival time plus duration, what will happen is this, we will have 1 + 2, how much will it become, it will be three, then one. + 2, how much will it become, it will be three, then one. + 2, how much will it become, it will be three, then one. When will A get his order? When will A get his food? Pay 3 units of time. Okay, so friend, if I talk about the waiting time here, how much will it be? If I do it after A's waiting time for A, what will it be? It will be said that he got the order on 3rd, he had given the order cup, he had given it on the van, you are ok, this is the waiting time for A, it is good, but look friend, now here if I make a timeline, then at our place, A came on the van, okay. You units of time taken to prepare his order means here the chef is free from the order but where is B where A is and how much time does it take for B's order to be prepared? BK's order takes some five minutes of time to be prepared. So see what I took back to the arrival time, what did you take, how much duration did you take, I took five when I came to B, then friend, if I leave in this total time, how long he had to sit in the restaurant, it is okay, preparation for receiving and all those things. So friend, see carefully that my B came on you, it was okay and when Saif is free, now I will add something else here I will do that, I will put it here, okay, so friend look, it came on you, she was chef. How much time did it take to become free? For 3 - chef. How much time did it take to become free? For 3 - chef. How much time did it take to become free? For 3 - 2 B, I am talking about the scenario of B. It took so much time because look, on three, the chef is getting free. B is already on A, so the chef is getting free. Only 1 unit of time has to be spent, here P has to wait so much, so how much will it be 2+5+3-2, how much will it be 2+5+3-2, how much will it be 2+5+3-2, we will have 8, which means when will B get his order, when will he get 8 units of time? Here B will get his order, he will definitely get it because look here, he placed the order in a stupid manner, his order took ₹ 5 units of time to be prepared his order took ₹ 5 units of time to be prepared his order took ₹ 5 units of time to be prepared but the chef was not free, so there is nothing in the chef being free. If it took time then this was the total duration of B. Okay, now what did I do here? How much did B have to wait for our B? Our B came at 2 o'clock, when he got the order, he had to wait till 6 o'clock, plus how much? It will be done here, it will be six. Now friend, you will say, what is written here, what is this? So friend, look at what is being made here, right, this is the eight that has come to us, from the beginning to 1 to the middle. On how many minutes of time will the order be received, it does not mean that B is starting from you and then not him, this van means from the van unit of time to how much time does B get, it means that A's order is filled then a After A's order is fully filled, B's fulwa, this means that now if I talk about C, okay then what will be the arrival time, what will be four, how much will be the duration, it will be three, it will be absolutely free. Now look here. What is this equation, we have arrival time plus duration plus chef's time to be free. Exactly this is our equation. Look here, what is the arrival time, we have four, what is the duration, we have three, but what is the time for chef to be free. Now see, chef at pay is becoming free, ours is fine and how many times and C, when A is coming, how much will be the CFT here, if C itself is free, when is four pay, then here pay will be +4, so how much will it be? A will go to here pay will be +4, so how much will it be? A will go to here pay will be +4, so how much will it be? A will go to us at 11, meaning us, A will go to us at 11, meaning when will C get his order? If I look at it from the point of view of 1 unit of time, then C will get his order at 11 and then how much weight has C had to pay here, so how much should be added here. It will be added here, our four pay order came on 11th, he got the order 11 - order came on 11th, he got the order 11 - order came on 11th, he got the order 11 - 4, how much is 7, so what will happen to us, this will be ours, it will be 2 + 6 + 7 and to ours, it will be 2 + 6 + 7 and to ours, it will be 2 + 6 + 7 and to get the average, divide it by 3. So 5, this will be our answer, okay, so what are we doing here? What are we keeping track of? Or on whichever unit the first order has arrived, I take my first order on 5, if I talk to five, then on whichever unit, basically the thing is that if I talk to the arrival time of the first order, then every customer. At what time is he receiving his order, we are storing it here. Okay, here we have an equation and to see the total time, what was his total duration of time, the amount of time he stayed in the restaurant, then arrival time plus duration plus chef's time. The time of being free is fine and then we calculated its waiting time. Here, it was here, but now you will say, man, this is the previous one, okay, this is ours, what is the total time of the previous one, now is there any next one? Man lo, it's like here the previous order is getting finished and at nine you are getting a new order, meaning here the customer with nine is man lo these are some customers, at the time of arrival your order is getting finished and at nine If this person brought you the order, then perhaps he is free right now the chef is free, so in this case, what will be the free time of your chef? Look, in this case, the free time of your chef will be zero. Okay, why will it be zero? Because look friend, here the chef does n't have to be busy. What is this? Basically, how much time will it take for the chef to be free? How much time will it take for the chef to be free? If it is fine here then it will become zero. You finished the order and your order was received as soon as it arrived, even then what will be the CFT? Will it become zero? Okay, so now let us code it once and see, I am the customer here, I have to give the answer in double here. I will make a double weight, I will take double the arrival time, which is A, what will I take in the stomach, I will take double the duration, which will be ARA, I will take the total time, which I am saying from T here, what is this? The time it will take for the arrival time plus to become free, here the waiting time of the first one will already be there, what will come, we will mine the total time, we will calculate the arrival time, I had stored it here, it is okay, but even if I am not a stone. Even here, we will run less, why will we run here, she tells me what equal you brought me from the van < where till where I am coming, equal you brought me from the van < where till where I am coming, equal you brought me from the van < where till where I am coming, now I equal you arrival time, what happened to arrival time, okay now if my total time Look at the previous one, if its total time is correct, if what is it is bigger than our arrival time, then now see this scenario is that the customer wait is over, then what will be our CFT here, we will remove it. We will remove the arrival time, okay, this much he will have to wait, otherwise what will happen to CFT, ours will become zero. Okay, and what will we add to the weight plus single, we will pay here as much as our total on time. Total time will also change. What will become of total time? Total time will become arrival time plus duration plus baking time. Sorry minus arrival time. This much he will have to wait because see what was happening here that B got our 2nd order. When did B get the order? Complete OK, he got his order as soon as he arrived, now what is this coming? Let's talk about the first customer. In respect of the first customer, when did B get his order? So now how much did B have to wait from the time of his arrival till the time of his arrival? When we received the order, that much weight had to be waited, we will definitely add that much here and what will we return in the end? Look at this small kurta, friend, I have not even taken the space, I explained to you from what was the space that we store. But when we are doing the process every time, then why do we need to store the total time in a separate vector, so we have done all our work here. Now let me run it and show it. First of all, we get a completion error. So where could we have made a mistake, why did I write S-CFT and for both the cases our answer was absolutely correct, here the question worth thinking about was what good can happen here and in what way on the previous order. Next order is dependent, we had to think about it a bit, so I think in what way I solved it here and then if you understand then please like the video, share it and subscribe the channel. Thank you so much.
|
Average Waiting Time
|
remove-max-number-of-edges-to-keep-graph-fully-traversable
|
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:`
* `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order.
* `timei` is the time needed to prepare the order of the `ith` customer.
When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**.
Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted.
**Example 1:**
**Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\]
**Output:** 5.00000
**Explanation:**
1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.
2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.
3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.
So the average waiting time = (2 + 6 + 7) / 3 = 5.
**Example 2:**
**Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\]
**Output:** 3.25000
**Explanation:**
1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.
2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.
3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.
4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.
So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.
**Constraints:**
* `1 <= customers.length <= 105`
* `1 <= arrivali, timei <= 104`
* `arrivali <= arrivali+1`
|
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
|
Union Find,Graph
|
Hard
| null |
1,168 |
hi everyone with Kelvin here so let's discuss about be weekly contest 7 for question optimized water distribution in the village so we are having n houses in a finished and then there is an option to put water source to each of the house with given cost in variable called wells so first house needs need cost of one to put water source second hosting cause of to enter of snip cause off to there is also option to put a pipe to connect to house so they can set the water source so let's see the first example here we have three house with the Wells of course of one two and two for first house second house enter house and we have the pipes as well so let's say if we don't want to build the pipes at all then every each house will build its own Wells so we will end up with a cost of 5 1 plus 2 but if we build a pipe it will be more effective so we will pick the first house to put the wells with cost of 1 and then we connect house 1 and house to with the cost of 1 and then we connect house 2 and house 3 with the cost of 1 so in total we only spend cost of 3 okay so yeah that is the minimum cost in the first example here so how we going to approach this question is basically we need to know like whether through city is connected or not so we can use data type called this join Union set to detect them and another thing here is let's say we have three pipe like we have one more pipe option here right if you already build the pipe 1 2 & 2 3 you build the pipe 1 2 & 2 3 you build the pipe 1 2 & 2 3 you don't need to put another pipe from 3 to 1 because 1 2 & 3 1 because 1 2 & 3 1 because 1 2 & 3 currently is already inside one group so you don't need to pull the pipe from 1 2 3 so we could we also can check that by using the disjoint union set so yeah when we let's say we have three option of pipe we need to start from the cheapest pipe - well first so we need to cheapest pipe - well first so we need to cheapest pipe - well first so we need to sort this pipe by the cheapest one by the smallest cost first so yeah let's see the solution so I create a simple decision unions in structure here so when you're going to merge two group into one like you building pipe from 1 to 2 it means this the group of 1 let's say 1/2 a lot of connected say 1/2 a lot of connected say 1/2 a lot of connected house and to have a lot of connected house when 1 & 2 is connected all city house when 1 & 2 is connected all city house when 1 & 2 is connected all city there is connected to the 2 is also connected to 1 and also the refers way so yeah when we try to models we try to find a group of a and we say the group of a pattern will be group of B parent so all of them will be connected this is in this genuine set you probably can check it out on how this journey on said this join you network and when we try to do a fine we try as long as it's not the parent we keep find doing the recursion call until the pattern is itself so this one also a very standard method from disjoint units and you can probably try to check it out so let's focus on the solution itself so we have so this is just a initialization of the decisional set and yeah we initialize each of the house have its own group initially because we don't put any pipe yet so house one the parent will be house one so house one the group one house to group to house three root three and etc and next thing is cross detector so each of the house so what detector is so you have a house and how much is the cost to put a water source there so at the worst case every house will its own Wells right so this is the maximum cost initially we put unless we can figure out like if we can merge it and we don't need to put the source later on so yeah and next thing is we saw in the pipe based on the cost so we start from the smallest cost to the most expensive cost to the reason I explained before and yeah and then we look through all the pipe starting from the cheapest pipe so the pipe to connect House aide to house B with the given cost from the index 0 1 & 2 here first cost from the index 0 1 & 2 here first cost from the index 0 1 & 2 here first house second house with the cost second house third house with a cost so how do we decide like we want to merge the first house and second house so we need to know like first house and second house is not connected to a same group first like if 1 & 2 is connected group first like if 1 & 2 is connected group first like if 1 & 2 is connected and 2 & 3 is connected when we check the and 2 & 3 is connected when we check the and 2 & 3 is connected when we check the group of 1 let's say the pair it's called Group 1 & 3 is also in a it's called Group 1 & 3 is also in a it's called Group 1 & 3 is also in a group 1 like so they are in the same group so we don't want to put another pipe but let's say 3-stone connected to pipe but let's say 3-stone connected to pipe but let's say 3-stone connected to 2 then 3 is possible to be connected to 1 we it's possible for us to pull that pipe because 3 having different group 8 1 2 right so yeah that's fine method like good what is the group of a and what is the group of me if they are not the same then we can continue to the next checking condition is what the water source to put a group a and water source to group B so we try to find their minimum cause like cause to pull water source for group a and constant water source from Group E what is the minimum cost so we started in the minimum well so if we decide to build that pipe the cost will be the minimum well plus the cost itself cause of the pipe right or if you don't want to build the pipe which is represented by cause here the cost to build the separate well means the cost the group the cost of the group a and the cost of the group a being added up we compare it with if we build the cheapest tip as well plus the pipe if it's cheaper to build the pipe then we merge the group a and Group E once we match Group A and Group E we update the costs so costs of the group a or cost of the Group B is the same because we already merged Group A and Group B so that group the cost will be minimum well right - the cost will be minimum well right - the cost will be minimum well right - well that thing yeah and the total cost will add up to the cost so the cost is the cost to build a pipe but the well itself we will add it later on that's why we have not doing minimum well plus costs because the cost of the pipe we want to calculate it separately from the well itself so that's why we don't add another cost here like minimum well plus cost but this cost is just the costs of building that group for the water source but the pipe itself is already built so we are already appended to the total cost right the reason is because when we try to add up a lot of house into one group like let's say we have a lot of house and we already connect all the house into one group right so we will end up only building one Wells and all the pipe that is required to connect all of those houses so that's why you see pipe costs already added up because we already decided to put that pipe but the well itself we need to determine it at the last if we already much a lot of house into one group by the pipe then we only need the minimum well in those pipe so that's what we are trying to do here so I credit has set just to make sure like the Wells for that group is already built so we look through all the all of our house and we check like if we haven't put a well for that group so you see here we do a fine I which is find a group of that house so when it's connected like this we can say like house to the group is one house three the group is also one and house one the group is also one so that's why when we look through all the house we just need to make sure like we happen with the water source for that group so if we haven't build the water source for dead crow then we boil the water source or that group with the costs to build that water source right and then we mark it as visited so the total cost will end up having all the cost to build the pipe and it costs to put the water source for its unique group and that's it for this question so thank you for watching see you on the next weekly contest
|
Optimize Water Distribution in a Village
|
duplicate-zeros
|
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes.
For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs.
Return _the minimum total cost to supply water to all houses_.
**Example 1:**
**Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\]
**Output:** 3
**Explanation:** The image shows the costs of connecting houses using pipes.
The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3.
**Example 2:**
**Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\]
**Output:** 2
**Explanation:** We can supply water with cost two using one of the three options:
Option 1:
- Build a well inside house 1 with cost 1.
- Build a well inside house 2 with cost 1.
The total cost will be 2.
Option 2:
- Build a well inside house 1 with cost 1.
- Connect house 2 with house 1 with cost 1.
The total cost will be 2.
Option 3:
- Build a well inside house 2 with cost 1.
- Connect house 1 with house 2 with cost 1.
The total cost will be 2.
Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**.
**Constraints:**
* `2 <= n <= 104`
* `wells.length == n`
* `0 <= wells[i] <= 105`
* `1 <= pipes.length <= 104`
* `pipes[j].length == 3`
* `1 <= house1j, house2j <= n`
* `0 <= costj <= 105`
* `house1j != house2j`
|
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
|
Array,Two Pointers
|
Easy
| null |
1,209 |
Had a big Ajit Mahajan welcome talk on WhatsApp so this video into this video will be talking about drama number 209 also called as remove duplicates in spring 21 year 2006 champions so let's get a given string yes okay duplicate removal consists of Choosing to that descent and equal latest from this and removing them for watching the left and right side of the delimitation to continue yadav vipin delhi me one's duplicate removal schedule with long can return final scene after all this difficult removal of credit guarantee dancer this tree Word So Fixed When Created And Tom Ford Twitter Mobile And Desktop Screenshots Bluetooth Russia's Saint Letters Ideas Absolutely And Need To Remove Country's Center For The Meaning Of Side Subscribe And String Operation And The Return Of The Day Set Example By You Ribbon Since 2010 The example that will have is think of AP B C D A B is physical two letters which of the following is not an example for the giver channel subscribe The Channel subscribe and subscribe the Channel Result of birds pencil drawing yesterday Subah Can Also Removed At 2nd Year Left Ventricle Detail And Now You Can See The Temple Dedicated To Wish Him On Water Can And Will Love Double 102 FD Samsung 312 No Problem liked The Video then subscribe to the Page if you liked The Video then Ki Suvan Shri Munat Abhi As per Ticket Window Awadh News Soon Against Dual SIM And Not To Win But Stop This A To Sudhar Things That We Can Do Yes We Can Be Used And By Hunter Thomas Number Of Times And Home Number Of Times Any Particular Elements Record Solar This Visiting A String Writes On Every Time Will Love You Get With New Element Thursday subscribe to the Page if you liked The Video then subscribe to the two More Subscribe Quizzes Prepared to Declare Elements in the mood for the bone but before adding reliable video The Video then subscribe to the presents subscribe comment and subscribe the Channel subscribe two three one two three main office equal two show again this time to virar to remove this element depend to different Top Three End Subscribe Table No 21 Subscribe Now Two Times Now What's The Subscribe Vyas Right Choice Every Character With Or Without Needing To Recent Abe Left And So Will Require Something Like To Pair Because Doctor Kidnapped Scooter And Every Time We Encounter Renew Your CHARACTER WHICH IS NOT THE TOP 100 QUESTIONS LIKE AND SUBSCRIBE MUST SUBSCRIBE PAGE COMING TO OFFICE TURN OFF BANE TO THE COMPLETE STRENGTH BUT AS THEY ARE GIVING SO LET'S DO THE DAY GONE SONA BLOODY HOTSPOT OF THE CO DUST WHAT THEY ARE DOING JUST Waiting for Every Character subscribe this Video then subscribe to the Page if you liked The Video then subscribe to the Page Beauty and Hot Wheels of Previous Word in the State Bank of Indore Data Structure and Details of All Elements Not Different And Use This Is The Time David Element From Subscribe Now We Are The Final Subscribe To Mein Ruke Sona What Pyaar-Vyaar Basically Ruke Sona What Pyaar-Vyaar Basically Ruke Sona What Pyaar-Vyaar Basically This Person Doctrine Which Will Return Dakhil Result And Basically A Taraf Years Which Content Elements Present In Every Time They Are Doing To Automatically Detects Rotten Subscribe to the Page if you liked The Video then subscribe that if the result Chapter 9.1 Reversed that if the result Chapter 9.1 Reversed that if the result Chapter 9.1 Reversed System Codes 10 Most Probably Work and Yes Author Jhaal And Has Been Waiting For The 98% Place Jhaal And Has Been Waiting For The 98% Place Jhaal And Has Been Waiting For The 98% Place And Went To Send Space Saunf This Video Guys You Like The Video Hit The Like Button Left Side Se 1000 Like Button A Few Rules Sach Content Aa Or List Question Sandwich Subscribe And Also Next Video Boy A Kar Do Ajay Ko Kar Do
|
Remove All Adjacent Duplicates in String II
|
design-bounded-blocking-queue
|
You are given a string `s` and an integer `k`, a `k` **duplicate removal** consists of choosing `k` adjacent and equal letters from `s` and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make `k` **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It is guaranteed that the answer is **unique**.
**Example 1:**
**Input:** s = "abcd ", k = 2
**Output:** "abcd "
**Explanation:** There's nothing to delete.
**Example 2:**
**Input:** s = "deeedbbcccbdaa ", k = 3
**Output:** "aa "
**Explanation:**
First delete "eee " and "ccc ", get "ddbbbdaa "
Then delete "bbb ", get "dddaa "
Finally delete "ddd ", get "aa "
**Example 3:**
**Input:** s = "pbbcggttciiippooaais ", k = 2
**Output:** "ps "
**Constraints:**
* `1 <= s.length <= 105`
* `2 <= k <= 104`
* `s` only contains lowercase English letters.
| null |
Concurrency
|
Medium
| null |
4 |
hello friends welcome to good Hecker this coach material here we're going saw mininum - so Deena risk only father they mininum - so Deena risk only father they mininum - so Deena risk only father they are two saudi-iranian are two saudi-iranian are two saudi-iranian and lungs - of size m and respectively and lungs - of size m and respectively and lungs - of size m and respectively find the medium to Saudi Arabia tio log M plus n so example one here lumps one is of one three and lungs - it's a true is of one three and lungs - it's a true is of one three and lungs - it's a true the medium is a 2.0 we see here in total the medium is a 2.0 we see here in total the medium is a 2.0 we see here in total Lia like an odd number so we take the middle one that's a 2.0 and the example middle one that's a 2.0 and the example middle one that's a 2.0 and the example true here times one is one - lungs two is three four the meaning is - lungs two is three four the meaning is - lungs two is three four the meaning is of the average between the two middle numbers that's a two plus three divided by two that's two point five so in order to solve this Corey Pavin so we can look at some example and then divide our conclusion and our algorithm then we can solve this a meaning of true Saudi Arabia so here we can take a look at some example first so first there are example so this example we have a two sorted array a and B so in total there are four numbers come back with a to Saudi Arabia is a four numbers and the median would be the average between the two middle numbers so if Lea in Saudi our rate you know Sunday order there's one two three four so the median will be the two plus three divided by two that's a two point five so we get to the average of two middle numbers and this example we have a total one two three four five that's a total fine numbers so that's odd number so the medium would be just take the value of the middle number so if that's in ascending order there's one to show you five so that's a third one that's a two million number is just 2 so here we notice that the total number of the a and B array matters so if the total number is a even number that we take the two middle numbers and get their average to get a medium value and if that total number is like a fine there's an odd number so if that's an odd number in total and the way I just take the middle number so the middle number oh I don't like the third one that's a 2 so we know that the total number season is an important factor for us to find a medium so here like a first one the if the total number is a even number so we are actually looking for the total divided by 2 and the total divided by 2 plus 1 these two numbers we get these two numbers and get their average and if that's just odd number so that we are only looking for one number that's a total divided by 2 plus 1 this number is a million number so here we can derive our goal for the public phone find the meaning of to sort an array to us Nariko that would be the find case number in a and B so here finds a case number C here like as a first example we are looking for find the total divided by 2 number in a and B and a final a total divided by 2 plus 1 that number in a and B and this example find the total divided by 2 plus 1 number that's okay is just a total divided by 2 plus 1 so here we have this fighter casing a and B then we can step further to least our like a cases like if we can compare with the first half first K divided by 2 e numbers in a and the first K divided by 2 in B then we come here you've letter Y is a smaller that we can get rid of that part and keep searching that it finds the case number in a and B so here like a leaf the a the first K divided by 2 numbers in a is a smaller than the first K divided by 2 numbers indeed since it is a saltier repose our soul theory and the largest number in the first K divided by 2 numbers in a is of K divided by 2 number and they say they don't index so that our K divided by 2 minus 1 in array and we compare this to number if a look first K divided by 2 numbers in a is a smaller lender that first our K divided by 2 numbers in a B that we can see that we know that the first half in a we can get rid of and so that we can if we need to find a case number we can just go to finds up reduce our range so our range would be K divided by 2 a by 2 plus 1 and so on those Resta animates ways of B array that we can find a comparison together to find our case so we already get afraid get rid of first K divided by K half and a similarly if hey first arcade divided by 2 number is greater than first RK / two numbers in not B then in first RK / two numbers in not B then in first RK / two numbers in not B then in that case we can get rid of the first half in the B so if we are looking for case number so we can just use a current a range with a reduced bar-8 range so we a range with a reduced bar-8 range so we a range with a reduced bar-8 range so we are looking for them be K divided by 2 number we K divided by 2 numbers plus 1 and the rest elements use this range to find a case number seen both in a and B and a larger case so if there is no animals no numbers in the 8th so in that case we can just directly return the case numbers in the B that's a K minus 1 index that is a case number in both a and B similarly if there is no element in B so that an the case number in a is a number we are looking for and another scenario that's a like a HK sold even K is just 1 so we are not only looking for the first element in a and B in that case we can just an a directory returns up first value of the current range of a and a current range of be so minimum value of them like a search place in a and the first of value in the bit B so that's the first one so that's meaning value and the week directly return so with this these larvae cases we derive our a gorilla so we are actually when we're looking for the medium value in two sorted arrays we are looking for the case number in a and B like for you a number we are looking for the total divided by two numbers in a and B array and we are also looking for a larva total divided by two plus 1 numbers in a and B when we find this to lumber we divide by two in the medium way and if the total numbers is a just an odd number we are only looking for total divided by two plus one that number that's a case in a and B and we find that we can return as a medium for a and B array okay so with this cases we can come work to the code and to solve this coding problem so go back to the Cody let's use a Java to solve this column table so as we just said where you can first check the total nuns over to erase so we get a two total ins because it's total ins to matters like a total nuns if that's odd number even it's a whole number so we are only looking for final case number in that case we are only looking for one number that is total divided by two plus one so they are all looking for total divided two plus one this is a cake otherwise it will total number is a even number so we are looking for two numbers first one we are looking for total / - first one we are looking for total / - first one we are looking for total / - this is a first number we are looking for and the second one we are looking for his own code whole bus divided by 2 + 1 so with these two values together we + 1 so with these two values together we + 1 so with these two values together we can divide by 2 to get the average so we find the total divided by 2 that's a clean number and total divided k2 by 1 that's a lot of 1 and we divide their sum by 2.0 together average because it sum by 2.0 together average because it sum by 2.0 together average because it is a make it a decimal point so we need to use a 2.0 so here then we can build to use a 2.0 so here then we can build to use a 2.0 so here then we can build this find a case function so it will return our integer value so fine case a case value so it takes up both sorry and the start searching index of a post array so start to and okay the case number we are looking for so first if like we just said if there's no more elements in the first re if there's a no 4 story that means start index search searching index is already equal or greater the noms on and we can just directly return the current k case number in the second array so that would be 2 plus K and if there's no more animals in secondary similarly we can return just a case number in the first re and you for the K is just a 1 in that case we can just directly return the mininum value between the current first lump our first element in the first array and a signal early to start to and now we can have a compare wisdom first a to the first K divided by two numbers in the first array and a second array so that we can have a compare so here it's a Hera like a index one would be the start 1 plus K divided by 2 minus 1 and index 2 would be star K divided by 2 minus 1 and the value of the index so it would be next quarry as a key so Latin if the index 1 is with her or Ecotools on nom Swan dominance and it is a smaller than done so he is possessing range and we can get the value of that number so that some lumps one index one otherwise we can just as an integer top max value to indicate it's already auto bring similarly if this is a student range we can get that value max value and then we come here so this is a this too is of as we just have said this is a first time the K divided by two numbers in the a and a K divided by two numbers in a be the single array so if the cake one is a smaller and the cake true we can just keep going to looking for get rid of the first hop in the FIR first hockey in the first I'll read so that nawa but this start index would change the starting index will change to fungus star index + index will change to fungus star index + index will change to fungus star index + k / - it's true and still current k / - it's true and still current k / - it's true and still current arranging second array and otherwise we can find a case that will get rid of first hi in cigarette one alums - and first hi in cigarette one alums - and first hi in cigarette one alums - and that would be star two plus K divided by 2 and here the it's another K is a K minus K so the case number is changed because we already Gatorade over hop so we can K minus K divided by 2 so that's it so here it's a double check Jeff keeps our typo we first okay to the total nuts over to erase if that total Nance is a odd number and we just need to find the total divided by 2 plus 1 that number that's a case number otherwise we need to find two numbers if that's a total number it's a you a number we can give the total divided by 2 number that's a case number and total divided by 2 plus 1 and so also our kind number give this to lumber and get an average and we build this fine case Hoover function to looking for the case in two arrays so if without first one is already autorange there's no more elements enough versa agree we can directly return love the currently a as a case number in the secondary seminary gives no more elements in the single ring we return the case not a case number in the first Audrey if the K is a just one we return a medium value in current first Audrey and second array and then we looking for the compared with our first our K divided by two numbers in the first array and a second array so that if Liv first K divided by two numbers is a smaller than first K divided by two numbers in the second array that we can get rid of a first law K divided by two lumber in the first sorry and doing us search keep doing the search and the if the first RK / - lumber is a and the if the first RK / - lumber is a and the if the first RK / - lumber is a greater than the first K divided by two numbers in the signal array so we can get rid of the first K divided by two numbers in the cigar E and keep doing a search ok let's click the submit button exactly so this is a correct answer for this up try and find the meaning of a to saudi-iranian poppet so you see this is saudi-iranian poppet so you see this is saudi-iranian poppet so you see this is a hard question so it's a very were sinking and the really worst practice and many times and because this is um like there's an underlying you if you see this is an example that you need to like a first get rid of the half and then do the search for another ha is an essential ideas for the binary search ok so just keep practice and you will be more Confessional to solve the coding Pomerance ok thank you for watching thank you for subscription to go Decker you know YouTube channel so let's keep practice and keep making progress so see you next time bye
|
Median of Two Sorted Arrays
|
median-of-two-sorted-arrays
|
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays.
The overall run time complexity should be `O(log (m+n))`.
**Example 1:**
**Input:** nums1 = \[1,3\], nums2 = \[2\]
**Output:** 2.00000
**Explanation:** merged array = \[1,2,3\] and median is 2.
**Example 2:**
**Input:** nums1 = \[1,2\], nums2 = \[3,4\]
**Output:** 2.50000
**Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5.
**Constraints:**
* `nums1.length == m`
* `nums2.length == n`
* `0 <= m <= 1000`
* `0 <= n <= 1000`
* `1 <= m + n <= 2000`
* `-106 <= nums1[i], nums2[i] <= 106`
| null |
Array,Binary Search,Divide and Conquer
|
Hard
| null |
1,508 |
hey everybody this is Larry this is me going over range summer sorted sub-arrays sums keep two of the reason sub-arrays sums keep two of the reason sub-arrays sums keep two of the reason contests yeah so basically I don't there may be wasted on doing a more clever way but given that n is only a thousand you can actually just generate all the prefix sums I mean order sums by just having a running total and then insert into in a way somewhere you sort it just so that you get two sorted order and then you just do a naive sum from left to right yeah I think this is just testin keeping it simple because you can definitely maybe play around with prefixed sums as well but you don't need to because you could just do a running sum like the way that I do here yeah and all you have to do after that is just keep it simple proof force it and then sum from left to right I hope you had a good time watching this video let me know what you think hit the like button to subscribe when trying to discard and I will see you next farm bye
|
Range Sum of Sorted Subarray Sums
|
longest-happy-prefix
|
You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed from 1**)_, inclusive, in the new array._ Since the answer can be a huge number return it modulo `109 + 7`.
**Example 1:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 5
**Output:** 13
**Explanation:** All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
**Example 2:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 3, right = 4
**Output:** 6
**Explanation:** The given array is the same as example 1. We have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
**Example 3:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 10
**Output:** 50
**Constraints:**
* `n == nums.length`
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 100`
* `1 <= left <= right <= n * (n + 1) / 2`
|
Use Longest Prefix Suffix (KMP-table) or String Hashing.
|
String,Rolling Hash,String Matching,Hash Function
|
Hard
|
2326
|
1,481 |
hello friends welcome to the coding interviews channel hope you are doing great if you haven't subscribed to the channel yet please go ahead and subscribe I have created bunch of playlists to cover various categories of problems dealing with stacks queues linked lists trees graphs and also there are several playlists to cover various pad various programming paradigms such as dynamic programming BFS DFS greedy method and so on please check them out I have uploaded the code for this problem to the github repository you can get the link from description of this video let's jump into today's problem least number of unique integers after Kerry moles given an array of integers and an integer K find the least number of unique integers after removing exactly K elements so we are given with two inputs one is an array of integers and an integer K let's say the number of integers in the array is n right and we are supposed to remove K elements and our task is what is the least number of unique integers possible after removing K elements right so that is what is our question is so for example let's go with the example 1 5 4 and K is equal to 1 is given right so in that case 5 4 there are 3 elements we are supposed to remove one of the elements right so let's say if you remove 5 how many unique elements will be there 5 & 4 unique elements will be there 5 & 4 unique elements will be there 5 & 4 right there are still 2 any unique elements will be there but what if we remove 4 there will be only one unique integer right even though there will be 2 files we are talking about unique integers right so 5 both are same so we will count only one unique integer right that is 5 right so in that particular case if we remove 4 we will be ending up with one unique integer right so but how to choose 4 instead of 5 right that is the that is what the trick here that we need to do right so let's look go ahead and look at one more example to understand it in a bit right so now there's a this is a another array for 3 1 3 to 4 right so in this case k is equal to 1 again so I am allowed to remove one element but how many choices that we have in this particular case there are 8 elements and 4 unique choices right so 4 unit says you can remove 1 2 3 or 4 but any of them any of any one of them you can remove and how many unique elements are possible so in this particular case there are 4 unit elements right 1 2 3 & there are 4 unit elements right 1 2 3 & there are 4 unit elements right 1 2 3 & 4 out of which if we remove one how many unique elements are possible right if we remove four for example before right this one there will be still four unique element so there is no change if we remove three still there is no change if there is if you remove one right still there is no change because there is one available if you remove two right there will be only 1 3 & 4 that's right there will be only 1 3 & 4 that's right there will be only 1 3 & 4 that's it right and that part is what we have to remove we need to remove two right so that these two examples should tell you something that means what we are going to do is we will start with the number to be deleted which occurred least number of times right so we will remove the number which occurred least number of times we will start there and we will be removing K such elements right so we if let's say if came or equal to 3 right if K or equal to 3 for example so to start with I will remove 2 right to start it I'll remove 2 so how many more I need to remove two more so out of 2 more I could take off two fours are two ones right even if I take of 2 4 2 ones it will be same because if I take two fours right two elements remind three and one if I take off 2 once 2 elements remind 4 and 3 so it doesn't matter what elements I need to I remove right in case of K is equal to 3 for this particular array so the case to remove the numbers which starts with least number occurrences right so that is the trick that we are going to use to solve this particular problem so for this case we need to count the number of occurrences of each integer right so I have created a map here and this for loop is going to count the number of occurrences for each element so that means for example this one right if we if I were to do the map right so it's 4 how many times it is 2 right and 3 how many times it's 3 times and to how many times it is 1 and 1 how many times it is 3 right how one is actually 2 times right yes so now we have this map what we said is we will start with the least number of occurrences right so if we sort this sort the map right sort the map that's what we are going to do so once I start the map by the number of occurrences right to 1 and it could be for 2 1 2 & 3 that's what it is all be for 2 1 2 & 3 that's what it is all be for 2 1 2 & 3 that's what it is all right so for occurred two times and one also occurred two times right in this array right and this I so this is the sorted map now we are going to remove K times right so if K is equal to three we remove this and we remove this that will be three elements right that's it so how many elements remain two elements that's what we are going to have so now that we have prepared this map we are sorting this map so this is what is sorting right so this will sort by the number of occurrences served by num occurrences right and then I initialized the map count answer to the map count right that is the total number of elements available so now we I start removing key elements so for each element in the map I am going through and see if it is less than or equal to K right just remove that many values from K and remove decrement the answer why are you decrementing the answer by one because those type of elements are gone now right that's why we are decrementing the answer by one so otherwise you just break it out so that many element whatever the answer that you have that is the answer we are going to return so basically we will remove that many or K many elements and come up with the least number of unique integers right so this is a the trick here is to count the number of occurrences and sort them in the order of number of occurrences so once you know that the problem becomes pretty simple to understand right so let's go ahead and look at the time and space complexity for this time and space all right it's a time so here we are going through the complete array one time right so we are saying the number of elements in the array we started with n right so there will be n integers right so that means to start with we took order of n time plus we are not done yet so we are going through the map now right we are not going through the array anymore we are going through the map so how many elements in the map are there we don't know that right but worst case how many elements could be there if you're given array is let's say if the given array is like this right 1 2 3 4 5 so in that particular is what we'll say ok 1 occurred once 2 occurred once 3 occurred once 4 occurred once 5 occurred once right so that means it is equal to the number of elements in the array also so worst case will be order of M right but are we going through all the elements here not really only until key elements but what if K is equal to n right still the same this will be holding good right so order of n plus order of n will be equal to the order of 2m but we are going to remove all the constants from the Big O notation we will say final complexities order and so let's go look at the space complexity now so are we using any extra space here yes we are using extra space to calculate the number of occurrences right so how many number of occurrences we said so in the worst case the map will have n elements that's what we said right for this example so space is also order of and we're using right apart from that space we are not using anything but when we talked about the time complexity we just calculated the time complexity for each here and for each here there is an important thing that we did not consider which is this statement the sorting statement right that is an important one how much a sorting would take if there are n elements the sorting would take and log in the best sort right and log n right so the total time complexity in this particular case we would say is order of n plus order n log n normally order of n will be less than order of n log n that is why we would say the total complexity is order of n log n right so time complexity is order of n log n on the whole and space complexities order and if you have any further questions please post them in the comment section below this video I will get back to you as soon as I can I have posted this code to the github repository you can find the link in the description section of this video below if you haven't subscribed to the channel yet please go ahead and subscribe and share among your friends please click on the bell icon so that you will be notified about my future videos thank you for watching I will be back with another problem soon till then stay safe and good bye
|
Least Number of Unique Integers after K Removals
|
students-with-invalid-departments
|
Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
**Output:** 2
**Explanation**: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
**Constraints:**
* `1 <= arr.length <= 10^5`
* `1 <= arr[i] <= 10^9`
* `0 <= k <= arr.length`
| null |
Database
|
Easy
| null |
242 |
hey what's up back to leak code again today i'm going to be doing the valid anagram with javascript this is asking to compare two strings and to see if they are anagrams of each other or essentially if the two words have all the same letters in them and if so just return the true if they don't have all the same letters in them regardless of order then return false so for this one i'm going to start by making a helper function oops and we'll call it sorter and we're going to input a string for this helper function and what we'll do here is we're going to call string dot split and we're going to change this string into an array with dot split then we're going to call dot sort which will sort this array and then from there we're going to join it which will change it back from an array to a string again oops and that's return and then all we need to do is return the output of this helper function comparing the two different strings s and t so b sorter s and to c if sorter t right there so if i run that works just fine and if you want i'll break this down real quick with sorter we'll go sorter and we'll pass in the string of uh we'll just say it's hello and instead of just returning this here to walk you through this we just want to console.law we just want to console.law we just want to console.law string dot split so if i hit run let's see we should be getting an output down here yep right here so you see how it changed hello into an array and if we call dot sort on that run this again we'll see that the array is now sorted and then if we join it we'll see that it is now a sorted string just like that so then all we're doing up here right is just passing in this function twice and comparing the results of this the first function here with the string of s and the second function call with the string of t and seeing if they're the same or not so it would be in this case right if we had s and t if s and t were both anagrams of hello it would just be passing in the result of the sorted string compared against the result of the other sorted string and that's it hope you like the video
|
Valid Anagram
|
valid-anagram
|
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "anagram", t = "nagaram"
**Output:** true
**Example 2:**
**Input:** s = "rat", t = "car"
**Output:** false
**Constraints:**
* `1 <= s.length, t.length <= 5 * 104`
* `s` and `t` consist of lowercase English letters.
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
| null |
Hash Table,String,Sorting
|
Easy
|
49,266,438
|
1,603 |
hey everybody this is larry this is me going over q1 of the recent bi-weekly contest 36 uh design parking bi-weekly contest 36 uh design parking bi-weekly contest 36 uh design parking system so this is actually i actually was a little bit slow on this one uh well for me and you'll see why when you see me stop this live later in the video remember to hit the like button hit the subscriber and join the discord and this problem basically it's really straightforward-ish straightforward-ish straightforward-ish uh you just have to keep track of the number of big cars medium cars and small cars um i just misread it as i don't know the thing uh in a while but um but yeah but basically you just keep track of how many of uh cars of each size we've seen uh so far and for example uh yeah big cars medium cost small car and basically that's what i did i just checked i for every uh car type that comes in i subtract it from the thing and i re right i make sure to reindex or index big medium and smaller as one two and three that's basically what i do here uh and then this makes the return type easy because that means that if after we take up a slide it has zero or more slots free that means that we added the card successfully and that's pretty much how i set up q1 uh you could watch me stop it live next right do well okay i mess with this our small story whoops hey everybody uh yeah thanks for watching this is larry uh this is me out uh hit the like button hit the subscribe button join me on discord i hope you had a great contest i hope you had a great prom uh let me know what you think let me know if you have any questions and i will see y'all next contest bye
|
Design Parking System
|
running-sum-of-1d-array
|
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the `ParkingSystem` class:
* `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor.
* `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`.
**Example 1:**
**Input**
\[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\]
\[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\]
**Output**
\[null, true, true, false, false\]
**Explanation**
ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
parkingSystem.addCar(3); // return false because there is no available slot for a small car
parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.
**Constraints:**
* `0 <= big, medium, small <= 1000`
* `carType` is `1`, `2`, or `3`
* At most `1000` calls will be made to `addCar`
|
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
|
Array,Prefix Sum
|
Easy
| null |
471 |
everyone welcome to my channel so in this video i'm going to cover the solution to this question calling code string with stratis lens and also at the same time i'm going to briefly cover the general steps we should follow in coding interview so let's get started before we start the real question for today i would really appreciate that if you can help subscribe this channel because it can help this channel to grow so thanks the other ones let's take a look at this question so give an empty string encoded string such that its encoded lens is the shortest the encoding rule is something like k bracket the encoded string where the encoded string inside the square bracket is being repeated exactly k times so note that k will be a positive integer and if a encoding process does not make the string shorter then we don't need to encode it so if there are several solutions we just need to return any of them so let's say um for example one we have three a's triple a then upward is triple a because if we just replace it like a three bracket a then it is the encoded uh the encoded format is going to be with lens 4 so it doesn't make the screen shorter so we just return the original string let's say example 2 and 3 similarly so we can replace the 5 a's with 5 and bracket 8 which can make it shorter and we have like an example four is something like this example five is more interesting because it has like a bracket a b c and then there's another bracket outside of the outside of it so let's see the constraints so the lens is between one two one 150 and as only contains lowercase english letters so the first step in the code interview is try to understand the question if there's anything unclear clarify with the interviewer and also think about some match cases so until now i think we pretty much understand what it is asking us to do some ash cases what i can think of is if the lens is uh the length of the input string is smaller than five then there's no way for us to have a encoded string to make the original string to be shorter so i would say the first edge case i was i would check is if the lens is smaller than 5 we just return the original string and that's it so next part is about finding solution so this is a pretty difficult question uh i thought about the solution and then wrote some code down so let's go through the solution and then briefly go through this visual code so the solution we actually here we actually used like a dynamic programming solution so we defined this uh dp array um like a 2d array so the dp array uh dp start and end means this one it means um the shortest encoded string um encoded string for i'll say this is let's say input is as from start to end encoded format so dps start and is the started encoded format for the substring for s from start to end so both start and end are inclusive so how are we going to compute the dp star to end actually what we could do is we just decompose it into the problem so like dp start to end is actually any uh let's say it is like the minimum the shortest within dp start to p plus dp p plus 1 to the n so p is anywhere uh p is between start and uh and minus one so that's essentially uh the dp formula how we are going to leverage the results from the sub problem to recompose into the solution to the original problem so it'll be something like that so let's go through this big piece of code to further understand the solution so uh essentially first of all we are going to check the ash case um and then we are going to define the dp 2d dp array um which has like the first dimension as the length second dimensions as the lens as well so uh we are going to iterate through um we are going to iterate through each of the lines of the substring i try to try each of the start points and then we are going to compute the corresponding dp uh the result for the dp uh i'll say dp position so uh for first of all we try from the lens as minus one uh sorry we have we tried the lens as one and then until we iterate through all of the lens which is the longest lens is just the length of the original input string itself so first of all we define the start which is uh the start here like on line eight and the and then the end is uh computed from start plus length minus one and we notice no you know noted it is worse to know that the end is inclusive so first of all we get the shortest string i try to get the shortest string which is just the substring itself so if the lens is the length of the less of the current string your substring we are currently looking at it is smaller than 5 then there is no way for us to actually find the encoded format to make it shorter so we are just going to have the dp start to end set as the original substring and then we just continue otherwise if the lens is larger or equal to 5 potentially we can have like an encoded format to make the string for a string shorter so but we still need to dive into it so let's see how we do it so first of all we will just try to have like a uh like connect shortest with the shortest and find if there and try to find like the repeated point so this one might be a little bit harder uh for you to understand so let me give you an example to try to explain this one so let's say if we have um a b c d e so this one actually there's no repeated pattern we could find from it so what we do is we if we connect this one like uh if we do shortcuts plus shorted it's going to be something like this and then we just try to find the shortest within this new string starting from the first point then it is going to be able to find like the repeated position which is starting from um like the end of the original string plus one so um so if that is the case actually it means there's no repeated pattern for us to leverage so we are just not going to jump into this if branch to make the make a like encoded version for it otherwise let's say i give you another example let's say you have um a let's say we have five a's so if we have five a's um and then we try to find the repeated position so when we try to find the repeated position we find that repeated position uh return is one so this means uh starting from one uh it is like starting so starting from one that's the that's where we just try we find the original uh string and it also means that we can probably uh have a repeated pattern with the lens as one so if we have like a repeated position which is smaller than the length of the original string then it we just find like a repeated pattern which we can leverage to make the string to be shorter so in this case first of all we record down how many of the patterns are repeated which is computed by shortest dot lens divided by the repeated position so for the example for this one the repeated position is uh actually one let me for this specific example and uh the how many number of the repeated patterns are up here it is actually five which is um the length is five and the repeated position is one so this one it gives us like a five and then what we do is uh we have like the left bracket and the closing bracket and also what we do is uh we include uh these the we include the repeated pattern i would say the into this uh left and right bracket so why do we use dp start to end so that is because um there could be something like let's say for example five there could be something like this it's like a bracket within bracket uh like two layer of the bracket so that's why we use dp uh like the dp result instead of leveraging the substring itself so this is like the most juicy part for this one except the dp formula and after this what we do is we try to enumerate out like the all of the middle point and see if uh if any of the if you try to decompose the original problem into sub problem if there is any way to get us like a shorter encoder string if there if it is true then you're just going to set the shortest to be like a shorter version of the encoded string and finally we just set dt start to end as the shortest and finally what we are going to return is dp from zero to the end of the string so that's essentially the solution to this uh question and uh it is going it is like uh let's see what is the runtime for it so the runtime essentially there is a two layer of the for loop it has like a n square and also within each of the so we for each of the like a start to end we need to enumerate all the middle points so it makes it to be n cubed but actually what we did is uh we have uh so we have like a string manipulation so for the string manipulation it makes it a little bit um it makes it a bit i would say a bit slower so in this solution if we consider like the string manipulation stuff like we connect the strings then it is good then it is going to be something like uh because for this one the operation is going to be kind of like an old n so we are looking at n to the power of 4 for this specific solution so um that's pretty much it about the runtime of this solution and um what is next okay so for the coding part we already explained the piece of code how it works but in the real coding interview care about the correctness readability and don't be too slow when doing the coding work and also last time a lot the last thing is don't forget to do some testing so try to set some task cases uh to make sure you have good enough test coverage so other than that i think uh we should be good for this question so if you have any questions regarding the code or regarding the solution whatever feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
|
Encode String with Shortest Length
|
encode-string-with-shortest-length
|
Given a string `s`, encode the string such that its encoded length is the shortest.
The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. `k` should be a positive integer.
If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return **any of them**.
**Example 1:**
**Input:** s = "aaa "
**Output:** "aaa "
**Explanation:** There is no way to encode it such that it is shorter than the input string, so we do not encode it.
**Example 2:**
**Input:** s = "aaaaa "
**Output:** "5\[a\] "
**Explanation:** "5\[a\] " is shorter than "aaaaa " by 1 character.
**Example 3:**
**Input:** s = "aaaaaaaaaa "
**Output:** "10\[a\] "
**Explanation:** "a9\[a\] " or "9\[a\]a " are also valid solutions, both of them have the same length = 5, which is the same as "10\[a\] ".
**Constraints:**
* `1 <= s.length <= 150`
* `s` consists of only lowercase English letters.
| null |
String,Dynamic Programming
|
Hard
|
394,726
|
1,539 |
good morning in this question we are gonna see Keith missing positive number although it is marked as easy but if you go on to the integrities of this question to find out okay how to do the better solution then it's actually a medium but yeah let's see that the problem says that we are given an array called error of positive integers sorted in the strictly increasing order okay of let's understand it from this example really quickly it just says that we are given an array let's say 2 3 4 7 and uh let's say if we write the numbers down one two three four five six seven eight nine ten eleven twelve thirteen fourteen like up till then so what is the fifth number from this array so you can easily see one is missing but the two is not missing three is not missing 4 is not missing 5 is missing 6 is missing seven is not missing eight is missing nine is missing so one five six eight nine is the fifth missing number in this array so we just have to return a 9. right let's quickly see the next example too if the r is one two three four if we write the number down like one two three four five six seven eight nine ten eleven twelve s like this so we will see okay one is not missing two is not missing three is not missing four is not missing five is missing six is the second missing element in this array cool now we have got the idea of the question what the question is saying but let's see how we're gonna solve this so first let's see okay if we have this constraints our length is 1000 and my K is 1000 so one option is very optimal one to be sure is that we can easily solve it by using these two pointers that okay we can see and iterate on my array and my those n numbers simultaneously and see if I'm pointing at let's say n and I'm pointing at my array and I'm pointing at my number n I'll see if they are matching which means that element was not a missing element if they're not matching which means here example I am pointing at one and starting of the array at two if these both would have been same which means that my particular element of n it is not missing but they are not same for example in this case my one is not same as 2 which means my one is a missing element which is not into as both are sorted so it's for sure that everything will come before which means that okay it was sorted so it should like if one would have been in the array ARR so it should have been earlier only so it would have been in the starting itself if one is not in the starting which means one was not present at all so which means my one was a missing element so my K was 5 I got one missing element so I reduced my K to 4. now I moved on to the next one two and two I just moved my n pointer just ahead two and two both are same which means that it's not a missing element so my K remains as it is cool my T remains as it is I move my next pointer to 3. cool both are still same still my K remains as it is I move my pointer ahead I move whenever I found it's same I move both of my pointers cool now it's also same cool no worries my T is still same now I just move my pointer ahead now you can easily see that it's different five and seven are different right so my five is a missing element so I reduce my K to 3 because I have found another missing element now my K is 3 pretty cool again it's six and seven right still it's not same which means it's a missing element so I reduce my K22 cool again my K is two now I am at this location same it's not a missing element so I carry remain same then I move my pointer again right it's 8 it's 11 it's not same which means it's a missing element so I reduce my k to one now my K is one it's at nine it's at eleven not same so I reduce my K to zero oh K has been reduced to zero this means that I need to find K which means five missing elements and my K is now zero which means I have found fifth missing element right now so I can just return this 9 and yeah it's my answer so you can just see that okay I just found my fifth missing element as nine and I made this whole thing by just using these two pointers and iterating on this n array only once as you can see it one step at a time I'm just moving ahead of this n I'm moving ahead of this in so its complexity is O of N and as no space is using just two pointers so I can just say it's of one space but in the problem itself it said that okay can you do it in less than open which means less than of n is always login is it so first thing it mind comes is okay we have to do it over login so the first thing of log n and one thing is sorted okay another thing you have to do an off login sorted off login sort it off login binary search that's the reason we are trying not sure we are trying to use binary search because it's sorted and we have to do it in login that's it that's the main intuition why we thought of balancing binary search at the first place now where we think of final search okay what we have L pointer our pointer mid cool pointer R pointer hey Aryan usually we take R pointer as the end of this array right which would have been four why you took r equal to 5 which means Beyond this array can you give the answer for that oh yeah for sure but we will see it later not now else it will confuse you so we take my L pointer as the starting of the array and R Ponder is the ending which means the fifth index which means just outside this array right cool I just find the meat out of it which is for sure two which is L plus r by two okay I found the mid now comes the interesting part now we have found the mid but the next step like in a binary search what's the next step we have L we write while L is less than R then we compute mid okay we completed mid but then the main operation comes that we have to shift at l or we have to shift that R beyond the mid right now how to decide on the shifting part here comes the picture if we clearly see what we have with us is something like this right so it just says okay if I am specific to particular index let's say I'm standing here so what it says is I am standing at the index 3 and the value is 7. what it says is that if I am standing at 7 and the index is 3 which means that three elements have come before it which means that it is the fourth element if it is the fourth element and if everything would have been sorted if everything would have been fine okay so the fourth element would have been a four because it is like one two three four so instead of a 7 if everything would have been fine so the fourth element would have been a four because we would have started writing like one two three four no missing elements nothing missing everything is fine everything is cool but it is seven and not a four it should have been a four but it is a seven which means that three elements seven minus four three elements are missing before this particular thing so my at index three if I have value 7 it indicates that before this which means including this I have three because it is if index is 3 which means it is the fourth element so it's actually a fourth element so it just shows that okay I have three missing elements before it's the reason that it will help us to find because now you thought what we it shows us number of missing elements which means that it showed me that but to make sure me it has three missing elements before it now if I am at seven it showed me okay one was missing five was missing and six was missing but it just showed me the number okay I just have three missing elements before it and I showed you right now how so basically if the number of missing elements before it would be nothing but a i minus of I plus one I plus 1 indicates okay actual number of elements if I is 3 which means four elements have would have been there and a i is just actual element present at that index here it is seven I was three plus one which means four now it gives me three okay now you got it okay how you will find number of missing elements which if you are standing at that index now let's move back to the problem what the problem said was okay if I'm standing at L I'm standing at R I got the mid from that mid I can easily find okay if I'm standing at Mid what are the number of missing elements before it if I have this whole thing what are the number of elements before it said okay it has one missing element it says it has one missing element now comes an interesting part so it says that in this part there is only one missing element which means that I need to find the fifth missing element which means the which means that the remaining four missing elements are in the next part it's for sure that one missing element is in the left part so remaining four will be in the right part and I want fifth missing element so I just say okay missing a number of elements are one which is actually less than my K which is 5 which is the fifth missing element I need to found so I just increased my L from 0 to Mid plus 1 as we do in the binary search now the condition was the condition here right here I found the missing elements which was before this range which means from L to Mid number of missing elements if it is less than the required missing elements so I move my L forward if it would have been more I would have moved my L backwards let's see now I moved my L forward because see mid was here right mid was here I just moved my L by mid plus one now my L is here my R is here right so mid is now no worries at all number of missing elements in this range would be nothing but 11 minus 4 plus 1 which is 6 it is more than five it just says okay number of missing elements in this range would be six but I want fifth missing elements so I need to reduce my R cool no worries I reduce my R to Mid now my L is 3 R is four it will be actually three okay now number of missing elements in this range will be 7 minus 3 plus 1 which is three it's actually less than k right so I need to move my l cool no worries I moved my L now my R is here so my mid will also be here now I checked okay but why I will check and not check out it because L is equal to R in the case of binary search Capital donation while L is less than R now L has become equal to R so a loop will break now one thing I have ratio condition okay my L is equal to R which means my L is pointing to 4 and the element is 11. r and what to do with it what will I do with it is nothing says about the answer how will you say okay we got to a point where L is equal to R we are at index which is right here right at the index 4 and the element is 11. now we will try to find what will be the keyth missing element how let's see here as you can clearly see that we landed finally after balances completed at L equal to 4. now let's take an example that we have to find our kth missing element right so let's imagine that element to be Z now hypothetically what our answer says is C what was l what was it l was just the location of a hypothetical missing element L was just the location of our hypothetical missing element so if L versus element so it means that before that thing four elements were present these four were present so and how many number of elements we need to have we have K missing elements four elements were present before it my element would come after here so basically if let's say if I have the hypothetical element which is the create missing element this L equal to 4 represents okay if the values let's say Z so Z would have been here now if Z would have been here so I can clearly say okay I have these four missing elements I have these four existing elements and how many number of missing elements were there five so basically if I just say okay it is one two three and four so basically after these five elements I will have my number which means I'll just have a z of four plus five to understand why it is because I just imagine okay my Z is at the location right here where L equal to 4 which means that the previous elements for existingly there so basically previous elements will for sure be there and let's say it's not a two three four seven let's say it's one two three four or just four elements and I want five more elements to get to this location Z so the actual value of Z will be nothing but 9 which is 4 plus 5 4 is because of it has four previous elements and five are actually the missing elements so it gets a 9 which is actually a location see if I actually it was 11 right if I replace it with 9 so basically 9 was the actual location if 9 would have been the answer it was the actual location of L equal to 4 so my L equal to 4 showed me okay what was the 9 location and I know okay previously I had four elements and five elements was missing so I just added a five so I got a nine thus we got the 9 and thus we have the answer now you will see okay that we showed but one thing we earlier said okay I will show you why we took my r as not n minus 1 but a n it's because the missing element it can also lie outside the array see when we choose the bounds such that L and R we choose the bound such that it's whatsoever will happen between these bounds right if L and R is L is zero and R is n minus 1 so it will it says that okay everything will be inside the array but our existing element or see the missing element it can be outside the array as well it's the reason we took our r as n and not n minus 1. I hope that you guys understood the entire logic and entire concept behind it let me show the code it's very simple it just says that okay while my L is less than R I just need a mid the prime condition I just found the element index plus 1 if it shows the number of missing elements it shows number of missing elements from L to Mid if this is less than K so I need to include increase my mid f it is not then I just bring my R to Mid and ultimately as I showed you guys that why we need to do a l plus r l plus K it's because I have four elements before it and the actual location of Z which is actually after we know it's nine so before after that we need to have five add five new missing elements thus I did a l plus K and for sure my L and K both are L and R both are same ultimately it will lie at the same place so yeah L plus K would be what is what we return so the complexity will be o of log n and thus will reduce from n to a plugin I hope that you guys liked it if yes then do hit the right button it motivates me a lot and yeah goodbye take care
|
Kth Missing Positive Number
|
diagonal-traverse-ii
|
Given an array `arr` of positive integers sorted in a **strictly increasing order**, and an integer `k`.
Return _the_ `kth` _**positive** integer that is **missing** from this array._
**Example 1:**
**Input:** arr = \[2,3,4,7,11\], k = 5
**Output:** 9
**Explanation:** The missing positive integers are \[1,5,6,8,9,10,12,13,...\]. The 5th missing positive integer is 9.
**Example 2:**
**Input:** arr = \[1,2,3,4\], k = 2
**Output:** 6
**Explanation:** The missing positive integers are \[5,6,7,...\]. The 2nd missing positive integer is 6.
**Constraints:**
* `1 <= arr.length <= 1000`
* `1 <= arr[i] <= 1000`
* `1 <= k <= 1000`
* `arr[i] < arr[j]` for `1 <= i < j <= arr.length`
**Follow up:**
Could you solve this problem in less than O(n) complexity?
|
Notice that numbers with equal sums of row and column indexes belong to the same diagonal. Store them in tuples (sum, row, val), sort them, and then regroup the answer.
|
Array,Sorting,Heap (Priority Queue)
|
Medium
| null |
295 |
hi folks today let's talk about the code 295 find median front data stream okay fun fact about this problem i added this problem to the code say second between builder is um this guy and my purifier is also sky yes i edit about like 10 problems to lead code yeah so let's take a look at this problem if you haven't really reached the pro the problem take some time so this problem is let's say we have a data stream for example we consume the one we consume the two now we want to find the median is one plus two divided by two so it's one point five next we consume three there's three elements so the median is the second element so it's two so let's see how to solve this problem so now if solution is we can maintain a sorted vector so when you add a num and the time complexity is o and since it's a vector if you insert a element into the vector you need to move all elements after it the time complexity of fun medium is all one but we let's see a better solution we can use two heaps one is maximum tip which used to store small elements another one is minimum heap which is used to store larger elements what we want to do is we want to maintain a property once the total elements it's an even number we want to put the smaller elements into the maximum heap and larger elements into the minimum heap then the median is the top element of the maximum heat plus the top element of the minimum heap and divided by two if the size of the total elements is an odd number then we put the actual number in minimum heap so the minimum and so the median is the top element of the minimum heap okay let's see how to implement it let's take a look at this example first we're at num2 okay anyway we will put a number into the minimum heap first then we will move top element from minimum heap to maximum heap okay now if size of minimum heat is less than size of maximum heat we will move top element of maximum heat to minimum heat okay now what's the medium since it's odd number so the top element of minimum heap is a medium which is two okay next we add three anyway we add push the screen into the minimum heap now we move the top element of the minimum heap to maximum heap now what's in median since the size of maximum heap is same as size of minimum heap so the median is 2 plus 3 divided by 2 which is 2.5 which is 2.5 which is 2.5 okay next let's add 6 anyway we push 6 to minimum heat then we do the same move top element from minimum heat to maximum heat okay now the size of minimum heat is smaller than the size of maximum heat so we move the top element from maximum heap to minimum heap okay now the median here is top element of minimum heap which is three next we push one and we move the top end element in the minimum heap to the maximum heap okay now the sides are same so the medium median is two plus three divided by two okay at last we push four we do the same we move three to maximum heap now the size of minimum heap is smaller than the size of maximum heat so we move straight back to the minimum heap now the median is the top element of minimum heat which is three okay now let's implement it in the code the coding part is pretty easy as long as we know uh on what would happen so let's create two heap in c plus let's priority q okay std less okay this is um maximum heat let's also add a minimum heap okay let's implement fun median first so if the size is same we know that submitting is on the top elements the average of the top element okay otherwise the median is the top element of the minimum heap okay let's implement and now first anyway we need to push the element into the minimum heap then um we move the top element from mid minimum heat to maximum heat okay let's do this then we check if the size of minimum heap is less than the size of maximum heat okay and we should move the elements okay let's see if we compiles cool let's submit nice so for this problem we can use two heaps to solve our questions thanks
|
Find Median from Data Stream
|
find-median-from-data-stream
|
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
* For example, for `arr = [2,3,4]`, the median is `3`.
* For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`.
Implement the MedianFinder class:
* `MedianFinder()` initializes the `MedianFinder` object.
* `void addNum(int num)` adds the integer `num` from the data stream to the data structure.
* `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input**
\[ "MedianFinder ", "addNum ", "addNum ", "findMedian ", "addNum ", "findMedian "\]
\[\[\], \[1\], \[2\], \[\], \[3\], \[\]\]
**Output**
\[null, null, null, 1.5, null, 2.0\]
**Explanation**
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = \[1\]
medianFinder.addNum(2); // arr = \[1, 2\]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3); // arr\[1, 2, 3\]
medianFinder.findMedian(); // return 2.0
**Constraints:**
* `-105 <= num <= 105`
* There will be at least one element in the data structure before calling `findMedian`.
* At most `5 * 104` calls will be made to `addNum` and `findMedian`.
**Follow up:**
* If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
* If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
| null |
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
|
Hard
|
480,1953,2207
|
867 |
good morning min what is up nerds and don't worry I'm probably the biggest nerd here today I'm working on transpose matrix so I need you to know how to do this before I did a problem I posted yesterday my slack channel called rotate image so that was basically prerequisite so I'm gonna go over this one real quick this one's really simple I'll actually have to do this in one of my CS classes in a bash script so Java makes it a lot easier in my opinion so it reads given a matrix a returned the transpose of a matrix is the matrix flipped over its main diagonal switching the row and column indices of the matrix so basically we're just you know if you could imagine you completely like turn it into a 3d dimensional yeah through a 3d dimension so negative one is over here and negative 18 or well that's that looks wrong cuz that's not negative make team over here okay anyways they made a mistake and it doesn't have to be n by n so I did a test case where is it I did a test kit oh I didn't not at this time I'm gonna add it now mm-hmm so I wanted I'm gonna add it now mm-hmm so I wanted I'm gonna add it now mm-hmm so I wanted to do a head by n test case so 10 11 12 and let's add that bracket so that's what we're gonna test against and let me show you guys on my iPad so the only ones that are going to be swapped are the ones whose eye element her eye index is different than the J index so as you see here one has an eye of 0 and J and 0 so it stays the same for 5 it's one and one so it stays the same and 9 is 2 and 2 so it stays the same but when you have a n matrix only born into one in 12 save status in because it's 0 + 0 + 3 + 3 so status in because it's 0 + 0 + 3 + 3 so status in because it's 0 + 0 + 3 + 3 so let's the 7 here is you know - 0 but now let's the 7 here is you know - 0 but now let's the 7 here is you know - 0 but now it becomes 0 - so that's all we have to it becomes 0 - so that's all we have to it becomes 0 - so that's all we have to do we just have to swap the jason-2 eyes do we just have to swap the jason-2 eyes do we just have to swap the jason-2 eyes so that's how we're gonna solve this problem so let's jump right into the code so let's grab the rows lengths so in rows equals a dot length you guys should know how to do this by now and the columns is a 0 dot length and let's create our 2d matrix that we're going to return new and let's give it we have to swap the remember we're swapping the columns and rows so the columns comes this time we're going to be returning mmm three rows instead of four rows is time so we got to swap the columns and rows so column schools where rows normally does and rows closed for comms normally does and then we're just going to loop through where eyes going to we're going to loop through the rows first so it's going to be two for loops so it's gonna be O of N squared running time and then it's just going to be open space complexity because we had to create a new matrix and or JJ's gonna be for the calm we're gonna loop through the columns so J less than columns and then we just have to set so we remember we're swapping to J and I values so matrix J of I equals a I of J and boom we're done it's transposed we just have to return the matrix you know solving this for you guys and I actually run go through the bugger real quick and I forgot and equals so it's going so fast so if we go through the debugger real quick I'll just show you guys how this works hopefully it helps you visualize it really recommend Linko premium if you guys are starting for interviews um it just helps a lot so one's gonna go here just like on my iPad let me see if I can pull them both up side by side so no it's not gonna work unless I do this sorry no that's not gonna work all right let's just go through it so twos gonna go there three is gonna go right here and then four it's gonna go here in the first row second column and then five seen going the second row second column and on and I don't want to loop to the whole thing I'm sure you guys get it by now but thanks for watching please subscribe if you have it already and I'll be posting more videos and if you guys have any questions let me know if you guys want me to do any specific problems please let me know and I will and I'll see you guys in the next video thanks for watching
|
Transpose Matrix
|
new-21-game
|
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`.
The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\]
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\]\]
**Output:** \[\[1,4\],\[2,5\],\[3,6\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 1000`
* `1 <= m * n <= 105`
* `-109 <= matrix[i][j] <= 109`
| null |
Math,Dynamic Programming,Sliding Window,Probability and Statistics
|
Medium
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.